Python:继续请求输入,直到给出有效响应

问题描述 投票:0回答:1
我正在开发一个随机数字游戏,并且有一个适用于该目的的代码。然而,当玩家输入小于 1 或大于 10 的数字时,我希望程序能够说“这不是有效的输入”。 有简单的方法吗? 我尝试使用 if else 语句进行快速修复,但没有成功。

这是我到目前为止的代码:

from random import randint def validateNumber(number): return 1 <= number <= 10 game_1 = randint(1, 10) while True: is_valid = False while not is_valid: try: number_in = int(input("Guess which number from 1-10 that will come up: ")) is_valid = validateNumber(number_in) except ValueError: pass if number_in == game_1: print(f"The result was {game_1}. Congrats!") break else: print(f"The result was {game_1}. Try again") game_1 = randint(1, 10)
当玩家输入无效时,是否有一种简单的方法可以循环询问新号码?

感谢所有答案! (很抱歉,如果这是一个非常简单的问题,我对 Python 还很陌生,即使在查看了这里的一些现有问题之后,现在也没有想法)

python loops validation random
1个回答
0
投票
您可以创建一个名为 is_valid(

input) 的函数:

def is_valid(_input_): if _input_> 1: if _input_ < 10: return True else: return False else: return False def __input__(): _input_ = int(input('Enter a number 1-10\n')) if is_valid(_input_): print('Okay!') while not is_valid(_input_): print('That input was not valid') return str(_input_) __input__()
    
© www.soinside.com 2019 - 2024. All rights reserved.