Newbie Python Trouble with "if"/"else"/"elif"

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

Newbie Python Trouble with "if"/"else"/"elif"

Post by Spectre557 on Mon May 04, 2009 12:57 pm
([msg=23137]see Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Hey, I've just started learning Python, and I'm trying to use conditions like "if" to vary the output given.

The idea was to get a different response depending on whether they say "yes" or "no". To keep things simple, I tried using something along the lines of "if the user says they are ready, do this, or else just give an alternative output". Ignore "time.sleep", that's just to give a more conversational-style element by using delayed response, and "F1" and "F2" are just pre-defined strings containing tabs and new lines to help with the formatting.

Code: Select all
time.sleep(1); response = raw_input("Are you ready?")

if (response == "yes" or "Yes" or "YES"):
   time.sleep(2); print (F1 + "Alrighty then, let's begin!" + F2)
else:
   time.sleep(2); print (F1 + "Oh..." + F2)


The output is always "Alrighty then, let's begin!" no matter what I enter, so it would appear there's a problem with the "else" bit. I've had a look at several sources online, but I can't put my finger on where I've gone wrong here, so would anyone mind giving me a simplified explanation of how to use these effectively?

Bear in mind I'm almost completely new to programming! :roll:

P.S. I had a look at "elif" but decided that I should stick to this method for the time being... was I wrong?
Current obsession: Minecraft
User avatar
Spectre557
Poster
Poster
 
Posts: 215
Joined: Wed Apr 29, 2009 4:04 am
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by aNewHobby4me on Mon May 04, 2009 1:35 pm
([msg=23140]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Code: Select all
if (response == "yes" or "Yes" or "YES")


This always evaluates to TRUE.

Try converting response to all lowercase and it might flow better, something along the lines of

Code: Select all
if (response.tolower == "yes")


Hope this helps :)
"To understand recursion you must first understand recursion."
aNewHobby4me
Poster
Poster
 
Posts: 185
Joined: Thu Jan 08, 2009 5:44 pm
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by AtlasDark on Mon May 04, 2009 2:38 pm
([msg=23146]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Doesn't ELIF translate to an IFF function? Something performed when a specific set of requisites are filled (a tad hard for me to explain, since what I'm conveying is strikingly similar to a standard 'if' nest)?
User avatar
AtlasDark
Poster
Poster
 
Posts: 175
Joined: Sun Apr 05, 2009 10:40 pm
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by Defience on Tue May 05, 2009 9:20 am
([msg=23184]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Try something like this:

Code: Select all
ans = "yes"
response = raw_input("Are you ready? ") #put a space between the '?' and last quote marks
if response == ans:
    print "Something"
elif response != ans:   # this says if the response is NOT equal to
    print "Something else"
User avatar
Defience
Addict
Addict
 
Posts: 1277
Joined: Thu Jun 12, 2008 3:16 pm
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by Spectre557 on Tue May 05, 2009 12:26 pm
([msg=23198]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Thanks for the responses :)

aNewHobby4me wrote:
Code: Select all
if (response == "yes" or "Yes" or "YES")
This always evaluates to TRUE.

Why is that? Or do you only know that based on the response from the program?

aNewHobby4me wrote:Try converting response to all lowercase and it might flow better, something along the lines of
Code: Select all
if (response.tolower == "yes")
Hope this helps :)

Hmm, well if i try to do this I get this error:
Code: Select all
AttributeError: 'str' object has no attribute 'tolower'

Do I need to import "tolower" from a module?

AtlasDark wrote:Doesn't ELIF translate to an IFF function? Something performed when a specific set of requisites are filled (a tad hard for me to explain, since what I'm conveying is strikingly similar to a standard 'if' nest)?

I'm really not sure there, someone with more experience will have to answer this one. :)

Defience wrote:Try something like this:
Code: Select all
ans = "yes"
response = raw_input("Are you ready? ")
#put a space between the '?' and last quote marks if response == ans:
print "Something"elif response != ans:   # this says if the response is NOT equal to
print "Something else"

Thanks for the workaround, this is useful to allow me to continue from here, but on the other hand, it's seems a slightly clunky method to have to use with any regularity.

What I'm really looking for here, is an explanation on why the code I'm trying to use at the moment isn't working the way I wanted it to. I'm more looking to learn what works and why, rather than just getting the job done any way possible. Means, not ends! :lol:

That said, I appreciate the responses thus far, cheers guys!
Current obsession: Minecraft
User avatar
Spectre557
Poster
Poster
 
Posts: 215
Joined: Wed Apr 29, 2009 4:04 am
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by aNewHobby4me on Tue May 05, 2009 4:49 pm
([msg=23214]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Spectre557 wrote:
aNewHobby4me wrote:
Code: Select all
if (response == "yes" or "Yes" or "YES")
This always evaluates to TRUE.

Why is that? Or do you only know that based on the response from the program?


Let me add parentheses to your conditional and explain:
Code: Select all
if ( (response == "yes") or ("Yes") or ("YES")  )


I know you intended to compare response to each of these, but that is not the way it played out.

Code: Select all
if ( (response == "yes") or (response =="Yes") or (response =="YES")  )


This code will execute as you wanted.

Code: Select all
if ( "Yes" )


This will return true in python (I just tried it to be sure.) As you or'ed something that will always returns true with your (response == "yes") it could never be false.

Spectre557 wrote:
aNewHobby4me wrote:Try converting response to all lowercase and it might flow better, something along the lines of
Code: Select all
if (response.tolower == "yes")
Hope this helps :)

Hmm, well if i try to do this I get this error:
Code: Select all
AttributeError: 'str' object has no attribute 'tolower'

Do I need to import "tolower" from a module?


For this, I apologize. I should have tested it before posting. The corrected code is

Code: Select all
if (response.lower == "yes")


It will convert response to all lowercase for the purpose of your comparison, and has the benefit of not changing the value of response.

Code: Select all
IDLE 2.6.2     
>>> a = "LOWER"
>>> a.lower()
'lower'
>>> a
'LOWER'


Spectre557 wrote:What I'm really looking for here, is an explanation on why the code I'm trying to use at the moment isn't working the way I wanted it to. I'm more looking to learn what works and why, rather than just getting the job done any way possible. Means, not ends! :lol:

That said, I appreciate the responses thus far, cheers guys!


You are very welcome :)
"To understand recursion you must first understand recursion."
aNewHobby4me
Poster
Poster
 
Posts: 185
Joined: Thu Jan 08, 2009 5:44 pm
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by Defience on Wed May 06, 2009 10:14 am
([msg=23253]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

I'm a little surprised you find this clunky:
Code: Select all
ans="yes"
response = raw_input("Are you ready? ")
if response == ans:
    print "Alrighty then, let's begin!"
elif response != ans:
    print "Oh..."


but not this:
Code: Select all
time.sleep(1); response = raw_input("Are you ready?")

if (response == "yes" or "Yes" or "YES"):
   time.sleep(2); print (F1 + "Alrighty then, let's begin!" + F2)
else:
   time.sleep(2); print (F1 + "Oh..." + F2)


but that's the joy of programming.. 8-) ..and mine was just to show you the 'not equal to' statement. Anyway, to ignore the uppercase, like aNewHobby4me said, use .lower:

Code: Select all
response = raw_input("Are you ready? ")
if response.lower() == "yes":
    print "Alrighty then, let's begin!"
else:
    print "Oh..."


output examples:
Code: Select all
>>>
Are you ready? yes
Alrighty then, let's begin!
>>>
Are you ready? Yes
Alrighty then, let's begin!
>>>
Are you ready? YES
Alrighty then, let's begin!
>>>
Are you ready? No
Oh...
>>>Are you ready? Foo
Oh...


-- Wed May 06, 2009 11:46 am --

Or you could even add in more if statements:

Code: Select all
response = raw_input("Are you ready? ")
if response.lower() == "yes":
    print "Alrighty then, let's begin!"
if response.lower() == "no":
    print "Try again later when you are ready"
elif response.lower() != "yes":
    print "Please enter a yes or no response"


I know that's not very elegant and could use refined but you get the idea:

Code: Select all
>>>
Are you ready? YES
Alrighty then, let's begin!
>>>
Are you ready? nO
Try again later when you are ready
>>>
Are you ready? foo
Please enter a yes or no response
User avatar
Defience
Addict
Addict
 
Posts: 1277
Joined: Thu Jun 12, 2008 3:16 pm
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by tgoe on Wed May 06, 2009 3:32 pm
([msg=23277]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

The elif is probably in the language because python doesn't have a switch/case construct. This is fine for a small number of options but once you get a whole page full of elifs things become tedious. You can use a dictionary to try and work around this:

Code: Select all
#imagine many more options and all those elifs you would have to write!

messages = {         "c" : "Nope, try again!",
                   "php" : "... ick!",
                  "lisp" : "Holy parentheses batman!",
            "javascript" : "That's not it...",
                "python" : "You are correct, sir!",
                  "ruby" : "Seems weird, no."
           } 

response = raw_input("What is my favorite language? ")

try:
    print(messages[response.lower()])
except KeyError:
    print("I've never tried that language...")
User avatar
tgoe
Contributor
Contributor
 
Posts: 638
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by Spectre557 on Thu May 07, 2009 4:10 am
([msg=23306]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

aNewHobby4me wrote:This will return true in python (I just tried it to be sure.) As you or'ed something that will always returns true with your (response == "yes")

I think I understand what you mean here, I'll need to be more careful with my "phrasing".

Defience wrote:I'm a little surprised you find this clunky

Heh, well that's just the first impression I got when I looked over it, but I don't really have enough experience to know what will be more efficient in practice. :)

tgoe wrote:The elif is probably in the language because python doesn't have a switch/case construct. This is fine for a small number of options but once you get a whole page full of elifs things become tedious. You can use a dictionary to try and work around this

Hmm, that's interesting. Thanks for sharing.

Thanks for clearing this up guys, consider me educated! :geek:
Current obsession: Minecraft
User avatar
Spectre557
Poster
Poster
 
Posts: 215
Joined: Wed Apr 29, 2009 4:04 am
Blog: View Blog (0)


Re: Newbie Python Trouble with "if"/"else"/"elif"

Post by Defience on Thu May 07, 2009 8:23 am
([msg=23316]see Re: Newbie Python Trouble with "if"/"else"/"elif"[/msg])

Glad we could offer you some suggestions and as you can see between aNewHobby4me, tgoe, you & me....we all had different ideas about this, also another good reason to add # comments when programming :ugeek:
User avatar
Defience
Addict
Addict
 
Posts: 1277
Joined: Thu Jun 12, 2008 3:16 pm
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests