The input()
function in Python is used to take input from the user. This function reads a line from the input (usually from the keyboard) and returns it as a string. It is particularly useful for interactive programs that require user input.
Table of Contents
- Introduction
input()
Function Syntax- Understanding
input()
- Examples
- Basic Usage
- Converting Input to Other Data Types
- Handling Invalid Input
- Real-World Use Case
- Conclusion
Introduction
The input()
function allows you to prompt the user for input and capture their response as a string. This is useful for creating interactive programs that can respond to user inputs.
input()
Function Syntax
The syntax for the input()
function is as follows:
input([prompt])
Parameters:
- prompt (optional): A string that is displayed to the user as a prompt before reading the input.
Returns:
- A string representing the user's input.
Understanding input()
The input()
function reads a line of text input from the user, converts it to a string (if it isn't already), and returns that string. If a prompt string is provided, it is displayed to the user before reading the input.
Examples
Basic Usage
To demonstrate the basic usage of input()
, we will prompt the user to enter their name and age.
Example
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Name:", name)
print("Age:", age)
Output:
Enter your name: Ravi
Enter your age: 28
Name: Ravi
Age: 28
Converting Input to Other Data Types
This example shows how to convert the user's input to other data types, such as integers or floats.
Example
age = input("Enter your age: ")
# Convert the input to an integer
try:
age = int(age)
print("Age in 5 years:", age + 5)
except ValueError:
print("Invalid input. Please enter a valid number.")
Output:
Enter your age: 25
Age in 5 years: 30
Handling Invalid Input
This example demonstrates how to handle invalid input using a loop to prompt the user until valid input is provided.
Example
while True:
age = input("Enter your age: ")
try:
age = int(age)
print("Age in 5 years:", age + 5)
break
except ValueError:
print("Invalid input. Please enter a valid number.")
Output:
Enter your age: twenty
Invalid input. Please enter a valid number.
Enter your age: 30
Age in 5 years: 35
Real-World Use Case
Interactive Menu
In real-world applications, the input()
function can be used to create interactive menus that respond to user choices.
Example
def display_menu():
print("1. Add item")
print("2. Remove item")
print("3. View items")
print("4. Exit")
items = []
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
item = input("Enter item to add: ")
items.append(item)
print(f"'{item}' added to the list.")
elif choice == '2':
item = input("Enter item to remove: ")
if item in items:
items.remove(item)
print(f"'{item}' removed from the list.")
else:
print(f"'{item}' not found in the list.")
elif choice == '3':
print("Items in the list:", items)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
Output:
1. Add item
2. Remove item
3. View items
4. Exit
Enter your choice: 1
Enter item to add: Apple
'Apple' added to the list.
1. Add item
2. Remove item
3. View items
4. Exit
Enter your choice: 3
Items in the list: ['Apple']
Collecting User Data
Another real-world use case is collecting user data for processing or analysis.
Example
user_data = {}
user_data['name'] = input("Enter your name: ")
user_data['age'] = input("Enter your age: ")
user_data['email'] = input("Enter your email: ")
print("User Data:", user_data)
Output:
Enter your name: Sita
Enter your age: 27
Enter your email: sita@example.com
User Data: {'name': 'Sita', 'age': '27', 'email': 'sita@example.com'}
Conclusion
The input()
function in Python is used for creating interactive programs that can respond to user inputs. By using this function, you can prompt the user for input, capture their response, and process it accordingly. This function is particularly helpful in scenarios such as interactive menus, data collection, and creating user-friendly command-line applications.