python-3.x - Python中没有任何输入的“输入”按键代码
问题描述
我是 Python 新手,正在尝试使用 Python 3 制作这个交互式猜谜游戏。在游戏中的任何时候,如果用户在没有任何输入的情况下按“Enter”,它就会崩溃到“ValueError:int() 的无效文字与 base 10:''”我在这里添加什么?
重申一下,我是编程新手。我试图完全只使用我到目前为止学到的概念来编写这个代码,所以一切都是相当基本的。
# 'h' is highest value in range. 'a' is randomly generated value in the range. 'u' is user input
import random
h = 10
a = random.randint(1,h)
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
while u != a:
if 0 < u < a:
print("Please guess higher.")
u = int(input())
elif a < u < h:
print("Please guess lower.")
u = int(input())
elif u > h:
u = int(input("Whoa! Out of range, please choose within 1 and %d!" %(h)))
elif u == 0:
print("Thanks for playing. Bye!!")
break
# I was hoping to get the below response when user just presses "enter" key, without input
else:
print("You have to enter a number.")
u = int(input())
if u == a:
print("Well done! You got it right.")
解决方案
您的问题是您正在自动将 input() 调用的结果转换为 int,因此如果用户在没有实际输入数字的情况下按 Enter 键,那么您的代码将尝试将该空字符串转换为 int,因此会出现错误ValueError: invalid literal for int() with base 10: ''
. 您可以添加一个检查以确保用户在直接将其转换为 int 之前实际输入了一些输入,如下所示:
u = input()
while u == '':
u = input('Please enter a number')
u = int(u)
但是,这并不能阻止用户输入无效数字(例如“a”)并导致类似错误,因此捕获这两个问题的更好解决方案可能是:
u = ''
while type(u) != int:
try:
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
except ValueError:
pass
try except 捕获您之前看到的错误,其中用户输入了与数字不相似的内容,并且 while 循环重复,直到用户输入有效数字
推荐阅读
- angular - 我正在创建一个简单的应用程序,在成功登录后我想从登录页面导航到起始页面
- pytorch - 如何在 PyTorch 中向张量添加一些高斯噪声?
- java - 为什么 getOne() 会阻止 deleteById()
- xamarin.forms - Xamarin.Forms 步进器在 android 上仅显示减号按钮
- javascript - JavaScript 值到 PHP 变量
- architecture - 如何在 SOA 架构中实现 ESB?
- python - 如何计算一个元素在RDD加入(Spark)之后有2个字段相同的次数
- uipath - 如何在uipath中替换DOUBLE_QUOTE“字符
- python - 无法启动 docker-compose 并在 No module 上失败
- python - OpenCV:如何将我的图像传递给另一种方法?