In this tutorial, we will learn how to input two numbers in Python. This is a fundamental skill that every aspiring programmer should acquire, as working with user inputs is an essential aspect of programming and developing interactive applications.
Step 1: Using the input() Function
To receive input from the user, we will use Python’s built-in input() function. The function reads a line from the input (usually the user’s keyboard) and converts it into a string.
Here’s a basic example:
1 2 |
user_input = input("Enter a number: ") print("You entered:", user_input) |
Enter a number: 5 You entered: 5
However, the entered value is still a string and needs to be converted into an integer or floating-point number for mathematical operations.
Step 2: Converting Strings to Numbers
To convert the user input from a string to an integer or a floating-point number, we can use the int() and float() functions, respectively. These functions take a string as an argument and return the corresponding numeric value.
An example is shown below:
1 2 3 |
user_input = input("Enter a number: ") user_number = int(user_input) print("You entered:", user_number) |
Enter a number: 5 You entered: 5
Now that we know how to accept user input and convert it to a numeric value, it is time to receive two numbers, one after the other.
Step 3: Input Two Numbers
In this step, we will prompt the user to input two numbers, then convert those values to integers or floating-point numbers.
Here’s the complete code:
1 2 3 4 5 |
number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) print("First Number:", number1) print("Second Number:", number2) |
Enter the first number: 5 Enter the second number: 8 First Number: 5 Second Number: 8
For floating-point numbers, simply replace int() with float():
1 2 3 4 5 |
number1 = float(input("Enter the first number: ")) number2 = float(input("Enter the second number: ")) print("First Number:", number1) print("Second Number:", number2) |
Enter the first number: 5.5 Enter the second number: 8.5 First Number: 5.5 Second Number: 8.5
Conclusion
In this tutorial, we have learned how to input two numbers in Python using the input() function, converting the entered strings to integers or floating-point numbers, and working with the numeric values. With this fundamental knowledge, you can now proceed to develop more complex and interactive Python applications.