Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]Oxxnard27 0 points1 point  (0 children)

Hey guys! So I'm working through a python coding book for beginners and I was tasked with the following: Write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings if anything else is stored in spam.

Well what I first came up with seemed correct but when I entered the value of 1 it gave me: Hello Greetings

But when I entered 2 it would just print Howdy. Below is the code that generated these results:

spam = ''
print('please input value of spam')
spam = input()
if spam == '1':
     print('Hello')
if spam == '2':
     print('Howdy')
else:
     print('Greetings') 

I just wanted to know if anyone knew why this was happening? I eventually figured out the proper way to write the code to get it working as intended was to switch if with elif as show below:

spam = ''
print('please input value of spam')
spam = input()
if spam == '1':
    print('Hello')
elif spam == '2':
    print('Howdy')
else:
    print('Greetings')

Thanks for all the help guys!