Home > Software engineering >  Python Odd and Even
Python Odd and Even

Time:03-02

I am very new to python. I am trying to write a program that tests if a number is between a given range, then tells you if the number is odd or even. I am having trouble with the part that detects if it is odd or even. It seems that if it just repeats my even statement. Here is the code:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if num >= 1 and num <= 50:
        for num in range (1, 50):
            if (num % 2 == 0):
                print("Your number is even.")
        else:
            print("Your number is odd.")
        
    else:
        print("Try again. Number must be 1 through 50.")

CodePudding user response:

I don't think you need a for loop at all, and you forgot to indent the else part if your inner if-else:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if num >= 1 and num <= 50:
        for num in range (1, 50):  # not needed
            if (num % 2 == 0):
                print("Your number is even.")
            else:  # here
                print("Your number is odd.")
    else:
        print("Try again. Number must be 1 through 50.")

for-else constructs exist (and are pretty neat), but it you're starting to learn Python, it's a story for another time.

CodePudding user response:

Nope, you don't need the for loop:

while True:
    num = int(input("Please enter an integer between 1 and 50: "))
    if 1 <= num <= 50:
        if num % 2 == 0:
            print("Your number is even.")
        else:
            print("Your number is odd.")        
    else:
        print("Try again. Number must be 1 through 50.")
  • Related