'Python Odd and Even
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.")
Solution 1:[1]
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.
Solution 2:[2]
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.")
Solution 3:[3]
I think you don't need for loop, Remove for loop and try again.
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
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.")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CocompleteHippopotamus |
| Solution 2 | Tim Roberts |
| Solution 3 | Sk Kamal Hossain |
