我如何做到这一点,以便当用户输入一个数字来检查它是奇数还是偶数然后代码要求用户再次输入1或2

时间:2016-01-15 15:21:37

标签: python python-3.x

print ("[1] Identify, [2] quit")
user = int(input())
while (user) == 1:
    num = int(input("Enter a number: "))
    if (num % 2) == 0:
        print("{0} is Even".format(num))
    else:
         print("{0} is Odd".format(num))    
if (user) == 2:
    quit()

代码首先要求用户输入1或2,然后代码会要求用户输入一个数字,然后代码会说这个数字是奇数还是偶数但是我试图让它成功这样,在用户输入数字以检查它是奇数还是偶数之后,它再请求输入1或2。

2 个答案:

答案 0 :(得分:0)

您需要将前两行放在循环中。这是一种方法:

while True:
    print("[1] Identify, [2] Quit")
    user = int(input())
    if user == 1:
        num = int(input("Enter a number: "))
        if (num % 2) == 0:
            print("{0} is even".format(num))
        else:
            print("{0} is odd".format(num))
    elif user == 2:
        break
quit()

答案 1 :(得分:0)

最好的方法是将它全部放在while循环中,如果输入2就退出:

while True:
    user = int(input("[1] Identify, [2] quit "))
    if user==1:
        num = int(input("Enter a number: "))
        if not num%2:
            print("{0} is Even".format(num))
        else:
             print("{0} is Odd".format(num)) 
    else:quit()