gpt4 book ai didi

python-3.x - Python-错误检查

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

假设我有一个代码段:

players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9  '))

如果用户输入字母怎么办?我如何处理它,以便告诉用户他搞砸了并让他重新输入,直到输入号码为止?

这个怎么样:
possibleusershipplaces = [1,2,3,4,5,6,7,8,9]

players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9 '))

while players_chosen_hit not in possibleusershipplaces:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (or Ctrl/Command+C to quit) ')

players_chosen_hit = int(players_chosen_hit)

最佳答案

possibleusershipplaces = {1,2,3,4,5,6,7,8,9}
while True:
try:
players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9 '))
if players_chosen_hit in possibleusershipplaces:
break
except ValueError:
print("Invalid entry")

也要处理退出:
while True:
try:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (q to quit) ')
if players_chosen_hit == "q":
print("Goodbye")
break
players_chosen_hit = int( players_chosen_hit)
if players_chosen_hit in possibleusershipplaces:
break
except ValueError:
print("Invalid entry")

如果您不希望使用try/except并且仅使用正数,则可以使用 str.isdigit,但是try/except是惯用的方式:
possibleusershipplaces = {"1","2","3","4","5","6","7","8","9"}

for players_chosen_hit in iter(lambda:input('Please tell me where the hit is: 1-9 (q to quit) '),"q"):
if players_chosen_hit.isdigit() and players_chosen_hit in possibleusershipplaces:
players_chosen_hit = int(players_chosen_hit)
iter使用第二个参数 sentinel,如果输入该参数,则会中断循环。

使用函数并在达到条件时返回可能会更好:
def get_hit():
while True:
try:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (q to quit) ')
if players_chosen_hit == "q":
print("Goodbye")
return
players_chosen_hit = int(players_chosen_hit)
if players_chosen_hit in possibleusershipplaces:
return players_chosen_hit
except ValueError:
print("Invalid entry")

关于python-3.x - Python-错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28797226/

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