How do you get Python to detect for no input
Asked Answered
M

6

6

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
Mountaineer answered 6/10, 2014 at 23:40 Comment(3)
pretty sure you need 2 ==s in there and change " " to "".Frenchify
Right. Thanks. Forgot about that.Mountaineer
coinN is an int. You are checking whether it is an empty stringDozy
E
12

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.

Eiderdown answered 9/9, 2016 at 6:38 Comment(1)
Wonderful, this saved me!Tweedsmuir
C
6

Actually an empty string would be

""

Instead of

" "

The latter is a space character

Edit
A few other notes

  1. Don't use input as 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.

Cureall answered 6/10, 2014 at 23:40 Comment(3)
Right. I tried that. But instead of going to my response command it went to my exception command and was recognized as a ValueError.Mountaineer
@user3495234: Have you made the classic mistake of trying to do something with your input before you check that you can do it, instead of after? For example, calling int on it before your if statement?Rysler
I added what it looks like above. Should the int have gone afterwards?Mountaineer
A
2

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.

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

Example:

>>> s = ''
>>> if not s:
...     print 's is empty'
...
s is empty
>>>
Apery answered 7/10, 2014 at 0:2 Comment(1)
What if you want a conditional that's okay with a 0, but not okay with no inputs. This seems to be the OP's question.Synthetic
H
1

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.

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")
Henn answered 22/9, 2019 at 22:46 Comment(0)
D
0

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
Dozy answered 7/10, 2014 at 0:3 Comment(5)
I tried that but unfortunately the message that keeps getting printed out is "Invalid Input"Mountaineer
ah, I see, you are testing for a string with "", but you are inputting an int. I will update my post.Dozy
Unfortunately, I'm getting the same thing.Mountaineer
Are you sure it's nothing to do with totalcoin or rand?Dozy
I don't think so because I still get invalid input when I take out the totalcoin part and only leave it as if not coinN:Mountaineer
L
0

If You dont know no of rows and columns of the matrix input you are taking you can try this

 ok=True
 while ok:
   try:
       l=input()
       if not l or l=="":
          break
       else:
          li=list(l.split(","))
       li=[int(i) for i in li]
       matrix.append(li)
   except EOFError:
       ok=False
       break
Lindeman answered 26/11, 2023 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.