How do you get Python to detect for no input

user3495234 picture user3495234 · Oct 7, 2014 · Viewed 49.6k times · Source

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:

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

Answer

Tony Mathew picture Tony Mathew · Sep 9, 2016

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:

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.