Please help me what I'm missing here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please help me what I'm missing here?

Hi! So, I've just stared to learn python on my own and started to practice watching videos beside Sololearn. There was an excercise, so I created a code, somewhat similar to this one: ----------------------------------- a = 0 b = "k" if a > 0 and b == "K" or b == "k": print("ok") else: print("nok") Result: "ok" ------------------------------------- I can't figure out why? In the "if" statement, I'm saying that "a" has to be grater than 0, which is clearly not true in this case, but the result turns out to be "ok". The weirdest part is that if b = "K" (with big capitals), the result will be "nok". What is it in this code and in the basic logical operators I'm missing? Thanks!

1st Oct 2020, 2:51 PM
Snookerson
3 Answers
+ 7
According to the operator precedence, "and" has a higher priority than "or". this means that the evaluation will be done like shown here with brackets: if (a > 0 and b == "K") or (b == "k"): see alos the explanations from Julia Shabanova .
1st Oct 2020, 3:00 PM
Lothar
Lothar - avatar
+ 5
if (a > 0 and b == "K")= False or b == "k" = True So it's true, and if b ==K you get False or False=False
1st Oct 2020, 2:55 PM
Julia Shabanova
Julia Shabanova - avatar
+ 2
Thank you for your quick answers! It's clear now! 🙂
1st Oct 2020, 3:05 PM
Snookerson