我正在学习Python,尝试做的其中一项练习是制作“猜数字”游戏。我做了一个非常简单的程序,但是现在我想进一步介绍一下,并为输入设置一些边界,以便程序可以防止错误。这是我的代码:
# Guess the number game.
import random
print('Hello. What is your name?')
yourName = input() # collects user's name
solution = random.randint(1,20)
print('Well, ' + str(yourName) + ', I am thinking of a number between 1 and 20.')
acceptable = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20'] # acceptable answers
def game():
for attempts in range(1,6):
print('Take a guess. You have ' + str(6 - attempts) + ' attempt(s) remaining')
# try:
guess = (input())
while guess:
if guess != acceptable:
print("That is not a valid answer!")
guess = (input())
else:
moveon()
def moveon():
while guess != solution:
if guess < solution:
print('Your guess is too low. Try again.')
elif guess > solution:
print('Your guess is too high. Try again.')
else:
endofgame()
'''
except ValueError:
print('Please enter a guess that is a number.')
attempts + 1 == attempts
'''
def endofgame():
if guess == solution:
print('You guessed it! It took you ' + str(attempts) + ' attempt(s)')
playAgain()
else:
print('Game over! The number I was thinking of was ' + str(solution))
playAgain()
# Option to play again with a new number
def playAgain():
global solution
print('Play again? Y/N')
playAgain = input()
if playAgain == 'Y':
print('Okay, ' + str(yourName) + ', I have another number between 1 and 20.')
solution = random.randint(1,20)
game()
else: print('Thanks for playing!')
# Start game
game()
所以我要做的是确保提示用户输入1到20之间的数字时,输入“ 22”,“咖啡”或“ 14.5”之类的答案将是无效的,并提示他们再试一次并输入有效答案。但是,当我现在运行该程序时,输入的任何答案将被视为无效。我该如何做,以便仅接受某些答案,而其他答案则不被接受?我怀疑除了使用我不知道的列表之外,还有其他方法。预先感谢!
答案 0 :(得分:3)
您需要检查列表中是否包含 ,这是我们在Python中的处理方式:
if guess not in acceptable:
答案 1 :(得分:1)
您想使用if guess != acceptable
而不是使用if guess not in acceptable
。
使用python,您可以使用in
命令检查数组中是否存在元素。