gpt4 book ai didi

python - 我需要在简单的随机数字游戏中修复ValueError的帮助

转载 作者:行者123 更新时间:2023-12-03 08:22:00 26 4
gpt4 key购买 nike

我创建了一个简单的数字猜谜游戏,并且尝试修复无意输入时的错误。

当程序要求您进行猜测时,如果用户在没有输入数字的情况下按回车,则会出现此错误:

Traceback (most recent call last): File "/Users/tom/Documents/Automate with Python/RandomNumberGame.py", line 13, in guess = int(input()) ValueError: invalid literal for int() with base 10: ''



我希望它打印“请输入数字”。

我是编程新手,已经开始阅读“使用Python自动化无聊的东西”。提前致谢!

原始代码不包括
elif guess == ' ':
print('Please enter a number')

但目标是让程序说如果输入为空

我尝试添加:
guess = int(input()) or str(input()) 

没有任何进展

猜数字游戏
import random
print('Hello, What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!')
secretNumber = random.randint(1,1000)

print('DEBUG: Secret number is ' + str(secretNumber))

for guessesTaken in range(1,11):
print('Take a guess.')
guess = int(input())


if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess

if guess == secretNumber:
print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!')
else:
print('Too many guesses, The number I was thinking of was ' + str(secretNumber))

最佳答案

如果您也不想错过尝试,如果用户只是按Enter键而不输入数字。您可以像这样在while True:块中使用try-except

#code till this
for guessesTaken in range(1,11):
print('Take a guess.')
while True:
try:
guess = int(input())
break
except ValueError:
print('Please enter a number')
continue
#rest of your code

如果用户在尝试次数保持不变的情况下意外按下Enter键,则将允许用户继续游戏。

完整代码:
import random
print('Hello, What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!')
secretNumber = random.randint(1,1000)

print('DEBUG: Secret number is ' + str(secretNumber))

#code till this
for guessesTaken in range(1,11):
print('Take a guess.')
while True:
try:
guess = int(input())
break
except ValueError:
print('Please enter a number')
continue
#rest of your code

if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break #This condition is for the correct guess

if guess == secretNumber:
print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!')
else:
print('Too many guesses, The number I was thinking of was ' + str(secretNumber))

关于python - 我需要在简单的随机数字游戏中修复ValueError的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com