在 Python 中无需任何输入即可"enter"按键的代码



我是Python的新手,正在尝试使用Python 3制作这个交互式猜谜游戏。在游戏的任何时候,如果用户在没有任何输入的情况下只按"Enter",它就会崩溃为"ValueError:invalid literal for int((with 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循环重复,直到用户输入有效的数字

这是因为u=int(input(((总是试图将给定的值转换为整数。一个空字符串无法转换为整数->您会遇到这个错误。现在,python已经为这种类型的场景提供了try/except/else/finally子句。我认为你应该做的是类似的事情
while True: #loop forever
try:
u = int(input("Please, enter a number: ")) #this tries to accept your input and convert it to integer
except ValueError:                   #executes if there is an error in try
print("That isn't a valid integer, please try again")
else:
print("u =",u)
break  #break the loop if there was no mistakes in try clause

相关内容

最新更新