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

Your email address will not be published. Required fields are marked *