How To Use a Sum() Function In Python
The sum function is one of the most commonly used functions in Python programming. It is a built-in function that allows you to add numbers or items in a list together. The sum function is a valuable tool for calculate the sum (totals) in a variety of applications.
Basic Syntax and Parameters of Sum Function
The basic syntax of the sum function is “sum(iterable, start=0)”. The “iterable” parameter is the list, tuple, or set of numbers that you want to add together. The “start” parameter is an optional parameter that allows you to provide an initial value to start adding with. By default, the “start” parameter is set to 0.
How to use Sum() in Python – Examples of Using Sum Function:
Example 1 of Python sum method: Using the sum() to add up a list of numbers with print sum
numbers = [2, 4, 6, 8]
total = sum(numbers)
print(total)
Output: 20
Example 2 Python sum method: Using the sum() to find the sum total cost of items in a shopping cart with print sum
cart = {'Apple': 1.25, 'Banana': 0.75, 'Orange': 1.00}
total_cost = sum(cart.values())
print(total_cost)
Output: 3.00
Example 3 Python sum method : Using the sum() to calculate the total amount of rainfall in a given period with print sum
rainfall = {'January': 2.5, 'February': 3.0, 'March': 1.5, 'April': 2.0}
total_rainfall = sum(rainfall.values())
print(total_rainfall)
Output: 9.0
Tips and Tricks for Using Sum()
- Always make sure to pass an iterable to the sum function. If you pass a non-iterable object, such as an integer, you will receive a TypeError.
- Use list comprehensions to create the iterable to be passed to the sum function. List comprehensions are a concise way to create a list of numbers to add together.
- Be mindful of the data type of the iterable being passed to the sum function. If the iterable contains non-numeric values, such as strings, you will receive a TypeError.
Conclusion
This function is an essential tool for Python programmers. It simplifies the process of adding numbers or items in a list together. By understanding the basic syntax and parameters of this python functions, and applying the tips and tricks outlined in this article, you can leverage the power of the sum function in your Python programming endeavors.
Thank you for sharing such good information. Very informative and effective post. Keep it up!