python - 我怎么能在输入中制作一个有限的数字并只制作数字,我不想要符号
问题描述
我有一个小游戏,它可以让你选择一个随机游戏,但我有两个问题:
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: "))
解决方案
为了检查输入值,试试这个:
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"
推荐阅读
- python - 如何在另一个函数上使用错误处理函数?
- python - 没有名为“psutil”的模块
- c# - Datagrid 填充 MySQL 数据操作数据
- binary - 如何计算给定 n 位的多余 N 的范围?
- loops - Rust:迭代 iter() 或向量本身
- vue.js - Webpack 在 head 标签而不是 body 标签中注入 bundle
- kdb - kdb - kdb 服务器和上下文管理上的持久化功能
- python - 检查列表中是否出现多个 SUBstring,而不显式定义子字符串
- android - android.database.sqlite.SQLiteException:不是错误(代码 0 SQLITE_OK)
- c# - 我在 oledbdatareader 收到一个错误,说 ASP.NET 中的一个或多个必需参数没有给定值