📌 Introduction
User input is one of the most essential parts of any interactive Python application. Whether you’re building a simple calculator, a game, or a form, capturing input from users enables dynamic and flexible programs.
🎯 Objective
This guide will teach you how to capture and handle user input in Python using the built-in input() function. You’ll also learn how to convert string inputs into other data types like integers or floats.
💻 Example Code
# Program to get user's name and age and display a greeting message
# Asking for user input
name = input(“Enter your name: “)
age = input(“Enter your age: “)
# Convert age from string to integer
try:
age = int(age)
print(f”Hello, {name}! You are {age} years old.”)
except ValueError:
print(“Please enter a valid number for age.”)
🔍 Program Explanation
- input(): This function pauses the program and waits for the user to enter text.
- try/except block: We use this to handle cases where the age is not a valid number.
- f-string: This is used to format the output message in a clean and readable way.
▶️ How to Run This Program
- Open your text editor (e.g., VS Code, Notepad++, etc.).
- Paste the code into a new file and save it as user_input.py.
- Open a terminal or command prompt.
- Navigate to the folder where you saved the file.
- Type python user_input.py and hit Enter.
You’ll be prompted to enter your name and age. The program will greet you accordingly!