October 15, 2024

How to Take Input in Python

In Python, you can take input from the user using the built-in input() function. This function reads a line from the input, typically from the user, and returns it as a string. Below are various examples of how to take input in Python.

1. Basic Input

The simplest way to take input from the user is by using the input() function. The input is always returned as a string, regardless of what the user types.

Example:

# Taking basic input from the user
name = input("Enter your name: ")
print(f"Hello, {name}!")

Output:

Enter your name: John
Hello, John!

2. Taking Integer Input

If you need to take an integer input, you can convert the string returned by input() to an integer using the int() function.

Example:

# Taking integer input from the user
age = int(input("Enter your age: "))
print(f"You are {age} years old.")

Output:

Enter your age: 25
You are 25 years old.

3. Taking Float Input

Similarly, to take a float input, you can convert the string to a float using the float() function.

Example:

# Taking float input from the user
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters.")

Output:

Enter your height in meters: 1.75
Your height is 1.75 meters.

4. Taking Multiple Inputs

You can take multiple inputs at once by using the split() method, which splits the input string into a list of values. You can then convert each value as needed.

Example:

# Taking multiple inputs from the user
x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print(f"The sum of {x} and {y} is {x + y}.")

Output:

Enter two numbers separated by space: 10 20
The sum of 10 and 20 is 30.

5. Taking Input with a Default Value

You can provide a default value if the user presses Enter without typing anything by checking if the input is an empty string.

Example:

# Taking input with a default value
name = input("Enter your name (default is 'Guest'): ") or "Guest"
print(f"Hello, {name}!")

Output:

Enter your name (default is 'Guest'): 
Hello, Guest!

6. Handling Invalid Input

You can handle invalid input by using a try-except block, which will allow you to catch and manage exceptions, such as when the user enters a non-integer value when an integer is expected.

Example:

# Handling invalid input
try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("Invalid input. Please enter a number.")

Output:

Enter your age: abc
Invalid input. Please enter a number.