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

while True:

x = input('Input an integer: ')

if x.isdigit():

break

else:

print 'Please input an *integer*'

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

while True:

try:

x = input('Input an integer: ')

x = 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
相关资源
相似解决方案