如何让Python检测无输入

时间:2014-10-06 23:40:02

标签: python input enter

我是python编码的新手,我填写了一些需要大量输入的代码。它要求的一件事是程序在用户按下回车键并且没有输入任何输入时执行操作。我的问题是如何让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

5 个答案:

答案 0 :(得分:4)

实际上是一个空字符串

""

而不是

" "

后者是空格字符

修改
其他几点说明

  1. 不要使用input作为Python关键字的变量名称

  2. 比较平等使用==而不是=,后者是一个赋值运算符,它会尝试修改左侧的值。

答案 1 :(得分:2)

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

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"

希望这有帮助。

答案 2 :(得分:1)

另一个提示:

在python中,你不需要对空字符串进行相等测试。请使用truth value testing。这更像是pythonic。

if not coinN:

真值测试涵盖以下测试:

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

示例:

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

答案 3 :(得分:1)

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

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime
import time

#~~~~~~~~~~~~~~~# Cookies Saver:
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)


#~~~~~~~~~~~~~~~# Get to the link: 
driver.get('https://coininfoline.com/currencies/ETH/ethereum/')

input('ENTER AFTER PAGE LOADED:')

#~~~~~~~~~~~~~~~# Get price data:
while True:
    price_extracor = driver.find_elements_by_xpath('//span[@class="cmc-formatted-price"]')
    for price_raw in price_extracor:
        price = price_raw.text

#~~~~~~~~~~~~~~~# Time Stamp:
    timestamper = datetime.now()
    timestamper.microsecond

#~~~~~~~~~~~~~~~# Date and Price Printer:
    print(timestamper,str(price))
    time.sleep(1)

答案 4 :(得分:0)

编辑:

这样的事情:

 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