蟒蛇猜谜游戏拒绝无效的用户输入



我正在上我的第一个Python课程,像大多数Python类一样,最后一个任务是创建一个从1到100的猜谜游戏,跟踪有效尝试的次数。我无法获得(或在堆栈溢出上找到(的元素是如何拒绝无效的用户输入。用户输入必须是介于 1 和 100 之间的整数正数。我可以让系统拒绝除 0 和 <+ 101 之外的所有内容。

我唯一能想到做的事情最终告诉我,你不能让运算符比较字符串和整数。我一直想使用诸如猜测> 0 和/或猜测 101 <之类的东西。我也尝试创建某种功能,但无法使其正常工作。>

#  Generate random number
import random
x = random.randint(1,100)
#  Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
#  Check if input is a positive integer and is not 0 or >=101
#  this line doesn't actually stop it from being a valid guess and 
#  counting against the number of tries.
if guess == "0":  
print(guess, "is not a valid guess")
if guess.isdigit() == False: 
print(guess, "is not a valid guess")
else: 
counter += 1
guess = int(guess)
#  Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
import random
x = random.randint(1,100)
#  Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
try:
guess = int(guess)
if(100 > guess > 0):
counter += 1
guess = int(guess)
#  Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
else:
print("Number not in range between 0 to 100")
except:
print("Invalid input")
#  Generate random number
import random
x = random.randint(1,100)
#  Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 1   

while True:
try:
guess = int(input("Try to guess my number: "))
if guess > 0 and guess < 101:
print("That's not an option!")
#  Begin playing
elif guess == x:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
elif guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
counter += 1        
except:
print("That's not a valid option!")

我的教练帮助了我。(我发帖是为了防止那个给我成绩的人需要它。这是我们想出的。我发布它是为了帮助任何可能遇到这种特定拒绝用户输入问题的未来 Python 学习者。

谢谢你们这么快发帖!即使我需要导师的帮助,如果没有你的见解,我会显得更加无能。现在我实际上可以享受我的假期周末了。有一个很棒的阵亡将士纪念日周末!!

import random
x = random.randint(1,100)
print("I'm thinking of a number from 1 to 100.")
counter = 0
while True:
try:        
guess = input("Try to guess my number: ")
guess = int(guess) 
if guess < 1 or guess > 100:
raise ValueError()
counter += 1
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
except ValueError:
print(guess, "is not a valid guess")

最新更新