可以使用字符串str的isdigit方法判断字符串是否是一个仅有数字组成,也就是整数。如果是整数退出while循环,否则继续请求输入。

1
2
3
4
5
6
while True:
    = input('Input an integer: ')
    if x.isdigit():
        break
    else:
        print 'Please input an *integer*'

也可以使用try-except语句。如果输入的字符串是整数,那么它可以用用int()函数,转换为int类并退出循环,否则会出现ValueError,可以使用try-except语句捕获ValueError,然后继续请求输入。

1
2
3
4
5
6
7
while True:
    try:
        = input('Input an integer: ')
        = int(x)
        break
    except ValueError:
        print 'Please input an *integer*'

相关文章:

  • 2022-12-23
  • 2021-07-04
  • 2021-11-14
  • 2021-07-09
  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2021-08-23
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案