Here is a simple Python program that adds two numbers and prints the result:
Example 1: Add Two Numbers
# Define the two numbers num1 = 10 num2 = 20 # Calculate the sum of the two numbers sum = num1 + num2 # Print the result print(sum)
Example 2: Add Two Numbers With User Input
# Ask the user for two numbers num1 = input("Enter a number: ") num2 = input("Enter another number: ") # Convert the input strings to numbers (we assume they are both integers in this example) num1 = int(num1) num2 = int(num2) # Add the numbers and store the result in a variable result = num1 + num2 # Print the result to the user print("The result is:", result)
This code first asks the user for two numbers using the
input() function. The
input() function takes a string as an argument, which is the prompt that will be displayed to the user. In this case, the prompt asks the user to enter a number.
Next, the code converts the input strings to integers using the
int() function. This is necessary because the
input() function always returns a string, even if the user enters a number.
After that, the code adds the two numbers and stores the result in a variable called
result. Finally, the code prints the result to the user using the
You can try running this code yourself to see how it works. Just make sure to replace the example numbers with your own input.
Thanks for reading. Happy coding!