In this tutorial, we will learn how to input three numbers in a Python program. This is a fundamental concept that will help you to understand user inputs and their use in basic calculations and operations.
Step 1: Use the input() function
The input() function allows your program to accept user input. In Python, this input is always considered a string (text) by default. Therefore, you need to convert the input to numerical values, such as integers or floats, before performing calculations. You can do this by using the int() or float() functions, which allow you to convert the input string to a number.
For example, if you want to input an integer value, you would write:
1 |
number1 = int(input("Please enter the first number: ")) |
Step 2: Input three numbers
Following the above example, you can input three numbers using the input() function. Make sure to provide a user prompt for each input to help the user know which number they are entering. Here’s how you can input three integer numbers:
1 2 3 |
number1 = int(input("Please enter the first number: ")) number2 = int(input("Please enter the second number: ")) number3 = int(input("Please enter the third number: ")) |
Step 3: Perform calculations or operations
With the three numbers stored in variables, you can now perform calculations or operations, such as adding or multiplying the numbers. For example, to calculate the sum of the three numbers, you can write:
1 |
total = number1 + number2 + number3 |
Step 4: Display the result
You can use the print() function to display the result of your calculation. Here’s how to display the sum of the three numbers calculated in the previous step:
1 |
print("The sum of the three numbers is:", total) |
Full Python code
1 2 3 4 5 6 7 |
number1 = int(input("Please enter the first number: ")) number2 = int(input("Please enter the second number: ")) number3 = int(input("Please enter the third number: ")) total = number1 + number2 + number3 print("The sum of the three numbers is:", total) |
Sample output
Please enter the first number: 5 Please enter the second number: 7 Please enter the third number: 9 The sum of the three numbers is: 21
Conclusion
By following this tutorial, you now know how to input three numbers in a Python program using the input() function, convert the inputs into numerical values, perform simple operations or calculations on the inputs, and display the result.
This knowledge will help you build more complex and interactive programs as you progress in your journey to learn Python programming.