首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要整数的输入的Python错误处理

问需要整数的输入的Python错误处理
EN

Stack Overflow用户
提问于 2020-06-05 06:21:20
回答 1查看 28关注 0票数 1

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

谢谢!

代码语言:javascript
复制
# 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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-05 07:25:41

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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62205130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档