Why does Python run the line of code 'if p == 2 or 3' even when the input p is equal to 1? Can someone point out the mistake? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does Python run the line of code 'if p == 2 or 3' even when the input p is equal to 1? Can someone point out the mistake?

from math import sqrt as s p = int(input("Enter your number: ")) list = [p] if p>=4: for i in range(2,int(s(p))): if p % i == 0: print(p,"is not a prime number") list[:] = [] break else: continue if p in list: print(p,"is a prime number") if p == 1: print('1 is neither prime nor composite') if p == 2 or 3: print('{} is a prime number'.format(p))

26th May 2018, 6:01 PM
Shohan Dutta Roy
Shohan Dutta Roy - avatar
3 Answers
+ 2
to expand on Jan Markus explanation: python sees p == 2 or 3 as (p == 2) or 3 and since 3 is not zero, 3 is alway interpreted as true so you have (p==2) or true, which is always true
26th May 2018, 8:41 PM
Max
Max - avatar
+ 2
You could also use: if p in (2, 3):
26th May 2018, 8:51 PM
Manuel Maier
Manuel Maier - avatar
0
Thanks everyone, that was a silly mistake on my part
26th May 2018, 10:02 PM
Shohan Dutta Roy
Shohan Dutta Roy - avatar