你如何让 Python 检测到没有输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26226489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:14:31  来源:igfitidea点击:

How do you get Python to detect for no input

pythoninputenter

提问by user3495234

I'm new to coding in python and I was filling out some code that required a number of inputs. One thing it asked for was for the program to perform an action if the user pressed the enter key and did not type in any input. My question is how you would get python to check for that. Would it be:

我是 python 编码的新手,我正在填写一些需要大量输入的代码。它要求的一件事是,如果用户按下回车键并且没有输入任何输入,程序就执行一个操作。我的问题是你如何让 python 来检查。可不可能是:

if input == "":
    #action

Or is it something else? Thank you for the help.

或者是别的什么?感谢您的帮助。

Edit: Here is what my code currently looks like for reference.

编辑:这是我的代码目前的样子以供参考。

 try:
     coinN= int(input("Enter next coin: "))

     if coinN == "" and totalcoin == rand: 
         print("Congratulations. Your calculations were a success.")
     if coinN == "" and totalcoin < rand:
         print("I'm sorry. You only entered",totalcoin,"cents.")  

 except ValueError:
     print("Invalid Input")
 else:
     totalcoin = totalcoin + coinN

回答by Cory Kramer

Actually an empty string would be

实际上一个空字符串将是

""

Instead of

代替

" "

The latter is a space character

后者是一个空格字符

Edit
A few other notes

编辑
其他一些笔记

  1. Don't use inputas your variable name that is a Python keyword

  2. Comparing equality uses ==instead of =, the latter is an assignment operator, it attempts to modify the value of the left-hand side.

  1. 不要使用inputPython 关键字作为变量名

  2. 比较等式使用==代替=,后者是一个赋值运算符,它试图修改左边的值。

回答by James Sapam

Just another tips:

只是另一个提示:

In python you don't need to do equality test for empty string. Instead please use truth value testing. That is more pythonic.

在python中,您不需要对空字符串进行相等测试。相反,请使用真值测试。那更像pythonic。

if not coinN:

Truth value testing covers the following test:

真值测试包括以下测试:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False. 1
  • 没有任何
  • 错误的
  • 任何数字类型的零,例如 0、0L、0.0、0j。
  • 任何空序列,例如,''、()、[]。
  • 任何空映射,例如 {}。
  • 用户定义类的实例,如果类定义了非零()或len()方法,当该方法返回整数零或布尔值False时。1

Example:

例子:

>>> s = ''
>>> if not s:
...     print 's is empty'
...
s is empty
>>>

回答by Totem

EDIT:

编辑:

what about something like this:

这样的事情怎么样:

 try:
     coinN = input("Enter next coin: ")
     if coinN.isdigit(): # checks whether coinN is a number
         if coinN == "" and totalcoin == rand:
             print("Congratulations. Your calculations were a success.")
         if coinN == "" and totalcoin < rand:
             print("I'm sorry. You only entered",totalcoin,"cents.")
     else:
         raise ValueError

 except ValueError:
     print("Invalid Input")
 else:
     totalcoin = totalcoin + int(coinN) # convert coinN to int for addition

回答by Tony Mathew

I know this question is old, but I'm still sharing the solution to your problem as it could be a helpful hand to others. To detect no input in Python, you actually need to detect for "End of File" error. Which is caused when there is no input:
This can be checked by the following piece of code:

我知道这个问题很老,但我仍在分享您的问题的解决方案,因为它可能对其他人有所帮助。要检测 Python 中没有输入,您实际上需要检测“文件结尾”错误。这是在没有输入时引起的:
这可以通过以下代码进行检查:

final=[]
while True:
    try:
         final.append(input())   #Each input given by the user gets appended to the list "final"
    except EOFError:
         break                   #When no input is given by the user, control moves to this section as "EOFError or End Of File Error is detected"

Hope this helps.

希望这可以帮助。

回答by Garbow

I'm new to python and was looking for a fix to a similar problem. I know this is a really old post but I thought I would have a go at it. If I understand your problem correctly and what you're trying to achieve, this works fine for me. (As long as you don't try and enter a letter!) I posted earlier but it wasn't right, sorry.

我是 python 新手,正在寻找类似问题的解决方案。我知道这是一个非常古老的帖子,但我想我会尝试一下。如果我正确理解了您的问题以及您想要实现的目标,那么这对我来说很好用。(只要您不尝试输入字母!)我之前发布过,但不正确,抱歉。

totalcoins = None
coinN = None
sum_total = range

while coinN != '0' and totalcoins != '0':
    coinN = input("Please enter first amount:   ")
    if coinN == "":
        print("You didn't enter anything")
    else:
        totalcoins = input("Please enter second amount   ")
        if totalcoins == "":
            print("You didn't enter anything")
        else:
            sum_total = int(coinN) + int(totalcoins)
            if sum_total in range(100):
                    print('Sorry, you only entered {} cents'.format(sum_total))
            else:
                if sum_total == 100:
                    print('The sum of {0} and {1} is = 1 rand     '.format(coinN, totalcoins, sum_total))
            if sum_total >=100:
                print('The sum of {0} and {1} is = {2} rand   '.format(coinN, totalcoins, sum_total))
                print("\n")