如何避免ValueError并在python2中仅获取整数输入?

时间:2015-02-24 17:26:46

标签: python python-2.7

python valueerror

#!/usr/bin/env python

# getting user input
height = int(raw_input("height: "))

while (height < 0 or height > 23):
    height = int(raw_input("height: "))

# building the "pyramid"
spaceCount = height
hashCount = 1

for i in range(height):
    assert height != 0
    hashCount += 1
    spaceCount -= 1
    print " " * spaceCount,
    print "#" * hashCount

如果输入不是整数,代码应该一直提示用户。但是如何?

2 个答案:

答案 0 :(得分:1)

你需要捕捉异常。

 height = 24
 while (height < 0 or height > 23):
     try:
        height = int(raw_input("heightL "))
     except ValueError:
        print "Height needs to be an integer. Try again."

答案 1 :(得分:0)

您可以在无限循环中读取输入,等待用户输入有效整数。例如:

while True:
  try:
    val = int(raw_input("Enter an integer:"))
  except ValueError:
    print "I said an integer"
  else:
    # ValueError was not thrown, which means the user entered a valid integer
    break