Write a python while loop that sums all the numbers from m to n, where “m” and “n” are both user given values.
Code with while loop.
m = int(input("enter the value of m ")) n = int(input("enter the value of n "))
tmp1=m tmp2=n sum_till_m=0 while(m>0) : sum_till_m +=m m = m - 1 sum_till_n = 0 while (n > 0): sum_till_n += n n = n - 1 if ( tmp1 > tmp2 ) : ans = sum_till_m - sum_till_n + tmp2 else : ans = sum_till_n - sum_till_m + tmp1 print(ans)
The code without using while loop. but more optimised
m = int(input("enter the value of m ")) n = int(input("enter the value of n ")) sum_till_n = (n*(n+1))/2 sum_till_m = (m*(m+1))/2 if ( m > n ) : ans = sum_till_m - sum_till_n + n else : ans = sum_till_n - sum_till_m + m print(ans)
Get Answers For Free
Most questions answered within 1 hours.