supernova
supernova

Reputation: 23

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?"

Upvotes: 2

Views: 100

Answers (2)

Alex Riley
Alex Riley

Reputation: 177018

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? '))

Upvotes: 12

user3885927
user3885927

Reputation: 3503

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.

Upvotes: 2

Related Questions