The input()
function in Python is used to take user input from the keyboard during program execution. It always returns a string, so type conversion may be needed.
πΉ Basic Syntax
user_input = input("Enter something: ")
print("You entered:", user_input)
π Example Output
Enter something: Hello, Python!
You entered: Hello, Python!
πΉ Taking Integer Input
Since input()
always returns a string, we convert it to an integer using int()
.
age = int(input("Enter your age: "))
print("Your age is:", age)
π Example Output
Enter your age: 25
Your age is: 25
πΉ If a user enters non-numeric data, int(input())
will raise a ValueError.
πΉ Taking Multiple Inputs
Method 1: Using split()
We can take multiple inputs in a single line by using .split()
.
x, y = input("Enter two numbers: ").split()
print("First Number:", x)
print("Second Number:", y)
πΉ By default, split()
separates values by spaces.
π Example Output
Enter two numbers: 10 20
First Number: 10
Second Number: 20
π Converting to Integers
a, b = map(int, input("Enter two numbers: ").split())
print("Sum:", a + b)
Enter two numbers: 5 15
Sum: 20
πΉ map(int, input().split())
converts each value to an integer.
πΉ Taking List Input
numbers = list(map(int, input("Enter space-separated numbers: ").split()))
print("List:", numbers)
Enter space-separated numbers: 2 4 6 8 10
List: [2, 4, 6, 8, 10]
πΉ Reading a Single Character
Python does not have a direct method to read a single character, but we can use slicing:
char = input("Enter a character: ")[0]
print("You entered:", char)
Enter a character: P
You entered: P
πΉ Handling Errors in Input
If a user enters an invalid input, the program might crash. We handle errors using try-except
:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a number.")
Enter a number: abc
Invalid input! Please enter a number.
πΉ Taking Input Without a Prompt
If we donβt pass a string to input()
, it still waits for input:
name = input()
print("Hello,", name)
πΉ Summary
Use Case | Example |
---|---|
Read input | input("Enter name: ") |
Convert to int | int(input("Enter age: ")) |
Multiple inputs | x, y = input().split() |
Convert multiple inputs | map(int, input().split()) |
Read list input | list(map(int, input().split())) |
Read single char | input()[0] |
Handle errors | try-except ValueError |
Would you like a real-world example, like taking user credentials securely? π
Leave a Reply