首页 > 解决方案 > 如何获得正确的号码?

问题描述

--Python 这段代码有什么问题?

a=int(input('enter a number'))
b=list(range(1,11))
if a not in b:
   int(input('enter a number'))
else :
   print('ok')
    

输出:

 enter a number 89
 enter a number 8

标签: python-3.xlistfor-loopwhile-loopuser-input

解决方案


请进一步解释您正在尝试做什么,如果您尝试为“8”的第二个输入输出“OK”,那么您需要更改此代码的逻辑。

a=int(input('输入一个数字'))

这一行打印“输入一个数字”,然后你的 if 语句检查它是否在 b 内,但如果不是,它再次打印“输入一个数字”而不用它做任何事情,如下一行所示:

int(input('输入一个数字'))

如果您希望代码多次运行 if-else 块,请尝试使用 for 循环或 while 循环。

  • 另外,请注意您没有再次将输入放入变量 a 中。

编辑:试试这个代码:

    print('enter a number')
a=int(input())
while a not in range(1,11):
    print('enter a number')
    a=int(input())
else :
   print('ok')

推荐阅读