Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elif block not executing in Python

What is wrong here? Upon entering 3 (<=5), the output should be, I think, "Phew, ..." but it stays as "Awesome, ..."

weather = raw_input('How is the weather today, from 0 to 10? ')
answer = raw_input ('Are you in mood to go out? ')
if weather >= 5:
    if answer == 'Yes':
        print 'Awesome, I will go out!'
        print 'Will you come with me?'
    else:
        print 'Awesome, I am going out now!'
elif weather <= 5:
    print "Phew, I didn't want to go outside, great, I will stay in! Thank God!"
else:
    print "Huh?"
like image 459
supernova Avatar asked Apr 14 '26 02:04

supernova


2 Answers

raw_input returns a string not an integer, e.g. '3' instead of 3.

In Python 2, strings always compare greater than integers so weather >= 5 is always true.

To fix this, cast weather to an integer:

weather = int(raw_input('How is the weather today, from 0 to 10? '))
like image 77
Alex Riley Avatar answered Apr 15 '26 15:04

Alex Riley


raw_input returns a string and you need to convert it to integer.

weather = int(raw_input('How is the weather today, from 0 to 10? '))

And you need to catch any exceptions for handling wrong inputs.

like image 25
user3885927 Avatar answered Apr 15 '26 14:04

user3885927



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!