Introduction π
Input functions allow your Python program to interact with users. Using input(), you can collect information like names, numbers, or choices and use them inside your program.
Note
1. The input() Function β Basics π§©
The input function displays a message (optional) and waits for the user to type something.
basic_input.py
name = input("Enter your name: ")
print("Hello,", name)π When you run this program, Python pauses until you enter text and pressEnter.
2. Input Is Always a String β οΈ
Even if the user enters 25, Python treats it as `"25"`. You must convert it for numerical use.
string_input.py
age = input("Enter your age: ")
print(age, type(age)) # Output: '25' <class 'str'>3. Converting Input Types (Type Casting) π
Use int() or float() to convert input values.
Integer Conversion
int_input.py
age = int(input("Enter your age: "))
print(age, type(age))Floating-point Conversion
float_input.py
height = float(input("Enter your height: "))
print(height, type(height))Note
4. Taking Multiple Inputs π₯π₯
Method 1: Separate Inputs
multiple_inputs.py
name = input("Enter name: ")
age = int(input("Enter age: "))
print(name, age)Method 2: Single Line Input (Split)
Use split() when collecting multiple values at once.
split_input.py
a, b = input("Enter two numbers: ").split()
print(a, b)Converting split inputs to integers
split_ints.py
x, y = map(int, input("Enter two numbers: ").split())
print(x + y)5. Using input() in Expressions β
You can directly convert inside an expression.
expression_input.py
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
print("Sum:", num1 + num2)6. Customizing Prompts π¨
You can format input prompts for clarity.
custom_prompt.py
username = input("π€ Username: ")
password = input("π Password: ")
print("Login Successful!")7. Preventing Errors With Try/Except π‘οΈ
Use exception handling to avoid crashes when users enter invalid numbers.
safe_input.py
try:
marks = int(input("Enter marks: "))
print("Marks:", marks)
except ValueError:
print("Invalid input! Please enter a number.")8. Real-World Example π―
real_world.py
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you will be {age + 1} next year!")Conclusion π
You now understand how to collect and handle user input in Python. Want to learn about output formatting, operators, expressions, conditional statements, loops, or something else? Just ask! π