显示try的结果,除了整数检查作为字符串

时间:2013-07-31 14:57:38

标签: string exception python-3.x

我需要一个函数来检查不同的用户输入变量是否为整数。 结果应在最后确认给用户。 检查的工作原理是它保持循环直到输入整数, 但无法显示结果......

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))

2 个答案:

答案 0 :(得分:0)

没有答案,所以我只是玩这个和嘿presto,它有效...

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))

答案 1 :(得分: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