Loops, Dictionaries and Lists
Tip
Learning smaller parts of code will help you to implement specific types of functionalities in larger projects!
Let’s Return to Literals (e.g., numbers, strings, booleans, etc.) and work with them in interesting ways using print().
Note
In Python, print statements with an f prefix before the opening quotation mark denote f-strings, also known as formatted string literals. F-strings provide a concise and readable way to embed expressions inside string literals for formatting output.
Note
Curiously, both of the below print statements print out the same results, but the code is not the same …
Output:
His name is: Robert Paulson!
His name is: Robert Paulson ! # A space appears?!
Operators let you do math, compare values, and more!
Important
Examples:
Arithmetic: +, -, *, /, ** (power)
Comparison: ==, !=, <, >
Assignment: =, +=, -=
Note
Variables and operators are the backbone of calculators, games, and simulations!
Loops repeat actions. Use for and while loops.
Every now and then, your code will need to make decisions. Use if, elif, and else statements. Here is an example.
print("Welcome to the Secret Door Game!")
print("There are three doors: Red, Blue, and Green.")
# input() does not work with Quarto slides or Jupyter.
# Saved for later
# door = input("Which door do you choose? ").lower()
door = "red" ## Change this line to see what happens next!
if door == "red":
print("🔥 You found a treasure chest!")
elif door == "blue":
print("🌊 You discovered a hidden underwater tunnel!")
elif door == "green":
print("🌲 You entered a magical forest!")
else:
print("❌ That door doesn't exist!")Try out this code! Now, make a change and see what happens!
Loops and conditionals can be used to determine positive, negative numbers, or zeros. Neat-O!
Examples:
Output: Positive
Try out this code! Now, make a change and see what happens!
We find out if a number is positive, negative, or zero.
Examples:
Try out this code! Now, make a change and see what happens!
Here we use conditionals to decide whether a number is prime or not
# input() does not work with Quarto slides or Jupyter.
# Saved for later
# number = int(input("Enter a number: ")) #Get user input.
number = 11
if number < 2:
print("❌ This is not a prime number.")
elif number == 2:
print("⭐ 2 is a prime number!")
elif number % 2 == 0:
print("❌ This is not a prime number because it is divisible by 2.")
else:
print(f"Testing {number} for primality ... ")
# Check if the number has any divisor
for i in range(3, number, 2):
if number % i == 0:
print(f"❌ {number} is not a prime number.")
break
else:
print(f"GOOD NEWS! {number} is a prime number!")Try out this code! Now, make a change and see what happens!
You can nest loops, one inside the other.
Examples:
Output: Positive
Try out this code! Now, make a change and see what happens!
Logical operators use True and False to determine outcomes.
Examples:
Output:
Try out this code! Now, make a change and see what happens!
We now look at how we can manipulate strings
Important
A list is a fundamental data structure in Python used to store an ordered collection of items.
Lists maintain the order of elements, with each item accessible by its index (starting from 0).
Lists are mutable, so their contents can be changed after creation (items can be added, removed, or modified).
Lists can hold items of different data types, including other lists.
Lists are created using square brackets, with elements separated by commas.
Examples:
Output:
1
[1, 2, 3, 4, 5, 6]
[1, 2, 4, 5, 6]
5
Important
A dictionary is a built-in data structure in Python used to store key-value pairs.
Dictionaries are unordered collections (as of Python 3.6+, they maintain insertion order), where each value is accessed using its unique key.
Dictionaries are mutable, so their contents can be changed after creation (items can be added, removed, or modified).
Keys in a dictionary must be unique and immutable (such as strings, numbers, or tuples), while values can be of any data type.
Dictionaries are created using curly braces {}, with key-value pairs separated by commas and a colon between each key and value.
Examples:
my_dict = {"name": "Alice", "age": 25, "is_student": True} # definition
print(my_dict["name"]) # Access value by key
my_dict["age"] = 26 # Modify value
my_dict["city"] = "New York" # Add new key-value pair
print(my_dict) # {'name': 'Alice', 'age': 26, 'is_student': True, 'city': 'New York'}
del my_dict["is_student"] # Remove a key-value pair
print(my_dict) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
print(len(my_dict)) # Number of key-value pairsOutput:
Alice
{‘name’: ‘Alice’, ‘age’: 26, ‘is_student’: True, ‘city’: ‘New York’}
{‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’}
3
Test your understanding before checking the solutions! Click an answer to see if you’re right.
print("His name is:", firstName, lastName, "!") print an extra space before the exclamation mark, unlike the f-string version?score = 10. After running score += 5, what is the value of score?count = 3
while count > 0:
print(count)
count -= 1title = "star wars: a new hope", which method call converts it to "STAR WARS: A NEW HOPE"?inventory = {"gold": 50, "gems": 3}. After inventory["gold"] += 20, what is inventory["gold"]?Challenge:
Create two variables, a and b, assign them integer values, and print their sum, difference, product, and quotient.
Tip
Method Suggestions:
+, -, *, /print() function with labels for clarity/ gives a float resultChallenge:
Create a list of five numbers. Print the largest number in the list.
Tip
Method Suggestions:
[]max() functionprint() with a descriptive messageChallenge:
Create a dictionary with three key-value pairs representing a person’s name, age, and city. Print each key and its value.
Tip
Method Suggestions:
{} to create a dictionary.items() method to access key-value pairsfor key, value in dict.items().keys() and values with .values()Challenge:
Use a for loop to print all even numbers from 1 to 10.
Tip
Method Suggestions:
range(1, 11) to iterate from 1 to 10%range() with a step parameteri % 2 == 0 tests for even numbersChallenge:
Use a while loop to keep asking the user to enter a number until they enter a negative number.
Tip
Method Suggestions:
while True: for a continuous loopinput() functionint()break statement to exit the loop< 0 comparisonChallenge: Create two variables, assign them integer values, and print their sum, difference, product, and quotient.
Challenge: Create two variables, assign them integer values, and print their sum, difference, product, and quotient.
Challenge: Create a list of five numbers and print the largest number.
Challenge: Create a list of five numbers and print the largest number.
Challenge: Create a dictionary with three key-value pairs and print each key and value.
Challenge: Create a dictionary with three key-value pairs and print each key and value.
Challenge: Use a for loop to print all even numbers from 1 to 10.
Challenge: Use a for loop to print all even numbers from 1 to 10.
Challenge: Use a while loop to keep asking for input until a negative number is entered.
Challenge: Use a while loop to keep asking for input until a negative number is entered.
Tip
You are now able to use …
for and whileCool, Right?!