+ 1

Why doesn't it work properly

why this function always gives the answer "winter"? def season(a): b = None if a == '1' or '2' or '12': b = "winter" elif a == '3' or '4' or '5': b = "spring" elif a == '6' or '7' or '8': b = "summer" elif a == '9' or '10' or '11': b = "autumn" else: b = "This month does not exist" print(b) season(a = input(str("Enter a number moth: ")))

9th Nov 2018, 4:02 PM
Alex Buckner
Alex Buckner - avatar
6 odpowiedzi
+ 4
Because an not-empty string is always valued like true then first "if" condition will be always true without take cure if a=='1' or not. You have to detect if any var is equals to multiple values like: if a=='1' or a=='2' or a=='12': ...
9th Nov 2018, 4:12 PM
KrOW
KrOW - avatar
+ 8
You wrote, if a == '1' or '2' or '12': It is parsed as* if (a == '1') or ('2') or ('12'): Even if a is not '1', the string '2' and '12' both evaluate as True (in fact, any nonempty string is True). So you're basically saying if (a == '1') or (True) or (True): That's obviously True, so that block is executed everytime. Fix: if a == '1' or a == '2' or a == '12': Or, if a in {'1', '2', '12'}: Note: You'll have to do the same for other parts of your code too. *Because == has higher precedence than or: https://docs.python.org/3/reference/expressions.html#operator-precedence
9th Nov 2018, 4:13 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 6
You're welcome! The Q&A section is there for questions exactly like this! If you get stuck coding something, first use the search bar to see if there are similar questions asked before, and if you don't find anything, post it here with your attempted code and appropriate tags. We'd be more than happy to help! Cheers! 😊
9th Nov 2018, 4:43 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
👍👍👍
9th Nov 2018, 4:20 PM
KrOW
KrOW - avatar
+ 1
I've been thinking all day why it doesn't work :D
9th Nov 2018, 4:38 PM
Alex Buckner
Alex Buckner - avatar
0
thanks for answers
9th Nov 2018, 4:20 PM
Alex Buckner
Alex Buckner - avatar