【发布时间】:2019-10-11 14:29:19
【问题描述】:
我正在用 python 做一个简单的猜谜游戏,并试图在用户输入任何不是整数的输入时创建一个“无效输入”消息。
我尝试在 if 语句中只使用“int”来处理所有整数,但这不起作用。 我知道我的语法错误。我只是不确定正确的语法是什么。
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
这是我遇到的错误。我的代码中可能还有其他一些错误。
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
【问题讨论】:
-
if 条件后忘记加冒号
:,因此出现语法错误 -
好的,我在
if语句之后修复了缺失的:。现在我收到一条消息``` Invalid Entry。请输入一个介于 1 和 5 之间的整数:``` 即使在输入任何数字之后也是如此。 -
在给定in this answer 的情况下,您最好使用例程
sanitised_input。特别是,请致电sanitised_input('Guess a number between 1 and 5:', type_=int, min_=1, max_=5)。或者sanitised_input('Guess a number between 1 and 5:', range_=[1,2,3,4,5]).
标签: python python-3.x