# This is a guess the number game.
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!' )
guess =int(input())
if guess<secretNumber:
print('Your guess is too low')
elif guess>secretNumber:
print('Your guess is too high')
else:
break # This is for correct guess is equal.
if guess ==secretNumber:
print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))
嗨,我的超级编码员,
所以我试图将Try and Except块放到该程序中,我尝试将它放到后面 不幸的是,guess = int(input())无法使它正常工作。
因此,我正在尝试处理ValueError,因此,可以说用户需要输入Integers(数字),如果他键入诸如“ One”,“ Six”之类的字符串,则程序将崩溃。我想处理这种情况。请帮我一下。 :)
非常感谢。 眼镜蛇
答案 0 :(得分:1)
如何处理,它再次询问用户是否输入了字符串:
# This is a guess the number game.
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!' )
try:
guess =int(input())
except:
print("Must be a number, try again: ")
continue
if guess<secretNumber:
print('Your guess is too low')
elif guess>secretNumber:
print('Your guess is too high')
else:
break # This is for correct guess is equal.
if guess ==secretNumber:
print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))
答案 1 :(得分:0)
如果用户输入的不是数字,则python会由于出现错误而跳至异常,因此我在印刷品中添加了一些文字以阐明游戏规则。 我在for循环之后使用else,这在用户无法猜测7次尝试中的数字的情况下有时非常有用,您可以对其进行测试,看看即使else不在if之后,当ifgues == secretNumber时是正确的,并且您中断了循环,else语句不执行任何操作。 P.S仍然是在这里回答的新问题,请提供有关我的回答的反馈
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!, You Have 7 tries' )
try:
guess = int(input())
if guess<secretNumber :
print('Your guess is too low')
elif guess>secretNumber :
print('Your guess is too high')
if guess == secretNumber:
print('Good Job, ' + name + '! You guess my number in ' + str(guessTaken)+ ' guesses!')
break # This is for correct guess is equal.
except:
print('Please Enter A number ' + name + 'and not anything else' )
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))