Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one of all variables is empty

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?

like image 981
Markum Avatar asked May 16 '12 23:05

Markum


3 Answers

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!

like image 119
slezica Avatar answered Nov 12 '22 23:11

slezica


try this

if not all([name, loca]):
   print "Please enter valid details"
   ask()
like image 4
gefei Avatar answered Nov 13 '22 00:11

gefei


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.

like image 1
kojiro Avatar answered Nov 12 '22 23:11

kojiro