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?
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!
try this
if not all([name, loca]):
print "Please enter valid details"
ask()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With