I am writing a program to calculate the sum of odd and even numbers between 1-50.
This is what I have so far:
Display the message
print("Sums of odd and and even numbers")
print("="*45)
Ask the user whether they want to continue or not.
ch = 'y'
while(ch == 'y'):
# Prompt the user to enter a number.
# Store the number entered by the user in the variable n.
num =int(input('Enter a whole number between 1 and 50: '))
# If the number entered by the user is in the range 1-50
while(num<1 or num>50):
num = int(input("Try again. Your number must be between 1 and 50: "))
# Check if the valid number entered by the user is even or odd.
# If number mod 2 == 0, then the number is even
if num%2 == 0:
# Print the message.
print('')
print('Your number is an even number. ')
# Initialize the variable even_sum to 0.
# This variable is used to store sum of even numbers
even_sum=0
# for loop to find sum of even numbers
for i in range(2,num+1,2):
even_sum+=i
# Print the sum of the even numbers from 2 till the number
# entered by the user.
print('The sum of the even numbers from 2 to %d is : '%num,even_sum)
else:
# If number mod 2 is not equal to 0, print the message.
# So, the number is odd.
print('')
print('Your number is an odd number.')
# Initialize the variable odd_sum to 0.
# This variable is used to store sum of odd numbers
odd_sum=0
# for loop to find sum of odd numbers
for i in range(1,num+1,2):
odd_sum+=i
# Print the sum of the odd numbers from 1 till the number
# entered by the user.
print('The sum of odd numbers from 1 to %d is: '%num,odd_sum)
print('')
# Ask the user whether he/she wants to continue the program.
ch = input("\n Try again? (y/n) ")
The program works but I just need to add a loop that checks If num is not and integer. Like if the num is a floating point number or a string, then prompt again to input a whole number between 1 and 50