recap

NSFW

Python Make-Up Exam Final Recap / Cheat Sheet

This guide covers the exact style of problems from the midterm:

  1. BMI category
  2. Student grade
  3. Number guessing game
  4. Shopping cart
  5. Password validator bonus

It also includes the main patterns that can appear in similar make-up problems.

0. General Exam Strategy

Most problems follow this structure:

def function_name():
    # 1. Ask for input

    # 2. Validate input if needed

    # 3. Do calculation / logic

    # 4. Use if / elif / else

    # 5. return or print result

At the end, run the function:

print(function_name())

or:

function_name()

Use print(...) when the task says display / print.
Use return ... when the task says return.

1. Basic Python Things You Must Know

Input

name = input("Enter name: ")

Important: input() always gives a string.

So if user types:

25

Python stores it as:

"25"

not:

25

For numbers, convert it.

Integer:

age = int(input("Enter age: "))

Decimal number:

height = float(input("Enter height: "))

Use int() for whole numbers.
Use float() for decimal numbers.

2. Print and f-strings

Normal print:

print("Hello")

Print variable:

name = "Giorgi"
print("Hello", name)

f-string:

name = "Giorgi"
print(f"Hello, {name}")

Another example:

total = 29.6
print(f"Total: {total:.2f}")

Output:

Total: 29.60

:.2f means show 2 digits after decimal point.

3. If / Elif / Else

Use this when there are categories.

if condition:
    ...
elif condition:
    ...
else:
    ...

Example:

score = 85

if score >= 91:
    grade = "A"
elif score >= 81:
    grade = "B"
elif score >= 71:
    grade = "C"
else:
    grade = "F"

Important rule:

When using >=, usually go from biggest to smallest.

if score >= 91:
elif score >= 81:
elif score >= 71:

When using <, usually go from smallest to biggest.

if bmi < 18.5:
elif bmi < 25:
elif bmi < 30:
else:

4. Try / Except for Validation

Use this when user must enter a number.

try:
    number = int(input("Enter number: "))
except ValueError:
    print("Invalid number")

If user enters:

hello

then int("hello") fails, but your program does not crash.

For decimal:

try:
    weight = float(input("Enter weight: "))
except ValueError:
    print("Invalid number")

5. While True

Use this when you want to keep asking until input is correct.

while True:
    answer = input("Type done: ")

    if answer == "done":
        break

break stops the loop.

Example for valid positive number:

while True:
    try:
        number = float(input("Enter positive number: "))

        if number <= 0:
            print("Number must be greater than 0.")
        else:
            break

    except ValueError:
        print("Please enter a valid number.")

6. Lists

Create list:

cart = []

Add item:

cart.append("Apple")

Remove item:

cart.remove("Apple")

Check if item exists:

if "Apple" in cart:
    cart.remove("Apple")

Loop through list:

for item in cart:
    print(item)

Sorted list:

for item in sorted(cart):
    print(item)

7. Dictionaries

Dictionary stores key-value pairs.

prices = {
    "Apple": 2.7,
    "Cola": 4.5
}

Get price:

prices["Apple"]

Output:

2.7

Check if item exists in dictionary:

if item in prices:
    print(prices[item])
else:
    print("Item not found")

8. Split Input

If user enters numbers in one line:

20 30 40

Use:

scores = input("Enter scores: ").split()

This gives:

["20", "30", "40"]

They are still strings.

Convert to integers:

scores = [int(score) for score in scores]

Short version:

scores = [int(score) for score in input("Enter scores: ").split()]

Then:

total = sum(scores)

9. Important List Comprehension

This:

scores = [int(score) for score in scores]

means:

Go through every item in scores, convert it to integer, and make a new list.

Example:

Before:

scores = ["20", "30", "40"]

After:

scores = [20, 30, 40]

Long version:

new_scores = []

for score in scores:
    new_scores.append(int(score))

scores = new_scores

10. String Methods

text.lower()

makes lowercase.

"ADD".lower()

becomes:

"add"


text.title()

makes title case.

"apple".title()

becomes:

"Apple"


text.strip()

removes spaces from beginning and end.

"  add apple  ".strip()

becomes:

"add apple"


text.split()

splits by spaces.

"add apple".split()

gives:

["add", "apple"]

11. Problem 1 — BMI Category

Task

Create function bmi_category().

Ask for:

  • name
  • weight in kg
  • height in meters

Calculate:

BMI = weight / height²

In Python:

bmi = weight / (height ** 2)

Categories:

Underweight: BMI < 18.5
Normal weight: 18.5 <= BMI < 25
Overweight: 25 <= BMI < 30
Obese: BMI >= 30

Return dictionary:

{"name": name, "category": category}

Perfect Solution

def bmi_category():
    name = input("Enter your name: ")

    while True:
        try:
            weight = float(input("Enter your weight in kg: "))

            if weight <= 0:
                print("Weight must be greater than 0.")
            else:
                break

        except ValueError:
            print("Please enter a valid number for weight.")

    while True:
        try:
            height = float(input("Enter your height in meters: "))

            if height <= 0:
                print("Height must be greater than 0.")
            else:
                break

        except ValueError:
            print("Please enter a valid number for height.")

    bmi = weight / (height ** 2)

    if bmi < 18.5:
        category = "Underweight"
    elif bmi < 25:
        category = "Normal weight"
    elif bmi < 30:
        category = "Overweight"
    else:
        category = "Obese"

    return {"name": name, "category": category}


print(bmi_category())

What to remember

bmi = weight / (height ** 2)

Use float() because weight and height can be decimals.

Use this category pattern:

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal weight"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

You do not need to write:

elif bmi >= 18.5 and bmi < 25:

because if Python reaches that line, it already knows BMI was not below 18.5.

12. Similar BMI-Style Problems

This problem type means:

input number → calculate → category → return dictionary

Similar examples:

Age Category

def age_category():
    name = input("Enter name: ")

    age = int(input("Enter age: "))

    if age < 13:
        category = "Child"
    elif age < 20:
        category = "Teenager"
    elif age < 65:
        category = "Adult"
    else:
        category = "Senior"

    return {"name": name, "category": category}


print(age_category())

Temperature Category

def temperature_category():
    temperature = float(input("Enter temperature: "))

    if temperature < 0:
        category = "Freezing"
    elif temperature < 15:
        category = "Cold"
    elif temperature < 25:
        category = "Warm"
    else:
        category = "Hot"

    return {"category": category}


print(temperature_category())

13. Problem 2 — Student Grade

Task

Create function calculate_grade().

Ask:

  • student name
  • scores in one input, separated by spaces

Example input:

30 25 28

Find sum:

total_score = sum(scores)

Grading:

A: 91–100
B: 81–90
C: 71–80
D: 61–70
E: 51–60
F: below 51

Return:

{"name": name, "grade": grade}

Perfect Solution

def calculate_grade():
    name = input("Enter student's name: ")

    while True:
        try:
            scores = [int(score) for score in input("Enter scores separated by spaces: ").split()]

            if len(scores) == 0:
                print("Please enter at least one score.")
            elif any(score < 0 for score in scores):
                print("Scores cannot be negative.")
            elif sum(scores) > 100:
                print("Total score cannot be greater than 100.")
            else:
                break

        except ValueError:
            print("Please enter only integer numbers separated by spaces.")

    total_score = sum(scores)

    if total_score >= 91:
        grade = "A"
    elif total_score >= 81:
        grade = "B"
    elif total_score >= 71:
        grade = "C"
    elif total_score >= 61:
        grade = "D"
    elif total_score >= 51:
        grade = "E"
    else:
        grade = "F"

    return {"name": name, "grade": grade}


print(calculate_grade())

Important line

scores = [int(score) for score in input("Enter scores separated by spaces: ").split()]

Meaning:

  1. User enters "30 25 28"
  2. .split() makes ["30", "25", "28"]
  3. int(score) converts to [30, 25, 28]

Then:

total_score = sum(scores)

Grade logic

Use >= from highest to lowest:

if total_score >= 91:
    grade = "A"
elif total_score >= 81:
    grade = "B"
elif total_score >= 71:
    grade = "C"
elif total_score >= 61:
    grade = "D"
elif total_score >= 51:
    grade = "E"
else:
    grade = "F"

Do not start from 51, because then 95 would also be greater than 51 and get wrong grade.

14. Similar Student Grade Problems

Average Grade

Instead of sum:

average = sum(scores) / len(scores)

Code:

def calculate_average_grade():
    name = input("Enter student's name: ")

    try:
        scores = [int(score) for score in input("Enter scores: ").split()]

        if len(scores) == 0:
            return "Invalid input"

        average = sum(scores) / len(scores)

        if average >= 91:
            grade = "A"
        elif average >= 81:
            grade = "B"
        elif average >= 71:
            grade = "C"
        elif average >= 61:
            grade = "D"
        elif average >= 51:
            grade = "E"
        else:
            grade = "F"

        return {"name": name, "grade": grade}

    except ValueError:
        return "Invalid input"


print(calculate_average_grade())

Pass / Fail

def pass_fail():
    name = input("Enter student's name: ")

    try:
        scores = [int(score) for score in input("Enter scores: ").split()]
        total = sum(scores)

        if total >= 51:
            result = "Pass"
        else:
            result = "Fail"

        return {"name": name, "result": result}

    except ValueError:
        return "Invalid input"


print(pass_fail())

Highest Score

def highest_score():
    scores = [int(score) for score in input("Enter scores: ").split()]
    return max(scores)


print(highest_score())

Lowest Score

def lowest_score():
    scores = [int(score) for score in input("Enter scores: ").split()]
    return min(scores)


print(lowest_score())

Count Passing Scores

def count_passing_scores():
    scores = [int(score) for score in input("Enter scores: ").split()]

    count = 0

    for score in scores:
        if score >= 51:
            count += 1

    return count


print(count_passing_scores())

15. Problem 3 — Number Guessing Game

Task

Create function guess().

Difficulty:

Easy: 1–50, 10 guesses
Hard: 1–100, 7 guesses

Use random number.

After each guess, print:

Too high
Too low
Correct

Show guesses remaining.

If user runs out, reveal number.

Reject:

  • non-integers
  • out-of-range guesses

Perfect Solution

import random

def guess():
    while True:
        difficulty = input("Choose difficulty: easy or hard: ").lower()

        if difficulty == "easy":
            max_number = 50
            attempts = 10
            break
        elif difficulty == "hard":
            max_number = 100
            attempts = 7
            break
        else:
            print("Invalid difficulty. Please choose easy or hard.")

    secret_number = random.randint(1, max_number)

    print("I chose a number between 1 and", max_number)

    while attempts > 0:
        try:
            user_guess = int(input("Enter your guess: "))

            if user_guess < 1 or user_guess > max_number:
                print("Invalid guess. Enter a number between 1 and", max_number)
                continue

            attempts -= 1

            if user_guess == secret_number:
                print("Correct!")
                return

            elif user_guess > secret_number:
                print("Too high!")

            else:
                print("Too low!")

            print("Guesses remaining:", attempts)

        except ValueError:
            print("Please enter an integer number.")

    print("You ran out of guesses. The number was", secret_number)


guess()

Important things

Import random:

import random

Generate number:

secret_number = random.randint(1, max_number)

random.randint(1, 50) includes both 1 and 50.

Attempts loop:

while attempts > 0:

Subtract one attempt after a valid guess:

attempts -= 1

Correct answer stops the function:

if user_guess == secret_number:
    print("Correct!")
    return

Out-of-range guess should not count:

if user_guess < 1 or user_guess > max_number:
    print("Invalid guess")
    continue

continue means skip rest of loop and ask again.

16. Similar Guessing Game Problems

Dice Guessing Game

import random

def dice_guess():
    secret_number = random.randint(1, 6)
    attempts = 3

    while attempts > 0:
        try:
            user_guess = int(input("Guess number from 1 to 6: "))

            if user_guess < 1 or user_guess > 6:
                print("Enter number between 1 and 6.")
                continue

            attempts -= 1

            if user_guess == secret_number:
                print("Correct!")
                return
            else:
                print("Wrong!")
                print("Attempts left:", attempts)

        except ValueError:
            print("Enter an integer.")

    print("You lost. The number was", secret_number)


dice_guess()

PIN Guessing Game

import random

def pin_game():
    pin = random.randint(1000, 9999)
    attempts = 5

    while attempts > 0:
        try:
            guess = int(input("Enter 4-digit PIN: "))

            if guess < 1000 or guess > 9999:
                print("PIN must be 4 digits.")
                continue

            attempts -= 1

            if guess == pin:
                print("Correct PIN!")
                return
            else:
                print("Wrong PIN.")
                print("Attempts left:", attempts)

        except ValueError:
            print("Enter only integers.")

    print("You failed. The PIN was", pin)


pin_game()

Random Math Quiz

import random

def math_quiz():
    a = random.randint(1, 20)
    b = random.randint(1, 20)
    correct_answer = a + b

    attempts = 3

    print("What is", a, "+", b, "?")

    while attempts > 0:
        try:
            answer = int(input("Enter answer: "))

            attempts -= 1

            if answer == correct_answer:
                print("Correct!")
                return
            else:
                print("Wrong.")
                print("Attempts left:", attempts)

        except ValueError:
            print("Enter an integer.")

    print("You lost. Correct answer was", correct_answer)


math_quiz()

Random Word Guess

import random

def word_guess():
    words = ["apple", "banana", "cherry"]
    secret_word = random.choice(words)

    attempts = 3

    while attempts > 0:
        guess = input("Guess word: ").lower()

        attempts -= 1

        if guess == secret_word:
            print("Correct!")
            return
        else:
            print("Wrong!")
            print("Attempts left:", attempts)

    print("You lost. The word was", secret_word)


word_guess()

Use:

random.randint(1, 100)

for random numbers.

Use:

random.choice(words)

for random item from a list.

17. Problem 4 — Shopping Cart

Task

Create function shopping_cart().

Use dictionary:

{
    "Apple": 2.7,
    "Orange": 3.5,
    "Cola": 4.5,
    "Mascarpone": 14.9,
    "Beef": 22.4,
    "Pork": 18.9,
    "Nutella": 27.5
}

Start with empty list:

cart = []

Commands:

add apple
remove apple
show
done

show displays all items sorted alphabetically and total.

done shows final total and exits.

Ignore case:

ADD apple
Add Apple
add apple

should all work.

Perfect Simple Solution

def shopping_cart():
    prices = {
        "Apple": 2.7,
        "Orange": 3.5,
        "Cola": 4.5,
        "Mascarpone": 14.9,
        "Beef": 22.4,
        "Pork": 18.9,
        "Nutella": 27.5
    }

    cart = []

    while True:
        user_input = input("Enter command: ").strip()

        if user_input.lower() == "show":
            total = 0

            print("Shopping cart:")

            for item in sorted(cart):
                price = prices[item]
                total += price
                print(f"{item}: {price}")

            print(f"Total: {total:.2f}")

        elif user_input.lower() == "done":
            total = 0

            print("Shopping cart:")

            for item in sorted(cart):
                price = prices[item]
                total += price
                print(f"{item}: {price}")

            print(f"Total: {total:.2f}")
            break

        else:
            parts = user_input.split()

            if len(parts) < 2:
                print("Invalid command")
                continue

            command = parts[0].lower()
            item = parts[1].title()

            if command == "add":
                if item in prices:
                    cart.append(item)
                    print(item, "added")
                else:
                    print("Item not found")

            elif command == "remove":
                if item in cart:
                    cart.remove(item)
                    print(item, "removed")
                else:
                    print("Item not found")

            else:
                print("Invalid command")


shopping_cart()

Meaning

Dictionary:

prices = {"Apple": 2.7}

means Apple costs 2.7.

Empty cart:

cart = []

Add:

cart.append(item)

Remove:

cart.remove(item)

Check if item exists in shop:

if item in prices:

Check if item exists in cart:

if item in cart:

Sorted display:

for item in sorted(cart):

Total:

total = 0
total += price

total = 0 means start counting from zero.

total += price means:

total = total + price

Show vs Done

They are almost the same.

show = show cart and continue
done = show cart and stop

The only difference is:

break

done has break.
show does not.

18. Better Shopping Cart with Helper Function

This avoids repeating show code.

def shopping_cart():
    prices = {
        "Apple": 2.7,
        "Orange": 3.5,
        "Cola": 4.5,
        "Mascarpone": 14.9,
        "Beef": 22.4,
        "Pork": 18.9,
        "Nutella": 27.5
    }

    cart = []

    def show_cart():
        total = 0

        print("Shopping cart:")

        for item in sorted(cart):
            price = prices[item]
            total += price
            print(f"{item}: {price}")

        print(f"Total: {total:.2f}")

    while True:
        user_input = input("Enter command: ").strip()

        if user_input.lower() == "show":
            show_cart()

        elif user_input.lower() == "done":
            show_cart()
            break

        else:
            parts = user_input.split()

            if len(parts) < 2:
                print("Invalid command")
                continue

            command = parts[0].lower()
            item = parts[1].title()

            if command == "add":
                if item in prices:
                    cart.append(item)
                    print(item, "added")
                else:
                    print("Item not found")

            elif command == "remove":
                if item in cart:
                    cart.remove(item)
                    print(item, "removed")
                else:
                    print("Item not found")

            else:
                print("Invalid command")


shopping_cart()

19. Similar Shopping Cart Problems

To-Do List Manager

def todo_list():
    tasks = []

    while True:
        user_input = input("Enter command: ").strip()

        if user_input.lower() == "show":
            for task in sorted(tasks):
                print(task)

        elif user_input.lower() == "done":
            for task in sorted(tasks):
                print(task)
            break

        else:
            parts = user_input.split(maxsplit=1)

            if len(parts) < 2:
                print("Invalid command")
                continue

            command = parts[0].lower()
            task = parts[1].title()

            if command == "add":
                tasks.append(task)
                print(task, "added")

            elif command == "remove":
                if task in tasks:
                    tasks.remove(task)
                    print(task, "removed")
                else:
                    print("Item not found")

            else:
                print("Invalid command")


todo_list()

Food Order System

def food_order():
    menu = {
        "Burger": 12,
        "Pizza": 18,
        "Water": 2,
        "Coffee": 5
    }

    order = []

    while True:
        user_input = input("Enter command: ").strip()

        if user_input.lower() == "show":
            total = 0

            for item in sorted(order):
                print(item, menu[item])
                total += menu[item]

            print("Total:", total)

        elif user_input.lower() == "done":
            total = 0

            for item in sorted(order):
                print(item, menu[item])
                total += menu[item]

            print("Total:", total)
            break

        else:
            parts = user_input.split()

            if len(parts) < 2:
                print("Invalid command")
                continue

            command = parts[0].lower()
            item = parts[1].title()

            if command == "add":
                if item in menu:
                    order.append(item)
                else:
                    print("Item not found")

            elif command == "remove":
                if item in order:
                    order.remove(item)
                else:
                    print("Item not found")

            else:
                print("Invalid command")


food_order()

20. Bonus — Password Validator

Task

Create function:

is_valid_password()

Rules:

  • at least 8 characters
  • at least one digit
  • at least one uppercase letter
  • at least one lowercase letter
  • print which rule failed
  • return True or False
  • keep asking until password is accepted

Perfect Solution

def is_valid_password(password):
    valid = True

    if len(password) < 8:
        print("Password must be at least 8 characters long.")
        valid = False

    if not any(char.isdigit() for char in password):
        print("Password must contain at least one digit.")
        valid = False

    if not any(char.isupper() for char in password):
        print("Password must contain at least one uppercase letter.")
        valid = False

    if not any(char.islower() for char in password):
        print("Password must contain at least one lowercase letter.")
        valid = False

    return valid


while True:
    password = input("Create a password: ")

    if is_valid_password(password):
        print("Password accepted!")
        break
    else:
        print("Please try again.")

Important Methods

Length:

len(password)

Digit:

char.isdigit()

Uppercase:

char.isupper()

Lowercase:

char.islower()

At least one digit:

any(char.isdigit() for char in password)

No digit:

not any(char.isdigit() for char in password)

any(...) means at least one exists.
not any(...) means none exists.

21. Similar Validator Problems

PIN Validator

Rules:

  • exactly 4 digits
  • only numbers

​

def is_valid_pin(pin):
    if len(pin) != 4:
        print("PIN must be exactly 4 digits.")
        return False

    if not pin.isdigit():
        print("PIN must contain only digits.")
        return False

    return True


while True:
    pin = input("Create PIN: ")

    if is_valid_pin(pin):
        print("PIN accepted!")
        break
    else:
        print("Try again.")

Email Validator

Simple version:

def is_valid_email(email):
    valid = True

    if "@" not in email:
        print("Email must contain @.")
        valid = False

    if "." not in email:
        print("Email must contain a dot.")
        valid = False

    if len(email) < 5:
        print("Email is too short.")
        valid = False

    return valid


while True:
    email = input("Enter email: ")

    if is_valid_email(email):
        print("Email accepted!")
        break
    else:
        print("Try again.")

Username Validator

Rules:

  • at least 5 characters
  • starts with a letter
  • only letters and digits

​

def is_valid_username(username):
    valid = True

    if len(username) < 5:
        print("Username must be at least 5 characters.")
        valid = False

    if not username[0].isalpha():
        print("Username must start with a letter.")
        valid = False

    if not username.isalnum():
        print("Username must contain only letters and digits.")
        valid = False

    return valid


while True:
    username = input("Create username: ")

    if is_valid_username(username):
        print("Username accepted!")
        break
    else:
        print("Try again.")

22. File Handling Patterns

These may appear from lecture 7.

Write to file

"w" means write and overwrite old file.

name = input("What's your name? ")

with open("names.txt", "w") as file:
    file.write(name)

Append to file

"a" means append, add to end.

name = input("What's your name? ")

with open("names.txt", "a") as file:
    file.write(f"{name}\n")

\n means new line.

Read file

with open("names.txt") as file:
    lines = file.readlines()

for line in lines:
    print(line.rstrip())

rstrip() removes newline at the end.

Read file line by line

with open("names.txt") as file:
    for line in file:
        print(line.rstrip())

Read and sort names

with open("names.txt") as file:
    names = file.readlines()

for name in sorted(names):
    print(name.rstrip())

23. Common Mini Problems

Ask for 3 names and print sorted

def sorted_names():
    names = []

    for _ in range(3):
        name = input("Enter name: ")
        names.append(name)

    for name in sorted(names):
        print(name)


sorted_names()

Sum numbers

def sum_numbers():
    numbers = [int(x) for x in input("Enter numbers: ").split()]
    print(sum(numbers))


sum_numbers()

Average numbers

def average_numbers():
    numbers = [int(x) for x in input("Enter numbers: ").split()]
    average = sum(numbers) / len(numbers)
    print(average)


average_numbers()

Count positive numbers

def count_positive():
    numbers = [int(x) for x in input("Enter numbers: ").split()]

    count = 0

    for number in numbers:
        if number > 0:
            count += 1

    print(count)


count_positive()

Even numbers

def even_numbers():
    numbers = [int(x) for x in input("Enter numbers: ").split()]

    evens = []

    for number in numbers:
        if number % 2 == 0:
            evens.append(number)

    print(evens)


even_numbers()

number % 2 == 0 means number is even.

Dictionary lookup

def price_lookup():
    prices = {
        "Apple": 2.7,
        "Cola": 4.5
    }

    item = input("Enter item: ").title()

    if item in prices:
        print(prices[item])
    else:
        print("Item not found")


price_lookup()

24. Common Errors

IndentationError

Wrong:

def test():
print("hello")

Correct:

def test():
    print("hello")

Python needs indentation inside functions, loops, and if statements.

ValueError

Happens when conversion fails.

Example:

int("abc")

Fix:

try:
    x = int(input("Enter number: "))
except ValueError:
    print("Invalid number")

NameError

Happens when variable does not exist.

Wrong:

print(total)

before:

total = 0

Correct:

total = 0
print(total)

KeyError

Happens when dictionary key does not exist.

Wrong:

prices["Milk"]

if "Milk" is not in dictionary.

Correct:

if item in prices:
    print(prices[item])
else:
    print("Item not found")

IndexError

Happens when list position does not exist.

Wrong:

parts = ["add"]
item = parts[1]

Correct:

if len(parts) < 2:
    print("Invalid command")
else:
    item = parts[1]

TypeError

Example:

sum(["20", "30"])

Wrong because they are strings.

Correct:

numbers = [int(x) for x in ["20", "30"]]
sum(numbers)

25. Final Must-Memorize Patterns

Function

def function_name():
    ...

Call function

function_name()

or:

print(function_name())

Integer input

x = int(input("Enter number: "))

Float input

x = float(input("Enter number: "))

Validate number

while True:
    try:
        x = int(input("Enter number: "))
        break
    except ValueError:
        print("Invalid number")

Validate positive number

while True:
    try:
        x = float(input("Enter number: "))

        if x <= 0:
            print("Must be positive.")
        else:
            break

    except ValueError:
        print("Invalid number")

Many numbers in one input

numbers = [int(x) for x in input("Enter numbers: ").split()]

Sum

total = sum(numbers)

Average

average = sum(numbers) / len(numbers)

Empty list

items = []

Add to list

items.append(item)

Remove from list

items.remove(item)

Check item in list

if item in items:

Dictionary

prices = {"Apple": 2.7}

Dictionary lookup

prices[item]

Check item in dictionary

if item in prices:

Random number

import random

number = random.randint(1, 100)

Random choice from list

import random

word = random.choice(words)

Password checks

len(password) < 8


not any(char.isdigit() for char in password)


not any(char.isupper() for char in password)


not any(char.islower() for char in password)

Stop loop

break

Skip current loop

continue

Exit function

return

26. The 5 Most Useful Skeletons

Skeleton 1: Category Function

def category_function():
    name = input("Enter name: ")
    value = float(input("Enter value: "))

    if value < something:
        category = "Category 1"
    elif value < something:
        category = "Category 2"
    else:
        category = "Category 3"

    return {"name": name, "category": category}


print(category_function())

Use for BMI, age, temperature, discount.

Skeleton 2: Scores Function

def scores_function():
    name = input("Enter name: ")
    scores = [int(score) for score in input("Enter scores: ").split()]

    total = sum(scores)

    if total >= 91:
        grade = "A"
    elif total >= 81:
        grade = "B"
    else:
        grade = "F"

    return {"name": name, "grade": grade}


print(scores_function())

Use for grades, average, pass/fail.

Skeleton 3: Guessing Game

import random

def game():
    secret = random.randint(1, 100)
    attempts = 7

    while attempts > 0:
        try:
            guess = int(input("Enter guess: "))

            attempts -= 1

            if guess == secret:
                print("Correct!")
                return
            elif guess > secret:
                print("Too high!")
            else:
                print("Too low!")

            print("Attempts left:", attempts)

        except ValueError:
            print("Enter integer.")

    print("You lost. Number was", secret)


game()

Use for number guessing, dice, PIN, math quiz.

Skeleton 4: List Manager

def manager():
    items = []

    while True:
        user_input = input("Enter command: ").strip()

        if user_input.lower() == "show":
            for item in sorted(items):
                print(item)

        elif user_input.lower() == "done":
            for item in sorted(items):
                print(item)
            break

        else:
            parts = user_input.split()

            if len(parts) < 2:
                print("Invalid command")
                continue

            command = parts[0].lower()
            item = parts[1].title()

            if command == "add":
                items.append(item)

            elif command == "remove":
                if item in items:
                    items.remove(item)
                else:
                    print("Item not found")

            else:
                print("Invalid command")


manager()

Use for shopping cart, to-do list, contact list.

Skeleton 5: Validator

def is_valid(value):
    valid = True

    if condition_failed:
        print("Rule failed")
        valid = False

    if condition_failed:
        print("Rule failed")
        valid = False

    return valid


while True:
    value = input("Enter value: ")

    if is_valid(value):
        print("Accepted!")
        break
    else:
        print("Try again.")

Use for password, PIN, email, username.

Final Exam Memory

For this make-up, the most likely things are:

function
input
int / float
try / except
while True
for loop
list
dictionary
if / elif / else
sum
len
sorted
random.randint
append
remove
split
lower
title
strip
any
isdigit / isupper / islower
return dictionary

When you see a problem, first ask:

Is this a category problem?
Is this a list of numbers problem?
Is this a guessing game?
Is this a list manager?
Is this a validator?

Then use the matching skeleton.

Posted May 13, 2026, 7:26 AM UTC

10
Loading comments…