gpt4 book ai didi

Python - 是否可以使用列表作为 if 语句的条件?

转载 作者:行者123 更新时间:2023-11-28 22:10:23 24 4
gpt4 key购买 nike

我正在学习 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”之类的答案将无效并提示他们重试并输入有效答案。然而,当我现在运行这个程序时,输入的任何答案都被返回为无效。我该怎么做才能只接受某些答案,而其他答案不被接受?我怀疑除了使用我还不知道的列表之外还有其他方法。提前致谢!

最佳答案

您需要检查一个项目是否包含在列表中,这就是我们在 Python 中的做法:

if guess not in acceptable:

关于Python - 是否可以使用列表作为 if 语句的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56813921/

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