2. Assume that n has been declared as an integer variable and received a positive value which is unknown to us, you write statements to sum all values from 1 to n with a step size at 2 and print out the summation. For example, if n is 4, the summation is 4 because 1 + 3 equals 4; if n is 5 the summation is 9 because 1 + 3 + 5 equals 9.
Dear Student,
Please find the attached code for the required problem definition:
def sum_n(n):
# initializing the value of sum variable
sum = 0
# setting up the for loop with required step size of 2 starting from 1 to n+1
for i in range(1,n+1,2):
sum += i # adding all the values
print(sum) # printing the value of the sum variaable
n = int(input()) # taking user input for n
sum_n(n) # calling the function
Thank you, please upvote if you liked it!
Get Answers For Free
Most questions answered within 1 hours.