0

I need a function to check that different user input variables are integers. The results should be confirmed to the user at the end. The check works in that it keeps looping until integer is typed in, but cannot get the results to display...

def chkint(msg):
    while True:
        try:
            n = input(msg)
            return(int(n))
        except ValueError:
            print("Please enter an actual integer.")


number1 = input (chkint("Please enter first value:"))

number2 = input (chkint("Please enter second value:"))

results = (number1, number2)

print ("I have accepted: " + str (results))
4

2 回答 2

0

将其投射到int()一个try:块中是检查数字的好方法。在您最初的尝试中,您要求输入其消息依赖于进一步的输入。

错误的简化版本:

def getMessage():
    return input()   # this asks the user what to ask the user for

input(getMessage())  # this waits for getmessage to finish before asking the user

正如您所做的那样,删除input()语句是最简单的解决方法。
但更易读的修复方法是chkint(msg)根据字符串是否为数字,只返回 true 或 false ,就像这样

def chkint(msg):   # returns true if the string can be converted, false otherwise
    try:
        int(msg)
    except ValueError:
        return False
    return True
于 2013-08-01T18:56:09.453 回答
0

没有答案,所以我只是在玩这个,嘿,它的工作原理......

def chkint(msg):
    while 1:
        try:
            n = input(msg)
            return(int(n))
        except ValueError:
            print("Please enter an integer.")

number1 = chkint("Please enter first value:")

number2 = chkint("Please enter second value:")

results = [number1, number2]

print ("I have accepted: " + str (results))
于 2013-07-31T18:11:28.877 回答