How to add two numbers in Python
How to add two numbers in Python.
Here is a step-by-step tutorial on how to add two numbers in Python using different code examples:
Open your preferred Python Integrated Development Environment (IDE) or text editor and create a new Python file.
Start by declaring two variables to store the numbers you want to add. For example, let's say we want to add the numbers 5 and 3. We can declare the variables as follows:
num1 = 5
num2 = 3
Now, you have two options to add these numbers:
a. Using the
+operator:You can simply use the
+operator to add the values of the two variables. Assign the result to a new variable or print it directly. Here's an example:result = num1 + num2
print("The sum is:", result)Output:
The sum is: 8b. Using the
sum()function:Python provides a built-in function called
sum()to add multiple numbers. You can pass the numbers as an iterable, such as a list or tuple. Here's an example:result = sum([num1, num2])
print("The sum is:", result)Output:
The sum is: 8Another approach is to create a function that takes two arguments and returns the sum. This way, you can reuse the code whenever you need to add two numbers. Here's an example:
def add_numbers(a, b):
return a + b
result = add_numbers(num1, num2)
print("The sum is:", result)
Output:
The sum is: 8
- If you want to add numbers entered by the user, you can use the
input()function to get the input as strings and then convert them to integers. Here's an example:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 + num2
print("The sum is:", result)
Output:
Enter the first number: 5
Enter the second number: 3
The sum is: 8
That's it! You now know different ways to add two numbers in Python. Feel free to choose the method that suits your needs best.