【问题标题】:Code for "enter" key press without any input in PythonPython中没有任何输入的“输入”按键代码
【发布时间】: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


【解决方案1】:

您的问题是您正在自动将 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 循环重复,直到用户输入有效数字

【讨论】:

  • 谢谢!现在有意义
【解决方案2】:

这是因为 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

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2020-08-06
    • 2023-01-30
    相关资源
    最近更新 更多