Python - 错误检查

时间:2015-03-01 18:18:46

标签: python-3.x error-handling

说我有一个代码段:

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)

1 个答案:

答案 0 :(得分:1)

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")

如果你不想尝试/除了只有正数,你可以使用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")