Input and Output

Daniel Sarney
Python For Beginners

So far, you've learned how to store data in variables and display simple messages. But real programs need to interact with users—they need to ask questions, receive answers, and display information in a clear, professional way. In this lesson, you'll learn how to make your Python programs interactive by getting input from users and formatting your output beautifully.

Being able to create interactive programs is what transforms simple scripts into useful applications. Whether you're building a calculator, a quiz game, or a data entry system, understanding input and output is essential. By the end of this lesson, you'll be able to create programs that feel professional and user-friendly.

What You'll Learn

  • How to get input from users using the input() function
  • Understanding different types of input and how to convert them
  • Creating formatted output with f-strings
  • Using string formatting methods for professional output
  • Building interactive programs that respond to user input
  • Best practices for user-friendly input and output

Getting User Input

Python's input() function allows you to get text from the user. When your program reaches an input() statement, it pauses and waits for the user to type something and press Enter. The text the user types is returned as a string.

Here's a simple example:

# Getting input from the user
name = input("What's your name? ")
print("Hello, " + name + "! Welcome to Python programming.")

When you run this program, it will display "What's your name? " and wait for you to type your name. After you press Enter, it will greet you with your name.

The text inside the parentheses of input() is called a prompt—it tells the user what information you're asking for. Always make your prompts clear and helpful:

# Good prompts are clear and specific
age = input("How old are you? ")
favorite_color = input("What's your favorite color? ")
city = input("Which city do you live in? ")

print(f"You are {age} years old, love {favorite_color}, and live in {city}.")

Notice that input() always returns a string, even if the user types a number. This is important to remember when you need to do calculations!

Converting Input to Different Types

Since input() always returns a string, you'll often need to convert the input to the correct data type. This is especially important for numbers. Here's how to handle different types of input:

# Converting string input to integer
age_string = input("How old are you? ")
age = int(age_string)  # Convert to integer
years_until_100 = 100 - age
print(f"You'll be 100 in {years_until_100} years!")

# Converting string input to float
price_string = input("Enter the price: £")
price = float(price_string)  # Convert to float
tax = price * 0.20  # Calculate 20% tax
total = price + tax
print(f"Price: £{price}, Tax: £{tax}, Total: £{total}")

You can also convert the input directly in one line, which is more concise:

# Converting input directly
age = int(input("How old are you? "))
height = float(input("What's your height in meters? "))
is_student = input("Are you a student? (yes/no): ").lower() == "yes"

print(f"Age: {age}, Height: {height}m, Student: {is_student}")

Formatted Strings (f-strings)

F-strings (formatted string literals) are Python's modern and preferred way to format strings. They make it easy to insert variables and expressions into strings. F-strings start with f or F before the opening quote, and you use curly braces {} to insert values.

Here's a basic example:

# Using f-strings for formatted output
name = "Daniel"
age = 30
city = "London"

# Simple f-string
message = f"My name is {name}, I'm {age} years old, and I live in {city}."
print(message)

# F-strings can include expressions
price = 19.99
quantity = 3
total = f"Total cost: £{price * quantity}"
print(total)

F-strings are incredibly powerful because you can include any Python expression inside the curly braces. This makes your code more readable and easier to write:

# F-strings with expressions
first_name = "Daniel"
last_name = "Sarney"
full_name = f"{first_name} {last_name}"
name_length = f"Your name has {len(full_name)} characters"
print(full_name)
print(name_length)

# Mathematical expressions in f-strings
a = 10
b = 5
result = f"{a} + {b} = {a + b}"
print(result)  # Output: 10 + 5 = 15

Advanced String Formatting

F-strings support formatting options that let you control how values are displayed. This is especially useful for numbers, dates, and aligning text. Here are some common formatting techniques:

# Formatting numbers with f-strings
price = 19.987654
quantity = 3

# Format to 2 decimal places
formatted_price = f"Price: £{price:.2f}"
print(formatted_price)  # Output: Price: £19.99

# Format as percentage
discount = 0.15
print(f"Discount: {discount:.1%}")  # Output: Discount: 15.0%

# Format large numbers with commas
population = 8000000000
print(f"World population: {population:,}")  # Output: World population: 8,000,000,000

# Align text
name = "Daniel"
print(f"Name: {name:>10}")  # Right align in 10 characters
print(f"Name: {name:<10}")  # Left align in 10 characters
print(f"Name: {name:^10}")  # Center align in 10 characters

Building Interactive Programs

Now let's combine everything we've learned to create a practical, interactive program. This example demonstrates how input, output, and formatting work together:

# Interactive program: Personal Information Form
print("=== Personal Information Form ===")
print()

# Get user information
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
age = int(input("Enter your age: "))
email = input("Enter your email address: ")
salary = float(input("Enter your annual salary: £"))

# Calculate monthly salary
monthly_salary = salary / 12

# Display formatted information
print()
print("=" * 40)
print("YOUR INFORMATION")
print("=" * 40)
print(f"Full Name: {first_name} {last_name}")
print(f"Age: {age} years old")
print(f"Email: {email}")
print(f"Annual Salary: £{salary:,.2f}")
print(f"Monthly Salary: £{monthly_salary:,.2f}")
print("=" * 40)

This program demonstrates several important concepts: getting multiple inputs, converting types, performing calculations, and creating professional-looking output with formatting.

Error Handling for Input

When converting user input, you might encounter errors if the user enters invalid data. For example, if you try to convert "hello" to an integer, Python will raise an error. While we'll cover error handling in detail later, here's a simple way to handle this:

# Simple input validation
while True:
    try:
        age = int(input("Enter your age: "))
        break  # Exit the loop if conversion succeeds
    except ValueError:
        print("Please enter a valid number!")

print(f"You entered: {age}")

This code keeps asking for input until the user enters a valid number. We'll learn more about error handling in a later lesson.

Try It Yourself

Practice creating interactive programs with these exercises:

  1. Simple Calculator: Create a program that asks for two numbers and displays their sum, difference, product, and quotient with nicely formatted output.

  2. Personal Greeting: Write a program that asks for the user's name, age, and favorite hobby, then creates a personalized greeting using f-strings.

  3. Temperature Converter: Create a program that asks for a temperature in Fahrenheit, converts it to Celsius, and displays both temperatures with proper formatting (2 decimal places).

  4. Receipt Generator: Build a program that asks for an item name, price, and quantity, then displays a formatted receipt showing the item details, subtotal, tax (8%), and total cost.

These exercises will help you become comfortable with creating interactive programs that feel professional and user-friendly.

Summary

In this lesson, you've learned how to make your Python programs interactive. You now understand how to get input from users using the input() function, convert that input to the appropriate data types, and create beautifully formatted output using f-strings. You've also seen how to use formatting options to control how numbers and text are displayed.

The ability to create interactive programs is a crucial skill that transforms your code from simple scripts into useful applications. Remember that input() always returns a string, so you'll need to convert it when working with numbers. F-strings are your best friend for creating readable, professional output.

As you continue learning Python, you'll find that most programs you create will involve some form of input and output. The skills you've learned here will be used in almost every program you write.

What's Next?

In the next lesson, we'll explore conditional statements—the if, elif, and else keywords that allow your programs to make decisions. You'll learn how to create programs that behave differently based on conditions, such as checking if a user is old enough, determining if a number is positive or negative, or choosing different actions based on user input. This will make your programs much more intelligent and useful.

Video Tutorial Coming Soon

The video tutorial for this lesson will be available soon. Check back later!

Continue Learning

18 lessons
Python Intermediate

Start your learning journey with Python Intermediate. This course includes comprehensive lessons covering everything you need to know.