DAPHNE // Python Tutor

0/10
Loading Python runtime...

01 Numbers & Variables

Key Concepts
Two number types: int (whole numbers) and float (decimals).
  • // — integer division (rounds down)
  • / — true division (always returns float)
  • % — modulo (remainder)
  • ** — power (exponentiation)
Rule: int op int → int (except / which always → float).
Any operation with a float → float.
= is assignment. == is comparison.
Predict the Output
1. 7 // 2 3
2. 7 / 2 3.5
3. 7 % 3 1
4. 2 ** 10 1024
5. type(3) <class 'int'>
6. type(3.0) <class 'float'>
7. type(3 / 1) <class 'float'>
8. 10 + 3 * 2 16
9. 17 % 5 2
10. 2 ** 0 1
Exercises

Calculate the area and volume of a rectangular prism with width=7.3, length=15.1, height=6.

exercise 1.1

You have 1342 eggs. How many gross (144), dozens (12), and singles?

exercise 1.2

Experiment freely with operators:

sandbox

02 Using Functions

Key Concepts
Importing modules:
  • import math — access via math.sqrt()
  • from math import * — imports everything, call sqrt() directly
  • import math as m — alias, call m.sqrt()
  • from math import sin, cos — import specific functions
Useful functions: math.sqrt(), math.sin(), math.cos(), math.radians(), math.pi, round(), abs()
Random: random.randint(a, b), random.uniform(a, b)
Rule: print() displays a value but returns None.
Functions can be nested: math.sin(math.radians(45))
Predict the Output
1. print(print(3)) 3\nNone print(3) displays 3, returns None. Outer print displays None.
2. import math; math.floor(3.9) 3
3. round(3.14159, 2) 3.14
4. abs(-7) 7
Exercises

Calculate 2 × cos(π/6) rounded to 4 decimal places.

exercise 2.1

Simulate rolling 2 dice and print the total.

exercise 2.2

Risk dice: attacker rolls 3 dice, keeps the top 2. Print all 3 rolls and the kept total.

exercise 2.3

03 Strings — Basics

Key Concepts
Strings use '...' or "...". Escape characters:
  • \n — new line
  • \t — tab
  • \\ — literal backslash
  • \' — apostrophe inside single quotes
  • \" — quote inside double quotes
+ concatenates strings (no space).
print(a, b) adds a space between a and b.
'abc' * 3'abcabcabc'
\n counts as 1 character in len().
Predict the Output (Textbook 5.5)
1. number = 2; print('The number is', number) The number is 2
2. print('What\'s', 'the display?') What's the display?
3. print('Some things are', 'double'*2 + ',')
print('others are', 'triple'*3 + '.')
Some things are doubledouble,\nothers are tripletripletriple.
4. print('How do you obtain\na new line?') How do you obtain\na new line? \n creates an actual line break in the output.
5. print('one\n\ttwotwo\none\ttwotwo') one\n twotwo\none twotwo
6. print('Is one the same as \"one\"?') Is one the same as "one"?
7. x = 1; y = 2; print('the sum of', x, 'and', y, 'is equal to', x+y) the sum of 1 and 2 is equal to 3
8. x = 'one'; y = 'two'
print('Does \"' + x, y + '\" = \"' + x + y + '\"?')
Does "one two" = "onetwo"? + concatenates (no space), comma in print adds a space.
Exercises

Build a box around "The answer is 42" using +, *, and \n.

exercise 3.1

Experiment with string operations:

sandbox

04 Booleans & Decisions

Key Concepts
Comparison operators: ==, !=, <, >, <=, >=
Logical operators: and, or, not
Precedence: not binds tightest, then and, then or.
Think of and like multiplication and or like addition.
Common mistake: = (assignment) vs == (comparison).
Truthiness: 0, 0.0, '', [] are False. Everything else is True.
Predict the Boolean (Textbook 6.7)
1. True or False True
2. 1 < 2 or 1 > 2 True
3. 1 < 2 and 1 > 2 False
4. (1 != 2 and 'a' == 'a') or 2 == 3 True
5. 1 != 2 and 'a' == 'a' or 2 == 3 True and binds first: (True and True) or False → True
6. (1 != 2 or 'a' == 'a') and 2 == 3 False
7. 1 != 2 or 'a' == 'a' and 2 == 3 True and binds first: True or (True and False) → True or False → True
8. (1 < 2 or 3 == 3) and (1 == 0 or 1 != 1) False
9. 1 < 2 or 3 == 3 and 1 == 0 or 1 != 1 True True or (True and False) or False → True or False or False → True
10. (1 < 2 and 3 == 3) or (1 == 0 and 1 != 1) True
11. 1 < 2 and 3 == 3 or 1 == 0 and 1 != 1 True (True and True) or (False and False) → True or False → True
12. True or False and True or False and True or False True True or (F and T) or (F and T) or F → True or F or F or F → True
Predict If/Else Output
1. x = 5
if x > 3:
  print('big')
else:
  print('small')
big
2. x = 5
if x > 10:
  print('A')
elif x > 3:
  print('B')
else:
  print('C')
B
3. x = 7
if x > 5:
  print('A')
if x > 3:
  print('B')
A\nB Two separate if statements — both can trigger.
4. x = 0
if x:
  print('truthy')
else:
  print('falsy')
falsy 0 is falsy in Python.
5. s = ''
if s:
  print('has content')
else:
  print('empty')
empty
Exercises

Letter grade program: convert a mark (0-100) to A/B/C/D/E/F.

exercise 4.1

Discount calculator: 10% off over $100, additional 5% off over $200.

exercise 4.2

05 While Loops

Key Concepts
While loop repeats as long as the condition is True.
Three essentials:
1. Variable in test must be defined before the loop.
2. The loop body must update the test variable (or it runs forever!).
3. Loop body is indented.

Accumulator pattern: total = 0 before loop, total += value inside.
Shorthand: x += 1 is the same as x = x + 1
Predict the Output
1. k = 1
while k <= 3:
  print(k)
  k += 1
1\n2\n3
2. total = 0; k = 1
while k <= 4:
  total += k
  k += 1
print(total)
10 1 + 2 + 3 + 4 = 10
3. n = 8
while n > 1:
  n = n // 2
  print(n)
4\n2\n1
Exercises

Print the squares of 1 through 10.

exercise 5.1

Calculate the sum of squares from 1 to N (try N=10).

exercise 5.2

Integer division using repeated subtraction (compute a // b without using //).

exercise 5.3

GCD using the Euclidean algorithm.

exercise 5.4

06 Lists

Key Concepts
Lists are ordered, mutable collections: [1, 2, 3]
  • list[i] — access element at index i (0-based)
  • list[-1] — last element
  • list[a:b] — slice from index a to b-1
  • append(), insert(), remove(), pop(), sort()
  • len(), sum(), min(), max()
Lists are mutable — you can change elements in place.
Tuples (1, 2, 3) are immutable — once created, cannot be changed.
list.index(x) returns the position of x in the list.
Predict the Output
1. a = [10, 20, 30, 40, 50]; print(a[0]) 10
2. a = [10, 20, 30, 40, 50]; print(a[-1]) 50
3. a = [10, 20, 30, 40, 50]; print(a[1:3]) [20, 30]
4. a = [10, 20, 30, 40, 50]; print(a[:2]) [10, 20]
5. a = [10, 20, 30, 40, 50]; print(a[3:]) [40, 50]
6. a = [3, 1, 4, 1, 5]; a.sort(); print(a) [1, 1, 3, 4, 5]
7. a = [1, 2, 3]; a.append(4); print(len(a)) 4
8. a = [1, 2, 3]; b = a.pop(); print(b, a) 3 [1, 2]
Exercises

Generate 10 random numbers (1-100), find min, max, and average.

exercise 6.1

Build a list of squares from 1 to 20.

exercise 6.2

07 For Loops

Key Concepts
For loop iterates over a sequence (list, range, string).
  • range(n) → 0, 1, 2, ..., n-1
  • range(a, b) → a, a+1, ..., b-1
  • range(a, b, step) → a, a+step, a+2*step, ... (while < b)
  • enumerate(list) → gives both index and value
List comprehension: [expr for x in sequence]
Compact way to build a list in one line.
Example: [x**2 for x in range(5)][0, 1, 4, 9, 16]
Predict the Output
1. [x**2 for x in range(5)] [0, 1, 4, 9, 16]
2. list(range(3, 8)) [3, 4, 5, 6, 7]
3. list(range(0, 10, 3)) [0, 3, 6, 9]
4. list(range(5, 0, -1)) [5, 4, 3, 2, 1]
5. [c.upper() for c in 'hello'] ['H', 'E', 'L', 'L', 'O']
Exercises

Sum of the first 100 positive integers using a for loop.

exercise 7.1

Print a multiplication table (1-5).

exercise 7.2

Use a list comprehension to get squares of even numbers from 0 to 20.

exercise 7.3

Enumerate: print each fruit with its index.

exercise 7.4

08 Strings — Advanced

Key Concepts
f-strings (formatted string literals): f"Hello {name}"
String methods:
  • .split() — split into list by whitespace (or given delimiter)
  • ' '.join(list) — join list items with a separator
  • .upper(), .lower() — case conversion
  • .replace(old, new) — replace substrings
  • .find(sub) — find position of substring (-1 if not found)
  • .strip() — remove leading/trailing whitespace
String slicing: s[a:b] works just like list slicing.
s[::-1] reverses the string.
Strings are immutable — methods return new strings.
Predict the Output
1. name = 'Alice'; f"Hello, {name}!" 'Hello, Alice!'
2. x = 3; f"{x} squared is {x**2}" '3 squared is 9'
3. 'hello world'.split() ['hello', 'world']
4. '-'.join(['a', 'b', 'c']) 'a-b-c'
5. 'Python'[::-1] 'nohtyP'
6. 'hello'.replace('l', 'L') 'heLLo'
7. 'banana'.find('nan') 2
Exercises

Reverse a string using slicing.

exercise 8.1

Count the vowels in a string.

exercise 8.2

Experiment with f-strings and string methods.

sandbox

09 Functions

Key Concepts
Defining a function: def function_name(parameters):
Returning a value: return value
print vs return:
print() displays a value on screen. return sends a value back to the caller.
A function without return returns None.

Scope: Variables inside a function are local — they don't exist outside.
Order: A function must be defined before it is called.
Default arguments: def greet(name='World')
Predict the Output
1. def add(a, b):
  return a + b
print(add(3, 4))
7
2. def add(a, b):
  print(a + b)
result = add(3, 4)
print(result)
7\nNone print() inside the function displays 7, but the function returns None.
3. x = 10
def change():
  x = 20
change()
print(x)
10 x inside the function is local — it doesn't affect the global x.
4. def greet(name='World'):
  return f'Hello, {name}!'
print(greet())
print(greet('Alice'))
Hello, World!\nHello, Alice!
Exercises

Write an is_even(n) function that returns True if n is even.

exercise 9.1

Write factorial(n) using recursion.

exercise 9.2

Write distance(x1, y1, x2, y2) that computes the Euclidean distance.

exercise 9.3

Challenge: write a function that checks if a number is prime.

exercise 9.4

10 Exam Prep Workbook

Quick Reference Card

f-strings:     f"text {variable} more {expression:.2f}"
sum/max/min:   sum(list), max(list), min(list), list.index(max(list))
while pattern: total=0; i=0; while i<n: total+=item; i+=1
bool precedence: not > and > or (like: NOT > * > +)
slicing:       s[start:stop:step], s[::-1] reverses

Topic 1: String Formatting & f-strings

f-string syntax: Prefix a string with f and put expressions inside {}.
Format specifiers go after a colon inside the braces:
  • :.2f — 2 decimal places (float)
  • :>10 — right-align in 10 characters
  • :<10 — left-align in 10 characters
  • :^10 — center in 10 characters
  • :08d — zero-pad to 8 digits
f"Pi is {3.14159:.2f}""Pi is 3.14"
f"{'hello':>20}" → right-aligned in 20 chars
You can put any expression inside the braces: f"{2 + 3}""5"

Exercise 1: Given price = 19.99, produce the string "The price is $19.99" using an f-string.

Exercise 2: Format a table row: name left-aligned in 15 characters, grade right-aligned in 5 characters. Test with name="Alice", grade="A+".

Exercise 3: Build a receipt with aligned columns: item name (left, 20 chars), quantity (right, 5), unit price (right, 8, 2 decimals), total (right, 10, 2 decimals).

Topic 2: List Operations

Key list operations:
  • list[i] — access by index, list[-1] — last element
  • list[a:b] — slice, list[::-1] — reverse
  • append(), insert(i, x), remove(x), pop()
  • sum(), max(), min(), len(), sorted()
  • list.index(x) — find position of value x
Find max and its position:
highest = max(scores)
position = scores.index(highest)

Exercise 1: Given scores = [88, 92, 75, 98, 84], find the highest score and its position (index).

Exercise 2: Remove duplicates from [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] while preserving order.

Exercise 3: Compute the running average of [10, 20, 30, 40, 50]. After each element, print the average of all elements seen so far.

Topic 3: While Loop Patterns

Common while-loop patterns:
  • Counter: i = 0; while i < n: ...; i += 1
  • Accumulator: total = 0; while ...: total += value
  • Sentinel: Loop until a special value is encountered
  • Validation: Keep asking until input is valid
Always ensure:
1. Loop variable initialized before the loop
2. Loop variable updated inside the loop
3. Condition will eventually become False

Exercise 1: Sum the integers from 1 to 100 using a while loop.

Exercise 2: Input validation loop — keep asking for a number between 1 and 10. (Simulated with a pre-set list of attempts.)

Exercise 3: Collatz conjecture — starting from n, if even: n = n/2, if odd: n = 3n+1. Count steps to reach 1. Try n=27.

Topic 4: Boolean Logic & Operator Precedence

Truth tables:
  • True and True → True  |  True and False → False
  • True or False → True  |  False or False → False
  • not True → False  |  not False → True
Precedence (highest to lowest): not > and > or
Think of it like arithmetic: not = unary minus, and = multiplication, or = addition.

Short-circuit evaluation:
True or X → True (X is never evaluated)
False and X → False (X is never evaluated)

Evaluate these 15 expressions mentally, then click to reveal the answer:

1. True or False True
2. 1 < 2 or 1 > 2 True
3. 1 < 2 and 1 > 2 False
4. (1 != 2 and 'a'=='a') or 2 == 3 True
5. 1 != 2 and 'a'=='a' or 2 == 3 True
6. (1 != 2 or 'a'=='a') and 2 == 3 False
7. 1 != 2 or 'a'=='a' and 2 == 3 True TRICKY — and binds first: True or (True and False) → True
8. (1 < 2 or 3 == 3) and (1 == 0 or 1 != 1) False
9. 1 < 2 or 3 == 3 and 1 == 0 or 1 != 1 True
10. (1 < 2 and 3 == 3) or (1 == 0 and 1 != 1) True
11. 1 < 2 and 3 == 3 or 1 == 0 and 1 != 1 True
12. True or False and True or False and True or False True
13. not True and False or True True (not True) and False or True → False and False or True → True
14. not (True and False) or True True
15. not (True or False) and True False not True and True → False and True → False

Verify your answers:

verify booleans

Topic 5: Writing Functions

Function essentials:
  • def function_name(params): — define a function
  • return value — send a value back to the caller
  • print() displays but returns None
  • Variables inside a function are local (not visible outside)
  • def greet(name='World') — default argument
Common mistake: Using print() instead of return.
If you need to use the result later, the function must return it.
print() is only for displaying to the screen.

Exercise 1: Write is_palindrome(s) that checks if a string reads the same forwards and backwards.

Exercise 2: Write letter_grade(mark) that returns A (90+), B (80+), C (70+), D (60+), E (50+), or F.

Exercise 3: Write fibonacci(n) that returns the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8, ...).