【问题标题】:Python Error handling for an input requiring a integer需要整数的输入的 Python 错误处理
【发布时间】:2020-09-24 01:22:51
【问题描述】:

我想实现错误处理,以便如果用户输入除整数以外的任何内容,他们会被要求提供正确的输入。我相信 try/except 会起作用,但我想知道如何让它检查一个范围内的正确数字并确保没有其他字符。我已将我的代码粘贴在下面以供审核。

谢谢!

# Rock Paper Scissors

import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")

# game_counter = 0

human_1 = input("Please enter your name: ")

GameOptions = ['Rock', 'Paper', 'Scissors']

hmn_score = 0
cpt_score = 0

rps_running = True


def rps():
    global cpt_score, hmn_score
    while rps_running:

        hmn = int(input("""Please select from the following:
                                1 - Rock
                                2 - Paper
                                3 - Scissors
            \n""")) - 1

        while not int(hmn) in range(0, 3):
            hmn = int(input("""Please select from the following:
                                            1 - Rock
                                            2 - Paper
                                            3 - Scissors
                        \n""")) - 1

        print('You Chose: ' + GameOptions[hmn])

        cpt = rdm.randint(0, 2)

        print('Computer Chose: ' + GameOptions[cpt] + '\n')

        if hmn == cpt:
            print('Tie Game!')

        elif hmn == 0 and cpt == 3:
            print('You Win')
            hmn_score += 1
        elif hmn == 1 and cpt == 0:
            print('You Win')
            hmn_score += 1
        elif hmn == 2 and cpt == 1:
            print('You Win')
            hmn_score += 1
        else:
            print('You Lose')
            cpt_score += 1

        game_score()
        game_running()


def game_score():
    global cpt_score, hmn_score
    print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')


def game_running():
    global rps_running
    if hmn_score == 2:
        rps_running = False
        print(f"{human_1} Wins!")
    elif cpt_score == 2:
        rps_running = False
        print(f"Computer Wins!")
    else:
        rps_running = True


rps()

【问题讨论】:

    标签: python-3.x error-handling


    【解决方案1】:

    要回答您的问题,您可以执行以下操作

    options = range(1, 4)
    while True:
        try:
            choice = int(input("Please select ...etc..."))
            if(choice in options):
                break
            raise ValueError
        except ValueError:
            print(f"Please enter a number {list(options)}")
    print(f"You chose {choice}")
    

    至于代码审查,有一个特定的堆栈交换,请参阅Code Review

    【讨论】:

    • 非常感谢!我会将其移至相应的论坛部分。
    • 没问题,如果您认为是答案,可以将其标记为答案:)
    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2022-07-20
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多