在python中,如果输入不等于1-4,如何重复输入提示?

在python中,如果输入不等于1-4,如何重复输入提示?,python,Python,这就是我到目前为止所做的: userNum = int(input('How many perfect numbers do you wish to sum? (1-4)')) while userNum != 1 and userNum != 2 and userNum != 3 and userNum != 4: userNum = input('You did not enter a number 1-4! Try again!') if userNum == 1: pri

这就是我到目前为止所做的:

userNum = int(input('How many perfect numbers do you wish to sum? (1-4)'))
while userNum != 1 and userNum != 2 and userNum != 3 and userNum != 4:
    userNum = input('You did not enter a number 1-4! Try again!')
if userNum == 1:
    print('Sum is 6 = 6')
elif userNum == 2:
    print('Sum is 6 + 28 = 34')
elif userNum == 3:
    print('Sum is 6 + 28 + 496 = 530')
elif userNum == 4:
    print('Sum is 6 + 28 + 496 + 8128 = 8658')

如果输入的数字不是1、2、3或4,则会重新提示,但如果输入指定的整数之一,则不会退出while循环。有什么建议吗?

输入返回一个字符串,您将其与int进行比较

userInput = 0
while userInput not in [1, 2, 3, 4]:
    userInput = int(input('Enter a number'))

用户已经将其转换为整数。他们将第一次调用input()的输入转换为整数,但没有将随后调用while循环中的input()转换为整数。这不是问题。当你发现答案正确时,别忘了接受它。