Input/Output #
Communication with the user and the environment.
String Interpolation #
String interpolation is inserting variables or expressions into strings. Python offers several ways to achieve this:
- f-strings (from Python 3.6): f"Hello, {name}".
- str.format(): “Hello, {}".format(name).
- % strings: “Hello, %s” % name
We focus here only on the first method. Examples:
name = "Alice"
age = 25
# Using f-strings
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)
# Evaluating expressions in f-strings
calculation = f"2 + 2 = {2 + 2}"
print(calculation)
String Formatting #
Formatting strings allows control over how data appears. Use placeholders for alignment, padding, or precision:
{}
: Default placeholder.{:.2f}
: Floating-point with 2 decimal places.{:<10}
: Left-align in 10-character width.
Example:
# Numeric formatting
price = 19.99
formatted_price = f"Price: ${price:.2f}" # Two decimal places
print(formatted_price)
# Alignment
data = "Python"
print(f"'{data:<10}'") # Left-align
print(f"'{data:>10}'") # Right-align
print(f"'{data:^10}'") # Center-align
Fore more information check out the tutorial or visit pyformat.info for more in-depth description.
Console #
You can interact with the user via the console (in text based UIs):
# Printing output
print("Welcome to the console class!")
# Getting user input
name = input("Enter your name: ")
print(f"Hello, {name}!")
Advanced stuff:
# Print without a newline
print("Loading", end="")
for _ in range(3):
print(".", end="")
print(" Done!")
# Formatting console output
value = 42
print(f"The answer is: {value:010}") # Padded with zeroes
Files #
Files allow reading and writing persistent data (on storage). Python uses the open() function with modes:
'r'
: Read.'w'
: Write (overwrites existing content).'a'
: Append.
Boy scout rule - always leave the place in the same or better state as you encountered it. Thus always close the files after you finished working with them. If you use the with
keyword to work with them, Python will do that for you automatically, even if an exception occurs while working with it.
Examples:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, file!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print("File content:", content)
# Appending to a file
with open("example.txt", "a") as filehttps://docs.python.org/3/tutorial/inputoutput.html:
file.write("\nThis is appended text.")
# Reading line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Command Line Arguments (sys.argv
)
#
The sys.argv
list allows you to access command-line arguments passed to a Python script.
sys.argv[0]
is the name of the script, and subsequent elements are the arguments.
Example:
import sys
# Example: Accessing command-line arguments
if len(sys.argv) > 1:
print("Arguments passed:", sys.argv[1:])
else:
print("No arguments passed.")
# Example: Simple command-line calculator
if len(sys.argv) == 4:
num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])
if operator == '+':
print(f"Result: {num1 + num2}")
elif operator == '-':
print(f"Result: {num1 - num2}")
elif operator == '*':
print(f"Result: {num1 * num2}")
elif operator == '/':
print(f"Result: {num1 / num2}")
else:
print("Unsupported operator!")
else:
print("Usage: python script.py <num1> <operator> <num2>")
Homework (graded) #
Formatting #
Create a formatted report with the names and scores of students using string formatting. The numbers following the names should be aligned. Sort it by grade, best being on top. Here is the input data:
results = {
'Joe': 75,
'Freddy': 81,
'Peter': 55,
'DeAnna': 75,
}
FileIO #
Write a script to:
- Ask the user for their name and age.
- Save this data to a file.
Make sure you create a script, don’t do this using the interactive interpreter mode (REPL). Then write another script that will:
- Read and display the content of the file.