knowone
knowone

Reputation: 840

Number Comparison in Python displays wrong result

I'm starting to practice Python programming so please excuse if it's some very basic concept for you.

I'm trying to print result based on number comparison.

User Input: Any number between 1 to 100 Outputs: Based on comparisons, the output should be printed accordingly. Please look at the code below:

x = int(input("Enter a number: ").strip())

if 0<x<101:
    if (x%2 == 1):
       print("Weird")
    elif (x%2 == 0 & 1<x<6):
       print("Not Weird -  between 2 to 5; inclusive")
    elif (x%2 == 0 & 5<x<21):
       print("Weird -  between 5 to 20; inclusive")
    elif (x%2 == 0 & x>=20):
       print("Not Weird - Greater than 20")
    else:
        print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")

It does the job for first 3 if comparisons. But if I input any even number above 20, it prints the final else loop statement.

I modified the last if to 20<x<100, then it runs properly.

For some reason, I can't get the x>20 condition work. Any ideas what I'm doing wrong?

Upvotes: 1

Views: 85

Answers (2)

AER
AER

Reputation: 1531

Quick Answer: Use and instead of &. and is for boolean operators and & is used for bitwise operations (can be good for arrays which this is not).

Another note, you have 5<x<20 which is not actually inclusive of 5 and 20 (use 5<=x<=20 or 4<x<21) and x>=20 is not just greater than 20 it is also equal (use x>20). However if you actually want to restrict it to less than or equal to 100 obviously use 20<x<101.

Upvotes: 1

knowone
knowone

Reputation: 840

As suggested by outflanker in the comments above, pasting the corrected code.

x = int(input("Enter a number: ").strip())

if 0<x<101:
    if (x%2 == 1):
       print("Weird")
    elif (x%2 == 0 and 1<x<6):
       print("Not Weird -  between 2 to 5; inclusive")
    elif (x%2 == 0 and 5<x<21):
       print("Weird -  between 5 to 20; inclusive")
    elif (x%2 == 0 and x>=20):
       print("Not Weird - Greater than 20")
    else:
        print("Please enter a number between 1 & 100, limits inclusive. Exiting program...")

Upvotes: 0

Related Questions