How to Handle User Input in Python Programs

 

 

πŸ“Œ 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

  1. Open your text editor (e.g., VS Code, Notepad++, etc.).
  2. Paste the code into a new file and save it as user_input.py.
  3. Open a terminal or command prompt.
  4. Navigate to the folder where you saved the file.
  5. Type python user_input.py and hit Enter.

You’ll be prompted to enter your name and age. The program will greet you accordingly!

Β© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

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