In: Computer Science
Python: Write a function named calc_odd_sum that accepts a positive integer as the argument and returns the sum of all the odd numbers that are less than or equal to the input number. The function should return 0 if the number is not positive. For example, if 15 is passed as argument to the function, the function should return the result of 1+3+5+7+9+11+13+15. If -10 is passes, it shall return 0. You shall run the program test the result at least two times, one is a positive number and the other is negative number.
Python code:
#defining calc_odd_sum function
def calc_odd_sum(num):
#initializing total as 0
total=0
#checking if the number is not positive
if(num<=0):
#returning 0
return 0
else:
#looping from 1 to number
for i in range(1,num+1):
#checking if the number is odd
if(i%2!=0):
#adding the number to total
total+=i
#returning total
return total
#calling calc_odd_sum function and printing result for positive
number
print(calc_odd_sum(15))
#calling calc_odd_sum function and printing result for negative
number
print(calc_odd_sum(-10))
Screenshot:
Output: