如何让Python检测到没有inpu

2024-04-26 22:41:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始用python编写代码,我正在填写一些需要大量输入的代码。它要求的一件事是,如果用户按下了enter键,并且没有输入任何输入,程序就会执行一个操作。我的问题是如何让python检查它。会是:

if input == "":
    #action

还是别的什么?谢谢你的帮助。

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

 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

Tags: and代码用户程序编辑inputifaction
3条回答

只是另外一个提示:

在python中,您不需要对空字符串执行相等测试。请改为使用truth value testing。那更像是Python。

if not coinN:

真值测试包括以下测试:

  • 任何数字类型的零,例如0、0L、0.0、0j
  • 任何空序列,例如,,,,[]。
  • 任何空映射,例如{}。
  • 用户定义类的实例,如果该类定义了非零len方法,则当该方法返回整数零或bool值False时。1

示例:

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

实际上,空字符串将是

""

而不是

" "

后者是一个空格字符

编辑
其他一些注意事项

  1. 不要使用input作为变量名,它是Python关键字

  2. 比较等式使用==而不是=,后者是赋值运算符,它试图修改左侧的值。

我知道这个问题已经过时了,但我仍然在分享你的问题的解决方案,因为它可能会对其他人有所帮助。要在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"

希望这有帮助。

相关问题 更多 >