Python User Input Tutorial

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

User input is a fundamental aspect of interactive programs, allowing users to provide data to the program at runtime. Python provides simple ways to handle user input using the input() function. This tutorial covers the basics of obtaining and processing user input in Python.

Table of Contents

  1. Getting User Input
  2. Converting Input Types
  3. Handling Errors
  4. Multi-line Input
  5. Practical Examples
  6. Conclusion

1. Getting User Input

The input() function is used to get input from the user. It reads a line from the input (usually from the user), converts it to a string, and returns it.

Example

# Getting user input name = input("Enter your name: ") print("Hello, " + name + "!") 

Output

Enter your name: Alice Hello, Alice! 

2. Converting Input Types

The input() function always returns the input as a string. To work with other data types, you need to convert the input.

Example

# Getting integer input age = input("Enter your age: ") age = int(age) print("You are " + str(age) + " years old.") # Getting float input height = input("Enter your height in meters: ") height = float(height) print("Your height is " + str(height) + " meters.") 

Output

Enter your age: 25 You are 25 years old. Enter your height in meters: 1.75 Your height is 1.75 meters. 

3. Handling Errors

When converting user input, errors can occur if the input is not in the expected format. You can handle these errors using try-except blocks.

Example

# Handling errors try: age = int(input("Enter your age: ")) print("You are " + str(age) + " years old.") except ValueError: print("Invalid input. Please enter a valid number.") 

Output

Enter your age: twenty Invalid input. Please enter a valid number. 

4. Multi-line Input

To get multi-line input from the user, you can use a loop or the input() function repeatedly.

Example using a Loop

# Multi-line input using a loop print("Enter your favorite fruits (type 'done' to finish):") fruits = [] while True: fruit = input() if fruit.lower() == 'done': break fruits.append(fruit) print("Your favorite fruits are:", fruits) 

Output

Enter your favorite fruits (type 'done' to finish): Apple Banana Cherry done Your favorite fruits are: ['Apple', 'Banana', 'Cherry'] 

Example using sys.stdin.read()

Another method for multi-line input is using sys.stdin.read(), which reads input until EOF.

import sys # Multi-line input using sys.stdin.read() print("Enter your address (press Ctrl+D to finish):") address = sys.stdin.read() print("Your address is:") print(address) 

5. Practical Examples

Example 1: Simple Calculator

# Simple calculator try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == '+': result = num1 + num2 elif operation == '-': result = num1 - num2 elif operation == '*': result = num1 * num2 elif operation == '/': result = num1 / num2 else: print("Invalid operation") result = None if result is not None: print("Result:", result) except ValueError: print("Invalid input. Please enter valid numbers.") 

Example 2: Greeting Program

# Greeting program name = input("Enter your name: ") age = input("Enter your age: ") try: age = int(age) print(f"Hello, {name}! You are {age} years old.") except ValueError: print("Invalid age. Please enter a valid number.") 

Example 3: Collecting User Preferences

# Collecting user preferences print("Please enter your top 3 favorite movies:") movies = [] for i in range(3): movie = input(f"Movie {i + 1}: ") movies.append(movie) print("Your favorite movies are:", movies) 

6. Conclusion

Handling user input is a crucial aspect of making interactive programs. Python's input() function makes it easy to get user input, and by converting input types and handling errors, you can create robust programs that can interact with users effectively. This tutorial covered the basics of getting user input, converting input types, handling errors, working with multi-line input, and provided practical examples to illustrate these concepts.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare