Sunday, April 14, 2024
HomeComputer Science OutreachLearn Python: Create a program for users to input and add two...

Learn Python: Create a program for users to input and add two numbers.

Start learning Python programming by trying this simple example!

The Python code above creates a simple program that allows users to enter two numbers to add together, and then prints the result on the screen.
You can use our Python editor to write and execute the code above. Open the editor and type in the code exactly as it appears in the image above.

Explanation of the code

  1. The first two lines of the program use the input() function to prompt the user to enter two numbers. The function input() returns a string, so we store the user input in the variables num1 and num2.
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
  1. Since the input() function returns a string, we need to convert the inputs to integers so that we can add them together. We do this using the int() function and re-assign the values to num1 and num2.
    num1 = int(num1)
    num2 = int(num2)
  2. We add the numbers together and store the result in a variable called result.result = num1 + num2
  3. Finally, we use the print() function to display the result to the user. The print() function takes one or more arguments and prints them to the console.print(“The sum of”, num1, “and”, num2, “is”, result)

So when the program is run, the user is prompted to enter two numbers, the inputs are converted to integers, the numbers are added together, and the result is printed to the console in a message that tells the user what the sum of the numbers isFinally, we use the print() function to display the result to the user. The print() function takes one or more arguments and prints them to the console.

Dr. Troy Hawk, Ph.D.
Dr. Troy Hawk, Ph.D.
Research Scientist
- Advertisment -

Most Popular

Google IT Support Professional Certificate

Google Cybersecurity Professional Certificate

Learn to Create a Budget Using a Spreadsheet

Free Certified in Cybersecurity Courses

Recent Comments