0
How to check if input is empty in python?
While s = "" ? How to check if the input I receive is empty using only the while command.
6 Réponses
+ 6
You can check input is empty or not with the help of if statement.
x=input()
if x:
print(x)
else:
print('empty input')
+ 2
A tip: when you are dealing with EOF or something alike always remember that, to python, every null or empty or zero it's managed like a "false"... So you can put something like "while s:" because, if it's null or empty, will be false to python
+ 2
One pattern would be:
s = input()
while s:
somelist.append(s)
s = input()
It's a bit annoying to write the same line twice, but there is no 'do while' like in c.
Or you use this:
while True:
s = input()
if not s:
break
somelist.append(s)
+ 2
input() returns a string. To check whether it is empty, just check its length.
s=input()
while len(s)==0:
s=input()
+ 1
You might want to use the catch exception method.
Whenever you enter an input, in case that input is empty, it produces an End of File Error written as EOFError.
So your code should look something like this,
try:
#enter input
s = input()
#do something with your input
except EOFError:
#action when input is empty or there is no input
The code above should do it. ;)
0
x=input()
if not x:
print('empty input')