我是个蟒蛇初学者,我在做一个简单的猜数游戏,但每次我不小心输入一个字母或符号,而不是一个数字,我就会得到ValueError。如何在整个程序中传递此错误?我知道代码很混乱,对此我很抱歉,但我只是想找点乐子。
import random
tries = 15
money = 0
cheat = 0
run = True
random_number = random.randint(1, 20)
while run:
if cheat >= 1:
print(random_number)
cheat -= 1
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
guess = int(guess)
if guess == random_number:
money += 5
print("You got it right! You got it with " + str(tries) + " tries left", "your balance is", + money)
again = input("Play again? yes/no")
if again == "yes":
random_number = random.randint(1, 20)
else:
break
#store system
shop = input("Would you like to access the shop? yes/no")
if shop == "yes":
try_cost = 10
cheat_cost = 20
#if player has enough money
buy_try = input("Would you like to purchase more tries? price is 10 dollars for 5 tries. yes/no")
if buy_try == "yes" and money >= 10:
tries += 5
money -= 10
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
buy_cheat = input("Would you like to purchase a cheat? price is 20 dollars for 2 cheats")
if buy_cheat == "yes" and money >= 20:
cheat += 2
money -= 20
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
# if player doesn't have enough money
elif buy_try == "yes" and money != 10:
print("You don't have enough for that, you have", money, "dollars")
elif buy_cheat == "yes" and money != 20:
print("You don't have enough for that, you have", money, "dollars")
elif guess > random_number:
print("Try a little lower!")
tries -= 1
elif guess < random_number:
print("Try a little higher!")
tries -= 1
if tries == 0:
print("you ran out of tries!")
run = False
从1-20中选择一个数字!您有15个没有尝试的跟踪(最近一次调用):File "C:\Users\bashr\PycharmProjects\pythonProject1\main.py",第15行,在猜测=int(猜测)ValueError中:带基10:'s‘的int()无效文本
发布于 2022-02-03 02:22:20
在这种情况下,使用try
和except
子句。
文档:https://docs.python.org/3/tutorial/errors.html#handling-exceptions
发布于 2022-02-03 02:22:58
假设要访问整个文件中的错误,则可以使用全局变量,也可以使用类概念。
发布于 2022-02-03 02:59:04
我认为最快的解决方法是一段时间:而输入不是数字,再问一次输入。因此,在您的情况下,每次使用输入函数时,都应该使用如下内容:
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
while not guess.isdigit():
print("the input Is not a digit, please retry")
guess = input("Pick a number from 1-20! You have...")
或者你可以使用,你可以使用,尝试,除了
https://stackoverflow.com/questions/70965187
复制相似问题