python - 在我得到特定范围内的整数之前,如何继续要求用户输入?

标签 python python-3.x function error-handling while-loop

我最近决定重新审视我的TicTacToe游戏,该游戏是我大约3个月前制作的,需要重新调试,并且有一个特别的bug一直困扰着我。基本上,我有以下代码:

def player_choice(board):
    '''Asks the player for their next position, calls a func to check if it's free'''
    '''and returns the position if it's free for later use'''
    spot = None
    while spot not in range(1, 10) or not space_check(board, spot):
        try:
            spot = int(input("Choose your next position (1-9): "))
        except:
            print("Hmm, looks to me like your input was invalid")
        else:
            break
    return spot
这是一个更大的方案中的函数,但使整个游戏中断的是我需要一个整数作为输入,严格来说,范围在1到10之间。在尝试错误处理之前,我使用了while循环,该循环不断询问是否提供了str:
spot = int(input("Choose your next position (1-9): "))
    while spot not in range (1, 10) or not space_check(board, spot):
        spot = int(input("Looks like the spot you're trying to choose is invalid!\nPlease choose another position (1-9): "))
    return spot
但是后来我切换到了这个版本,这里它不会接受str作为输入,但是会接受1-10范围之外的int值。我的问题是:我该怎么做才能按照我需要的方式工作,取一个严格介于1到10之间的整数并继续询问直到精确提供此输入?

最佳答案

四处移动,这似乎可行。虽然我不知道为什么else总是被触发...

def player_choice2(board):
    '''Asks the player for their next position, calls a func to check if it's free'''
    '''and returns the position if it's free for later use'''
    try:
        spot = int(input("Choose your next position (1-9): "))
    except:
        print("Hmm, looks to me like your input was invalid")
        spot = 0
    while spot not in range(1, 10) or not space_check(board, spot):
        try:
            spot = int(input("Choose your next position **  (1-9) **: "))
        except:
            print("Hmm, looks to me like your input was invalid")
        else:
            # This always fires...?
            print("Else....")
    return spot

关于python - 在我得到特定范围内的整数之前,如何继续要求用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63271698/

相关文章:

python - 如何提高查准率和查全率

python - Python 中的缩进样式 : Reverse Words Function

c - print_list 函数只打印链表中用户的第一个输入

c++ - 有条件地从 C++ 调用 Lua 函数

python - select() 和 table.select() 的区别

python - 无法反序列化python中的protobuf字节字段

python - python 的文件和异常

python - C++ 到 Python 初学者

python - 如何在递归函数 Python 中使用列表?

javascript - 不调用内部函数