Python Basics
Copy the code from the exercise below and play around with the different basic building blocks of Python.
Create new cells with # %%
as necessary.
Python Basics
Section titled “Python Basics”# %%# Types:# Boolean (bool), Integer (int), Range (range), Float (float),# Complex Number (complex), String (str), List (list), Tuple (tuple),# Dictionary (dict), Set (set), Absence of value (None)
# %%# Boolean (bool)
# %%# Integer (int)
# %%# Range (range)
# %%# Float (float)
# %%# Complex Number (complex)
# %%# String (str)
# %%# List (list)
# %%# Tuple (tuple)
# %%# Dictionary (dict)
# %%# Set (set)
# %%# Absence of value (None)
# %%# Variables and Assignment (=)
# %%# Mathematical Operations (+,-,*,**,/,//)
# %%# Comparisons (==,!=,<,<=,>,>=)
# %%# Boolean Operators (and/or/not)
# %%# String Expressions (+,*)
# %%# List Expressions (+,*)
# %%# Conditional Execution (if/elif/else)
# %%# For Loops (for)
# %%# While Loops (while)
# %%# List Comprehensions [...]
# %%# Dictionary Comprehensions {...}
# %%# Functions (def)
# %%# Anonymous Functions (lambda)
# %%# Import Packages (import)
# %%# List Indexing
# %%# Dictionary Indexing
# %%# Types:# Boolean (bool), Integer (int), Range (range), Float (float),# Complex Number (complex), String (str), List (list), Tuple (tuple),# Dictionary (dict), Set (set), Absence of value (None)
# %%# Boolean (bool)True, False
# %%# Integer (int)15
# %%# Range (range)range(1, 10, 2)
# %%# Float (float)2.66666
# %%# Complex Number (complex)1.5 + 3.2j
# %%# String (str)"Text", "Text"
# %%# List (list)[1, 2, 3]
# %%# Tuple (tuple)(1, 2, 3)
# %%# Dictionary (dict){"a": 1, "b": 2, "c": 3}
# %%# Set (set){"a", "b", "c"}
# %%# Absence of value (None)None
# %%# Variables and Assignment (=)a = 1b = 4
c, d = 13, 14
# %%# Mathematical Operations (+,-,*,**,/,//)1 + 1a - 2
b / cb // 3 # Floor division
c * dc**2 # Power
# %%# Comparisons (==,!=,<,<=,>,>=)a == 1 # Truea != 1 # False
a < 2 # Truea <= 2 # True
a > 2 # Falsea >= 2 # False
# %%# Boolean Operators (and/or/not)a == 1 and not (b < 3 or b > 3)
# %%# String Expressions (+,*)"My name is " + "Peter"
"A" * 5 # "AAAAA"
# %%# List Expressions (+,*)["one", "list"] + ["two", "lists"]
["A"] * 5
# %%# Conditional Execution (if/elif/else)if a == b: print("a = b")elif a > b: print("a > b")else: print("a < b")
# %%# For Loops (for)for i in range(10): print(i)
# %%# While Loops (while)j = 0while j < 10: print(j) j += 1 # j = j + 1
# %%# List Comprehensions [...]lc = [i for i in range(5)]
# Same asll = []for i in range(5): ll.append(i)
lc == ll
# %%# Dictionary Comprehensions {...}keys = ["A", "B", "C"]values = [1, 2, 3]
dc = {k: j for k, j in zip(keys, values)}
# Same as
dl = {}for k, j in zip(keys, values): dl[k] = j
dc == dl
# %%# Functions (def)def my_function(a, b=2): return a**b
my_function(2)my_function(2, 3)
# %%# Anonymous Functions (lambda)my_afunc = lambda x: x + 1
my_afunc(1)
# %%# Import Packages (import)import polars as pl
pl.DataFrame()
# %%# List Indexingmy_list = [1, 2, 3, 4, 5, 6, 7]
len(my_list)
my_list[0]my_list[3]
my_list[-1]my_list[-2]
my_list[1:3]my_list[1:6:2]
# %%# Dictionary Indexingmy_dict = {"A": 1, "B": 2, "C": 3}
len(my_dict)
my_dict["A"]my_dict["C"]
Printing Patterns
Section titled “Printing Patterns”# %%# Print various patterns using the print() function, for loops, and string manipulation.
# %%# Print the pattern:# *# **# ***# ****# *****
# %%# Print the pattern:# *# **# ***# ****# *****
# %%# Print the pattern:# *# ***# *****# *******# *********
# %%# Print the pattern:# *# ***# *****# *******# *********# ***********# *********# *******# *****# ***# *
# %%# Print various patterns using the print() function, for loops, and string manipulation.
# %%# Print the pattern:# *# **# ***# ****# *****for i in range(5): print("*" * (i + 1))
# %%# Print the pattern:# *# **# ***# ****# *****length = 5for i in range(length): string = "*" * (i + 1) rjust_string = string.rjust(length) print(rjust_string)
# %%# Print the pattern:# *# ***# *****# *******# *********length = 5width = length * 2 + 1for i in range(length): string = "*" * (2 * i + 1) rjust_string = string.center(width) print(rjust_string)
# %%# Print the pattern:# *# ***# *****# *******# *********# ***********# *********# *******# *****# ***# *length = 11width = length * 2 + 1for i in range(length): string = "*" * (2 * i + 1) if i < length / 2 else "*" * (width - 2 * i - 2) rjust_string = string.center(width) print(rjust_string)
Guessing Game
Section titled “Guessing Game”# %%# Guessing Game# -------------# 1. Generate a random number between 1 and 20# 2. Give the player 3 attempts to guess# 3. Provide feedback if the guess is too high or too low# 4. Congratulate the player if they guess correctly# 5. Reveal the answer if they run out of guesses
# %%# Guessing Game# -------------# 1. Generate a random number between 1 and 20# 2. Give the player 3 attempts to guess# 3. Provide feedback if the guess is too high or too low# 4. Congratulate the player if they guess correctly# 5. Reveal the answer if they run out of guessesimport random
n_guesses = 3target = random.randint(1, 20)
for i in range(n_guesses): guess = input(f"Guess {i + 1}/{n_guesses}:")
if str.isdigit(guess): guess = int(guess) else: print(f"'{guess}' is not a number.") continue
if guess > target: print(f"{guess} is too high.") elif guess < target: print(f"{guess} is too low.") else: print(f"You win! The number was {target}.") breakelse: print(f"Game over! The number was {target}.")
Magic 8-Ball
Section titled “Magic 8-Ball”# %%# Create a fortune-telling program that gives random responses to yes/no questions.# - Store 10 different responses in a list (mix of positive, negative, and uncertain)# - Repeatedly ask for questions until user types 'quit'# - Select and display a random response for each question# - Handle empty input with an error message# ---# Example Responses# - Positive: "Yes, definitely", "It is certain", "Outlook good"# - Negative: "Don't count on it", "Very doubtful"# - Uncertain: "Ask again later", "Cannot predict now"# ---# Sample Run# Ask a question: Will it rain tomorrow?# ✨ Most likely## Ask a question:# Need a question!## Ask a question: quit# Goodbye!# ---# Hints# - random.choice(list) to pick random element# - Use while True with break or check for 'quit' in loop condition# - .lower() for case-insensitive quit command
# %%
# %%# Create a fortune-telling program that gives random responses to yes/no questions.# - Store 10 different responses in a list (mix of positive, negative, and uncertain)# - Repeatedly ask for questions until user types 'quit'# - Select and display a random response for each question# - Handle empty input with an error message# ---# Example Responses# - Positive: "Yes, definitely", "It is certain", "Outlook good"# - Negative: "Don't count on it", "Very doubtful"# - Uncertain: "Ask again later", "Cannot predict now"# ---# Sample Run# Ask a question: Will it rain tomorrow?# ✨ Most likely## Ask a question:# Need a question!## Ask a question: quit# Goodbye!# ---# Hints# - random.choice(list) to pick random element# - Use while True with break or check for 'quit' in loop condition# - .lower() for case-insensitive quit command
# %%import random
responses = [ "Yes, definitely", "It is certain", "Without a doubt", "Most likely", "Outlook good", "Ask again later", "Better not tell you now", "Cannot predict now", "Don't count on it", "Very doubtful",]
print("🔮 Magic 8-Ball 🔮")print("Ask a yes/no question (or 'quit' to exit)\n")
while True: question = input("Your question: ").strip()
if question.lower() in ["quit", "q", "exit"]: print("The spirits have departed. Goodbye!") break
if not question: print("The spirits need a question to answer!\n") continue
print("🔮 Consulting the spirits...") answer = random.choice(responses) print(f"✨ {answer}\n")
Dice Rolling Game
Section titled “Dice Rolling Game”# %%# Create a betting game where players guess if two dice will sum to odd or even.# - Start with $100, win at $200, lose at $0# - Each round: bet money → guess odd/even → roll two dice → win or lose bet# - Correct guess doubles your bet, wrong guess loses it# ---# 1 Game loop that runs while balance is between $0 and $200# 2 Get bet amount (1 to current balance)# 3 Get odd/even guess from player# 4 Roll two dice (1-6 each) and show result# 5 Update balance based on outcome# 6 Display win/loss messages at game end# ---# Sample Run# Balance: $100. Bet: 50# Odd or Even? (o/e): e# Rolled 3 + 4 = 7 (odd)# You lost $50!# ---# Hints# random.randint(1, 6) for dice# total % 2 == 0 to check if even# while 0 < balance < 200 for game loop
# %%
# %%# Create a betting game where players guess if two dice will sum to odd or even.# - Start with $100, win at $200, lose at $0# - Each round: bet money → guess odd/even → roll two dice → win or lose bet# - Correct guess doubles your bet, wrong guess loses it# ---# 1 Game loop that runs while balance is between $0 and $200# 2 Get bet amount (1 to current balance)# 3 Get odd/even guess from player# 4 Roll two dice (1-6 each) and show result# 5 Update balance based on outcome# 6 Display win/loss messages at game end# ---# Sample Run# Balance: $100. Bet: 50# Odd or Even? (o/e): e# Rolled 3 + 4 = 7 (odd)# You lost $50!# ---# Hints# random.randint(1, 6) for dice# total % 2 == 0 to check if even# while 0 < balance < 200 for game loop
# %%import random
balance = 100print("🎲 Dice Game 🎲")print(f"Start: ${balance}. Goal: $200\n")
while 0 < balance < 200: bet = min(balance, max(1, int(input(f"Balance: ${balance}. Bet: ")))) guess = input("Odd or Even? (o/e): ").lower()[0]
d1, d2 = random.randint(1, 6), random.randint(1, 6) total = d1 + d2 won = (guess == "e") == (total % 2 == 0)
print(f"Rolled {d1} + {d2} = {total} ({'even' if total % 2 == 0 else 'odd'})") balance += bet if won else -bet print(f"You {'won' if won else 'lost'} ${bet}!\n")
print(f"{'🎉 Winner!' if balance >= 200 else 'Game Over!'} Final: ${balance}")