繁体   English   中英

如何在python中创建while循环输入以仅接受1或2作为输入?

[英]how do create while loop input for accept only 1 or 2 as input in python?

x = 0
while not in range(1,3):
    x = input("Choose1 or 2 : ")

我多次尝试此代码只接受 1 或 2 个值。 但是在输入正确的输入后我未能停止循环。 请帮我修复它。

您的代码有两处错误:

  • 您没有在while循环中检查x的值。
  • input语句的结果是一个字符串,因此您不能在不将其显式转换为 int 格式的情况下将其与 int 进行比较。
x = 0
while x not in range(1,3):
    x = int(input("Choose1 or 2 : "))

while not in range(1, 3):检查变量while not in range(1, 3):因为您没有在该语句中定义任何变量,

所以你应该输入一个有效的语句,像这样

while x not in range(1, 3):

或者

while not x in range(1, 3):

其次, input('...')将始终返回str类型,而不是int ,因此您应该将其更改为

x = input('Choose 1 or 2: ')

所以你的完整代码将是:

x = 0
while x not in range(1,3):
    x = int(input("Choose1 or 2 : "))

如果x不是 1 或 2,您可以添加异常,如下所示:

x = int() #same as x = 0
while x not in range(1, 3):
    try:
       x = int(input('Choose 1 or 2: '))
    except:
       print('Chosen number is not 1 or 2')
    if x not in range(1, 3):
       print('Chosen number is not 1 or 2')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM