首页 > 解决方案 > 我怎么能在输入中制作一个有限的数字并只制作数字,我不想要符号

问题描述

我有一个小游戏,它可以让你选择一个随机游戏,但我有两个问题:

1-我想验证用户输入是 0 到 20 之间的数字。

2-我想让用户再次玩(可以通过询问他或直接)

这是我的代码,如果有任何问题或建议,请告诉我,我希望你能把它写在一封信里,以便我理解它,非常感谢你的帮助。

这是代码:

import random
rn = int(random.randint(0, 20))
gn = int(input("write a number from 0-20: "))


while True:
  if rn < gn:
    print("You were too close, try again")
    break
  elif rn == gn:
    print("Oh, I lost, you win, good game (GG)")
    break
  if rn > gn:
    print("You are not close, try again")
    break

while False:
  rn = int(random.randint(0, 20))
gn = int(input("write a number from 0-20: "))

标签: pythonpython-3.xinputwhile-loop

解决方案


为了检查输入值,试试这个:

def ask_for_guess():
    # the function will ask infinitely for input number unless it's valid number in between 0-20 
    while True:
        guess_input = input("write a number from 0-20: ")
        try:
            gn = int(guess_input) 
            assert 0 <= gn <= 20, "Number must be between 0-20"
            return gn
        except ValueError as ex:
            # ValueError will be thrown if the conversion to int will fail
            print(f"{guess_input} is not a number, please try again")
        except AssertionError as ex:
            # AssertionError will be thrown by the test in the try block if the number is not in range
            print(str(ex))

要检查用户是否想再次玩,试试这个:

play_again = True
while play_again: 
    rn = int(random.randint(0, 20))
    gn = ask_for_guess()
    if rn < gn:
        print("You were too close, try again")
    elif rn == gn:
        print("Oh, I lost, you win, good game (GG)")
    else:
        print("You are not close, try again")
    # if the user doesn't want to play again, the play_again variable will be False and the code won't enter for another iteration inside the while loop
    play_again = input("Do you want to play again? [y/n]") == "y"

推荐阅读