我有一个猜测游戏,我想将用户输入验证为数字,数字必须在我的范围之间(如果这里甚至是正确的术语),如果没有,则返回允许用户再次尝试的错误消息。
我已经设置了我的猜谜游戏,但现在我正试图设置它的限制。我尝试使用isdigit(str),但我不确定我是否完全理解它是如何工作的所以我现在有点困难,试图让它与TRY和Except一起工作:我也认为我搞砸了我的代码之前有效,因为现在当我输入5时,它说数字不在1到10之间,所以我的其他说法是错误的。
import random
`enter code here`#Welcome Message
print("Welcome to my Guess the number program!")
print()
guess = ()
number = random.randint(1, 10)
count = 0
#User input/game rules
while True:
guess = int(input("Guess a number between 1 and 10: "))
try:
guess = int(guess)
if guess<1 or guess>10:
count += 1
guess = int(guess)
print()
if guess < number:
print("Too low.")
print()
elif guess > number:
print("Too high.")
print()
else:
print("You guessed it!")
print("You guessed it in" ,count, "attempts.")
else:
print("number not between 1 and 10")
except:
print("Invalid input")[enter image description here][1]
在我开始搞乱它之前,这是代码。
import random
#Welcome Message
print("Welcome to my Guess the number program!")
print()
guess = ()
number = random.randint(1, 10)
count = 0
#User input/game rules
while guess != number:
guess = int(input("Guess a number between 1 and 10: "))
count += 1
print()
if guess < number:
print("Too low.")
print()
elif guess > number:
print("Too high.")
print()
elif guess == number:
print("You guessed it!")
print("You guessed it in" ,count, "attempts.")
else:
break
这是错的
if guess<1 or guess>10:
当猜测是5
然后它是False
并且它去
else:
print("number not between 1 and 10")
你需要
if guess>=1 and guess=<10:
或更短
if 1 <= guess =< 10:
你在三个地方使用int()
guess = int(input("Guess a number between 1 and 10: "))
try:
guess = int(guess)
if guess<1 or guess>10:
count += 1
guess = int(guess)
但你只能做一次。
你应该在try/except
里面做
guess = input("Guess a number between 1 and 10: ")
try:
guess = int(guess)
if 1 <= guess =< 10:
count += 1
对您的代码的评论:
在你的代码上看到以下mods:
import random
#Welcome Message
print("Welcome to my Guess the number program!\n")
number = random.randint(1, 10)
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess>=1 and guess<=10:
count += 1
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
else:
print("You guessed it!")
print("You guessed it in" ,count, "attempts.")
else:
print("number not between 1 and 10")
except:
print("Invalid input")