Write A Lambda Function To Print Sum Of All Numbers Between M And N

Hi Guys, welcome to my blog in this article you will learn about how to Write A Lambda Function To Print Sum Of All Numbers Between M And N.

 

Title : 

Write A Lambda Function To Print Sum Of All Numbers Between M And N



Write A Lambda Function To Print Sum Of All Numbers Between M And N


 

Description : 

Hey guys in this article you will learn how to compute the sum of numbers between m and n. Define a lambda function named as sum_mn() and user lambda keyword with input argument names as x and y. Use the range() function to get the range between x+1 and y. The reason I am using x+1 here is to get the excluding range between m and n. Once we get the list of numbers between m and n, sum all the numbers and return the sum.


    
sum_mn = lambda x, y: sum(range(x+1, y))


    


In the main program take two variables m and n, ask the user to enter two integer variables and store them.


    
m = int(input("Enter Value of M : "))
n = int(input("Enter Value of N : "))


    


Once we get values of m and n check if n value is less than m if so print error message, else call the above lambda function.


    
if n < m:
   print("Value of n should be greater than m")
else:
   print(f"Sum of all numbers between {m} and {n} is : {sum_mn(m, n)}")

    




Complete Python Code : 


    
sum_mn = lambda x, y: sum(range(x+1, y))

m = int(input("Enter Value of M : "))
n = int(input("Enter Value of N : "))

if n < m:
   print("Value of n should be greater than m")
else:
   print(f"Sum of all numbers between {m} and {n} is : {sum_mn(m, n)}")


    

 

 

Output : 


    
Enter Value of M : 1
Enter Value of N : 100
Sum of all numbers between 1 and 100 is : 4949


    

 

Output : 


    
Enter Value of M : 1
Enter Value of N : 3
Sum of all numbers between 1 and 3 is : 2


    



Conclusion :

The above Python program defines a lambda function that takes input as m and n integer values and then gets the numbers between m and n and sum all the numbers present in the middle. In the main program we will ask users to enter m and n values and call the lambda function once the lambda function gets executed the sum will be printed using print function call. Comment it down below if you have any suggestions to improve the above Python program

 

Post a Comment

0 Comments