Check if one of all variables is empty
Solution 1
You have very well isolated the problem:
if name or loca == None:
Here you think it says:
"If either name or loca equal none:"
But instead it says:
"if (name) is true or (loca equals None) is true:"
Where it should say:
"if (name equals none) is true or (loca equals none) is true:"
Which is:
if name is None or loca is None:
See, by the way, that None comparisons are better carried out with is
, since there is only one None
object.
Also, a more pythonic way of doing it is:
if not all((name, loca)):
Or, seeing as "all" it's just 2 variables:
if not (name and loca):
If you don't understand, read around a bit (the Python tutorial is excellent -- go for the conditionals part). Good luck!
Solution 2
try this
if not all([name, loca]):
print "Please enter valid details"
ask()
Solution 3
Well, neither name
nor loca
can ever be None
after running ask()
. At worst they're empty strings: ''
. What you're doing is asking if name
is True
, which it is if name
has any value other than ''
.
What you want to do is check if the names have a non-empty value:
if not (name and loca):
…
should be fine.
Solution 4
if name or loca == None:
This will never trigger for two reasons:
First, if you don't enter any data, you get an empty string, not
None
, soloca == None
will never be true.Second, your
if
statement is checking two things: whethername
is truthy (contains any data), and whetherloca == None
. You probably meantif name == None or loca == None
.
Combining these two things, you can write:
if name == "" or loca == "":
Or, simplifying and taking advantage of the fact that strings are "truthy" if they contain data:
if not (name and loca):
Markum
Hi! I am Mark, a somewhat newcomer to the world of programming. I have really gained an interest in Python, and it is what I write the most of my code in. Currently, I'm working on creating various features for a small but interesting IRC bot, learning all different aspects of Python as I go along.
Updated on June 07, 2022Comments
-
Markum almost 2 years
def ask(): global name, loca print "What's your name?" name = raw_input('> ') print "Where are you from?" loca = raw_input('> ') if name or loca == None: print "Please enter valid details." ask() ask() print "Alright, so you're " + name + ", from " + loca + "."
With this script, it will only ever print the last line if both of my variables are empty. If I fill in one, or both, it triggers that
if
, making me redo the function.What am I doing wrong here?