首页 > 解决方案 > 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.")

标签: python-3.x

解决方案


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


推荐阅读