Python User Input

In Python, user input can be gathered using the input() function. This function allows the program to pause and wait for the user to enter data. The input is read as a string by default and can be converted into other data types if necessary.

Below are several examples demonstrating how to gather and handle user input in Python.

Example 1: Basic User Input

This basic example demonstrates how to gather a user's name using input() and display a greeting.

# Basic User Input Example
name = input("Enter your name: ")
print("Hello, " + name + "!")

Output

Enter your name: Karthick AG

Hello, Karthick AG!

Example 2: Inputting Numbers

When using the input() function, the input is always received as a string. To work with numbers, you must convert the input to the appropriate type (e.g., int or float).

# Inputting numbers example
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 + num2
print("The sum is:", result)

Output

Enter the first number: 10

Enter the second number: 20

The sum is: 30

Example 3: Inputting Floats

Similar to integers, if you're expecting a floating-point number, you need to convert the input using float(). This example demonstrates how to input two floating-point numbers and display their sum.

# Inputting floating-point numbers example
num1 = float(input("Enter the first floating-point number: "))
num2 = float(input("Enter the second floating-point number: "))
result = num1 + num2
print("The sum is:", result)

Output

Enter the first floating-point number: 5.5

Enter the second floating-point number: 4.5

The sum is: 10.0

Example 4: Inputting Multiple Values

In this example, we gather multiple values in one line using the split() method, and convert the values to the correct types for further processing.

# Inputting multiple values example
num1, num2 = input("Enter two numbers separated by a space: ").split()
num1 = int(num1)
num2 = int(num2)
result = num1 * num2
print("The product is:", result)

Output

Enter two numbers separated by a space: 3 4

The product is: 12

Example 5: Handling Input Errors

It’s important to handle errors when receiving user input, such as ensuring the input is a number when required. This example demonstrates how to use a try-except block to handle input errors.

# Handling input errors example
try:
    num = int(input("Enter an integer: "))
    print("You entered:", num)
except ValueError:
    print("Error: Invalid input, please enter an integer!")

Output

Enter an integer: abc

Error: Invalid input, please enter an integer!