简体   繁体   English

如何让python识别出没有输入

[英]How do I get python to recognize that there has been no input

I would like to create a program in which if the user presses the enter key without typing in anything, python would recognize the lack of input and relocate it to the appropriate actions. 我想创建一个程序,如果用户按下回车键而不键入任何内容,python将识别缺少输入并将其重新定位到适当的操作。 For example: 例如:

some = int(input("Enter a number"))

if not some:
    print("You didn't enter a number")

else:
    print("Good job")

What I would like to happen is if the user pressed the enter key without typing a value, they would receive the first statement. 我想要发生的是,如果用户在没有输入值的情况下按下回车键,他们将收到第一个语句。 However, currently I only receive an error. 但是,目前我只收到错误。 Thank you. 谢谢。

Edit: I've had various responses about putting a try catch statement. 编辑:我有关于发出try catch语句的各种回复。 Actually, in my original code I had a error handling statement for a ValueError. 实际上,在我的原始代码中,我有一个ValueError的错误处理语句。 However I would like to distinguish between the user entering words instead of numbers and the user not entering anything. 但是,我想区分用户输入单词而不是数字而用户没有输入任何内容。 Is this possible? 这可能吗?

You're getting this error because anything given to input is expected to be a valid Python expression, but entering nothing gives 你得到这个错误,因为input任何内容都应该是一个有效的Python表达式,但是什么都不输入

SyntaxError: unexpected EOF while parsing

Edit: In Python 3.x, input is fine - the error will only be the ValueError below. 编辑:在Python 3.x中,输入很好 - 错误只会是下面的ValueError。

You can remedy this problem by switching from input to raw_input , but int also can't parse an empty string, which results in another error: 您可以通过从input切换到raw_input来解决此问题,但int也无法解析空字符串,这会导致另一个错误:

ValueError: invalid literal for int() with base 10: ''

So, you can either catch the exception that is produced, or check for empty input with a conditional statement. 因此,您可以捕获生成的异常,也可以使用条件语句检查空输入。 The latter is preferable, since other errors that may occur in your code may be swallowed up with exception handling. 后者是首选,因为您的代码中可能出现的其他错误可能会被异常处理吞噬。

raw = raw_input("Enter a number: ")
if not raw:
    print "You didn't enter a number"
else:
    some = int(raw)
    print "Good job"

Note of course that you will probably still have to deal with other syntax issues, such as if a person inputs something that isn't an integer (eg "cat") 请注意,您可能仍需要处理其他语法问题,例如,如果某人输入的内容不是整数(例如“cat”)

I searched and found a similar case in the official python documentation here : 我搜索,发现Python官方文档中的一个类似的案件在这里

while True:
    try:
        x = int(raw_input("Please enter a number: "))
        print "good job"
        break
    except ValueError:
        print "Oops!  That was no valid number.  Try again..."

update 01 更新01

code updated as below: 代码更新如下:

while True:
    try:
        x = raw_input("Please enter a number: ")
        x_mod = int(x)
        print "good job"
        break
    except ValueError:
        if len(x)==0:
            print "you entered nothing"
        else:
            print "Oops!  That was no valid number.  Try again..."

You have to use raw_input and then a try-catch to type check your input. 您必须使用raw_input然后使用try-catch来键入检查输入。

data = raw_input('Enter number: ')
try:
    print('You gave me the number: %i' % int(data))
except:
    print("I need a number")

I think this is what you're looking for 我想这就是你要找的东西

try:
    some = int(input("Enter a number"))
    print("Good job")
except (SyntaxError, ValueError):
    print("You didn't enter a number")

@user3495234 You may have solved this but I would solve this in following way. @ user3495234您可能已经解决了这个问题,但我会通过以下方式解决这个问题。

import re

some = input("Enter a number?\n>")
reg = re.compile('^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$')  
# A regexp from the perldoc perlretut

if some == "":
    print("Please enter something.")
elif reg.match(some):
    x = float(some)  # To avoid type casting error
    y = int(x)  # Apparently int(float) = int
    print("Good job")
    print(y)  # Checking for value is integer or not.
else:
    print("Looks like you didn't enter a number.")

I tried using isdigit() method to distinguish between the user entering words instead of numbers but that doesn't work well with float. 我尝试使用isdigit()方法来区分用户输入单词而不是数字,但这与float不兼容。 See this. 看到这个。

Updated regular expression to perldoc perlretut one because previous one was giving error in some cases. 将正则表达式更新为perldoc perlretut,因为前一个在某些情况下会出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何存储从用户输入创建的变量并在 Python 的不同文件中使用它? - How do I store a variable that has been created from a user input and use it in a different file in Python? 一旦我的代码已经执行,如何让我的代码循环回输入? (角色扮演游戏) - How do I get my code to loop back to an input once it has been executed already? (RPG Game) Python:新增功能,如何让Python将12识别为十二而不是3 - Python: Adding, How do I get python to recognize 12 as twelve and not 3 如何在python中绘制的图形中获得白色边框? - How do I get a white border in a figure that has been plotted in python? 如何让python识别安装在虚拟环境中的模块? - how do I get python to recognize modules installed in virtual environment? 如何让 python 识别字符串中的正确 substring? - How do I get python to recognize the correct substring in a string? 如何让python识别Pygame模块? - How do I get python to recognize the Pygame module? 如何让 IntelliJ 识别常见的 Python 模块? - How do I get IntelliJ to recognize common Python modules? 如何获取狮身人面像以识别装饰的python函数 - How do I get sphinx to recognize decorated python functions 如何让 VSCode 将 Python3 识别为我的默认值 - How do I get VSCode to recognize Python3 as my default
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM