Issue
Given an input range (lowest/highest) and choice(odd/even) how can I print the desired output in python? In the below code it doesn't seem to be executing the else condition
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
oddeven = input("Do you want to see odd or even numbers: ")
print(oddeven)
for num in range(low, high):
if (num % 2 == 0):
print(num)
else :
if (num % 2 == 1):
print(num)
Solution
I think the easiest solution to implement, would be for you to create two for loops, one for the even
case and one for the odd
case, so you only have to check once rather than for each iteration of the for loop:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
low = get_int_input("Enter the lowest number in the range (inclusive): ")
high = get_int_input("Enter the highest number in the range (inclusive): ")
valid_odd_even_responses = {"odd", "even"}
odd_even_response = ""
while odd_even_response not in valid_odd_even_responses:
odd_even_response = input(
"Do you want to see odd or even numbers: ").lower()
if odd_even_response == "odd":
for num in range(low, high + 1):
if num % 2 == 1:
print(num)
else:
for num in range(low, high + 1):
if num % 2 == 0:
print(num)
Example Usage:
Enter the lowest number in the range (inclusive): -1
Enter the highest number in the range (inclusive): 13
Do you want to see odd or even numbers: even
0
2
4
6
8
10
12
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.