如果输入不是特定类型,则打印..(Python)

时间:2017-12-07 17:02:00

标签: python python-3.x

我想添加" if"声明到我的代码。如果"猜测"不是整数,打印("您没有输入数字,请重新输入")然后从输入区域而不是起点重复代码。以下是我的尝试,但是当我在猜测输入中输入非int时,会出现ValueError。提前谢谢!

#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue


    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")

2 个答案:

答案 0 :(得分:1)

使用tryexcept

for guessesTaken in range(1, 7):
    try:
        guess = int(input())
    except ValueError:
        print ("You did not enter a number, please re-enter")
        continue

因此,您尝试将输入转换为整数。如果这不起作用,Python将抛出ValueError。您发现此错误并要求用户再试一次。

答案 1 :(得分:0)

您可以尝试一个简单的while循环,等待用户输入数字。例如,

guess = input("Enter a number: ") # type(guess) gives "str"

while(not guess.isdigit()):  # Checks if the string is not a numeric digit
    guess = input("You did not enter a number. Please re-enter: ")

这样,如果他们输入的字符串不是数字,他们将根据需要多次收到提示,直到他们输入一个整数(当然是字符串)。

然后您可以像以前一样将数字转换为整数:

guess = int(guess)

例如,请考虑以下情况:

"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer