循环用户输入问题

时间:2018-02-04 17:57:44

标签: python python-3.x

我有一个学校练习,我必须写一个程序,当用户输入一个整数时输出'奇数'或'偶数'。保持循环,直到用户按Q停止程序。到目前为止,我有这个;

while(True):
    num= int(input("Enter a number"))
    mod= num % 2
    if (mod > 0):
            print("This is an odd number")
    elif (mod == 0):
            print("This is an even number")
    else:
            print("Bye")
            exit()

但是,由于Q不是整数,因此它给出了ValueError。我该怎么做这个练习?感谢

2 个答案:

答案 0 :(得分:3)

int函数引发ValueError,我们可以使用try - except子句来捕获它:

while(True):
    inp = input("Enter a number"))
    if inp == 'Q':
            print("Bye")
    else:
        try:
            num = int(inp)
        except ValueError:
            print('Invalid input')
            continue;
        mod= num % 2
        if (mod > 0):
            print("This is an odd number")
        elif (mod == 0):
            print("This is an even number")

然而,代码并非真正" Pythonic "。例如,您编写了mod > 0,但由于这里只有01两种可能性,我们知道在这种情况下它是1。我们无需检查1,我们可以检查真实性。

另一个方面是mod == 0中的elif。由于我们知道如果mod > 0,则表示mod == 0,因此我们可以使用else代替if。通常不会在whilewhile True: inp = input("Enter a number")) if inp == 'Q': print("Bye") exit() try: num = int(inp) except ValueError: print('Invalid input') continue; if num % 2: print("This is an odd number") else: print("This is an even number")中编写括号(除非更改已检查表达式的语义)。所以我们可以使用:

{{1}}

答案 1 :(得分:2)

在我做任何事情之前,我通常会使用user_input = input()

这是固定版本:

while True:
    user_input = input("Enter a number")

    if user_input == "Q":
        print("Bye")
        exit()

    num = int(user_input)
    mod = num % 2
    if (mod > 0):
        print("This is an odd number")
    elif (mod == 0):
        print("This is an even number")
相关问题