⌨️ Python Input Functions β€” Getting Data From the User

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

πŸ’‘ The input() function ALWAYS returns data as a string β€” even if you type a number.

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

⚠️ If the user enters something invalid (like letters), type conversion will cause an error.

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 πŸŽ‰

>>β€œPrograms become interactive when they listen β€” input() gives your code a voice.” πŸ”₯

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! 😊