How to Add Two Numbers in Python ?
Adding two numbers in Python is straightforward. You can simply use the + operator. Here’s how you can do it:
1. Adding Two Numbers Directly
a = 5
b = 3
result = a + b
print(result) # Output: 8
2. Adding Two Numbers Entered by the User
You can use the input() function to get numbers from the user, convert them to integers or floats, and then add them.
# Get user input as integers
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
# Add the numbers
result = a + b
# Print the result
print("The sum is:", result)
3. Adding Floating Point Numbers
If you’re working with decimal numbers (floats), you can add them the same way as integers.
a = 5.5
b = 3.2
result = a + b
print(result) # Output: 8.7
4. Adding Two Numbers Inside a Function
You can also create a function to add two numbers and return the result.
def add_numbers(a, b):
return a + b
# Example usage
result = add_numbers(10, 20)
print(result) # Output: 30
Summary:
- Use the
+operator to add two numbers. - Convert input values to integers or floats if needed using
int()orfloat().