Input/Output & Comments
Overview
Learn how to ask users for information, display output messages, and document your code using comments.
Learning Objectives
- Write clear comments to explain how your code works.
- Ask users for input values and print outputs.
- Format output messages using f-strings.
Concept Explanation
Comments start with # and are notes for humans; Python completely ignores them. The input() function prompts the user for text. The print() function displays messages to the screen. You can inject variables directly into printed text using format strings (f-strings).
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
# This is a comment. Python skips this.
print('This prints to the screen.')
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Capture user name and age
user_name = input('Enter name: ')
print(f'Hello, {user_name}! Nice to meet you.')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Calculate age next year from user string input
age_str = input('Enter age: ')
age_next_year = int(age_str) + 1 # Convert string to integer first
print(f'Next year you will be {age_next_year} years old.')
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Show prompt text → Wait for User input → Capture input as String → Print styled f-string output
Common Mistakes
Review these common pitfalls when working with this topic:
- Forgetting that input() always returns text (a string), even if the user enters a number.
- Forgetting to put the letter 'f' before the quotes in f-strings.
- Using comments to explain obvious code instead of explaining complex logic.
- Leaving debugging print statements in production code files.
Best Practices
Enforce these Pythonic best practices in your codebase:
print('Name: ' + name + ', Age: ' + str(age)) # Messy concatenation
print(f'Name: {name}, Age: {age}') # Clean f-strings formatting
Quick Revision
Use these key summaries for last-minute revision:
- Use # to write single-line comments.
- input() gathers user inputs as strings.
- print() writes text messages to standard output.
- f-strings use curly braces to print variable values.
- Convert input strings to numbers before doing math.