【发布时间】:2020-04-07 16:02:54
【问题描述】:
我是 Python 新手,我正在尝试使用 Python 3 制作这个交互式猜谜游戏。在游戏中的任何时候,如果用户只是在没有任何输入的情况下按“Enter”,它就会崩溃到“ValueError: invalid literal for int( ) 以 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.")
【问题讨论】:
-
您正在尝试将空字符串转换为整数:
int(input())。而是先将input()的结果保存到一个变量中,然后检查是否为空,..
标签: python-3.x