Python Review Exercises: 1
Anaconda Installation
Anaconda download link: https://www.anaconda.com/download/success?reg=skipped
2 / 19
1. The print() Function
• Used to output text or data to the console.
• Can accept multiple arguments separated by commas.
print("Hello, World!")
print("The answer is", 42)
# Output: The answer is 42
3 / 19
1. Advanced print() Parameters
• sep: Defines the string inserted between values (default is a space).
• end: Defines the string appended after the last value (default is a newline).
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
4 / 19
2. The input() Function
• Pauses execution and waits for the user to type something.
• Optionally takes a prompt string to display to the user.
• Crucial: Always returns the data as a str (String).
name = input("Enter your name: ")
print("Welcome,", name)
5 / 19
2. Casting User Input
• Because input() returns a string, you must convert (cast) it to do math.
• Common casting functions: int(), float().
# Without casting, 5 + 5 becomes "55"
age_str = input("Enter your age: ")
age = int(age_str)
# Or, in one line:
price = float(input("Enter the price: "))
6 / 19
3. String Formatting (f-strings)
• f-strings (formatted string literals) are the modern, preferred way to format strings in
Python.
• Prefix the string with f and put variables inside curly braces {}.
name = "Alice"
score = 95
print(f"Player {name} achieved a score of {score}.")
# Output: Player Alice achieved a score of 95.
7 / 19
4. Variables and Assignment
• Variables are containers for storing data values.
• Python has no command for declaring a variable; it is created the moment you first
assign a value to it using =.
x = 5
y = "John"
x = "Sally"
# x is an integer
# y is a string
# x is now a string (dynamic typing)
8 / 19
4. Variable Naming Rules
• Must start with a letter or underscore (_).
• Cannot start with a number.
• Can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
• Python convention uses snake_case for variables.
# Good variable names
user_age = 25
is_logged_in = True
# Bad/Invalid variable names
2nd_player = "Bob" # Starts with a number
user-name = "Alice" # Hyphens are not allowed
9 / 19
5. Operator Precedence
• Determines the order in which operations are evaluated.
• Python follows PEMDAS/BEDMAS rules:
1. Parentheses ()
2. Exponents **
3. Multiplication/Division/Floor/Modulo *, /, //, %
4. Addition/Subtraction +, result = 10 + 5 * 2
# result is 20, not 30 (Multiplication happens first)
10 / 19
6. Expressions
• An expression is any combination of values, variables, and operators that evaluates to a
single value.
• If you can print it or assign it to a variable, it’s an expression.
# These are all expressions:
42
x + 5
len("Hello") * 2
x > 10
# Assigning an expression to a variable
total_cost = (price * quantity) + tax
11 / 19
7. Boolean Data Type
• Represents one of two values: True or False.
• Used heavily in conditional statements (if / while).
• Must be capitalized in Python.
is_active = True
game_over = False
# Evaluating expressions to booleans
print(10 > 9) # True
12 / 19
7. Logical Operators
13 / 19
• Used to combine multiple boolean expressions:
‣ and: Returns True if BOTH statements are true.
‣ or: Returns True if AT LEAST ONE statement is true.
‣ not: Reverses the result (True becomes False).
x = 5
print(x > 3 and x < 10)
print(x > 10 or x < 6)
print(not(x == 5))
# True
# True
# False
8. Comparison Operators
• Used to compare two values. They always return a Boolean.
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
a = 10
b = 20
print(a == b)
print(a != b)
# False
# True
14 / 19
8. Chaining Comparisons
15 / 19
• Python allows you to elegantly chain comparison operators together, mimicking standard
mathematical notation.
x = 15
# The traditional way (using 'and')
print(10 < x and x < 20) # True
# The Pythonic chained way
print(10 < x < 20)
# True
Tasks
1. Using Print & String Format
17 / 19
1. Dynamic Receipt: Given the variables item_name = "Wireless Mouse", quantity =
3, and unit_price = 24.99, write a single print() statement using an f-string that
calculates the total inline and outputs exactly: Purchased 3x Wireless Mouse at
$24.99 each. Total: $74.97.
2. Log Formatting: Given error_code = 404 and file_path = "/images/logo.png", use
the .format() method to print the following log message, ensuring the error code is
padded with zeros to be exactly 4 digits long: [ERROR 0404]: The requested resource
at '/images/logo.png' was not found.
2. Using Input
1. Temperature Converter Script: Write a short script that uses input() to ask the user,
“Enter temperature in Celsius: “. Convert their input to a floating-point number,
mathematically convert it to Fahrenheit (𝐹 = 𝐶 × 95 + 32), and print the result.
2. Initials Extractor: Write a script that prompts the user to input their full name (e.g.,
“john robert doe”). Process the input string to extract the first letter of each word,
capitalize them, and print the initials (e.g., “JRD”).
18 / 19
3. Using Variables & Expressions
19 / 19
1. Time Breakdown: You have a variable total_days = 134. Write a few lines of code
using variables and the modulo (%) and floor division (//) operators to convert this into
weeks and remaining days. Print the output as "X weeks and Y days".
2. In-Place Swap: Given two variables a = 15 and b = 42, write the most Pythonic way
to swap their values in a single line of code without declaring a third temporary
variable.
3. Compound Adjustments: A player’s score starts at score = 100. Using only
compound assignment operators (+=, *=, etc.), write three consecutive lines of code to:
add 50 points, multiply the total by 2, and then subtract 15 points.
4. Boolean Logic Expression: Given age = 25 and has_license = True, write a single
boolean expression assigned to a new variable can_rent_car that evaluates to True only
if the age is 21 or older and the person has a license.