+ 1

Why for loops is so strange when I use they with "if" and "or"?

I don't matter why when I make code like: For i in range(9): if i == 1 or 2: print ("P") "P" was printing 8 times, but not only 2. Why? I has been 1 once, and 2 similar once. P have to print only 2 times https://code.sololearn.com/cLcZBylXuT40/?ref=app

16th Jun 2021, 3:11 PM
Ласковый Зверёк
Ласковый Зверёк - avatar
4 ответов
+ 4
Operator precedence, https://www.google.com/url?sa=t&source=web&rct=j&url=https://docs.JUMP_LINK__&&__python__&&__JUMP_LINK.org/3/reference/expressions.html&ved=2ahUKEwid3s3muJzxAhWmwTgGHQ17AkoQFjALegQIHBAC&usg=AOvVaw20xmig3bG9EQm1_XcCKiMh&cshid=1623856603576 Look at the end part in above article . "==" has higer precedence than "or", so python interpret it as , if (i=="!") or "," in the above statement "," has some value , i.e. it isn't zero so if statement is always true , no mater if i is equal to "!" or not.
16th Jun 2021, 3:21 PM
Abhay
Abhay - avatar
+ 1
I==1 or 2 is always true condition because it's equal to and evaluated as (i==1) or (2) : so anything is treated as true in boolean equivalent, other than value 0 or ""(empty string ) or null values So it it like (I==1) or true => true so that's why "P" will be printed.... you need actually there I==1 or I==2 in python, it can shorten many types.. like (I in (1,2))
16th Jun 2021, 3:17 PM
Jayakrishna 🇮🇳
0
Try it in that way: for i in range(2): #if i == 1 or 2: not necessary print ("P")
16th Jun 2021, 4:28 PM
Angela
Angela - avatar
- 1
It’s printed 21 times in the linked example because len of text is 21. And its printed 9 times in the example above because range(9) means 9 times.
16th Jun 2021, 4:20 PM
Angela
Angela - avatar