🍳 Programming in Python: The Simple Recipe Book
Python is just a set of instructions. It's easy because it reads almost like plain English.
I. 🧱 Setting Up Your Workspace
Get the Kitchen (The Interpreter): Download Python. This is the machine that reads your recipe. —There will be a link here with the guide to properly installing python another time.—
Get the Notebook (The Editor): Use a simple text editor or program (I use Zed but, you can use something as simple as notepad). This is where you write the instructions.
II. 📦 Ingredients (Variables and Types)
An Ingredient (Variable) is just a label on a container (box) that holds a piece of information. The Type is what kind of thing is in the box.
Structure
Getty Images
The Box Type | What it Holds | Example (Python Code) |
Number (Whole) | Counting numbers (like 1, 10, -5). |
|
Number (Decimal) | Numbers with a dot (like 3.14, 0.5). |
|
Text (String) | Any words or letters. |
|
True/False (Boolean) | Only holds the concept of YES or NO. |
|
How to Label a Box:
# Create a box labeled 'temperature' and put 25 inside.
temperature = 25
# Create a box labeled 'greeting' and put "Good Morning" inside.
greeting = "Good Morning"
# Look inside a box (Display the value)
print(temperature)
III. ❓ Decisions (The if Recipe Step)
Sometimes your recipe needs to change based on a condition. This is where you use if.
The Rule: If a condition is true, follow the steps written underneath it (indented).
weather = "rainy"
if weather == "rainy":
# IF the condition is true, DO THIS:
print("Take an umbrella.")
elif weather == "sunny": # 'elif' means 'or else if'
# IF the first was false, but THIS one is true, DO THIS:
print("Wear sunglasses.")
else:
# OTHERWISE (if ALL conditions above are false), DO THIS:
print("Just a regular day.")
IV. 🔄 Repetition (The Loop Recipe Step)
If you need to do the same thing many times, you don't write the instruction over and over. You use a Loop.
A. Do this 'X' times (The for Loop)
# Do the following step 3 times
for count in range(3):
print("Stir the mixture.")
# The output will be:
# Stir the mixture.
# Stir the mixture.
# Stir the mixture.
B. Do this WHILE something is true (The while Loop)
energy_level = 10
# Keep doing this instruction AS LONG AS the energy level is greater than 0
while energy_level > 0:
print("The machine is running.")
# Subtract 1 from the energy level each time so it eventually stops
energy_level = energy_level - 1
print("Energy depleted. Machine stopped.")
V. 🗃️ Organized Boxes (Data Structures)
Sometimes you need to store many pieces of related information together in one big, organized container.
A. The List (A Shopping List)
An ordered list where you can add, remove, or change items. (Changeable)
shopping_list = ["Milk", "Eggs", "Bread"] # Change the second item (Lists start counting at 0) shopping_list[1] = "Cheese" print(shopping_list) # Output: ['Milk', 'Cheese', 'Bread']
B. The Dictionary (A Contact Book)
A list of pairs: a Key (the name) and a Value (the number). You look up the value using the key. (Look-up)
info_book = { "Name": "Quantum", "Age": 1000, "Status": "Active" } # Get the value for the "Status" key print(info_book["Status"]) # Output: Active
VI. 🤖 Reusable Instructions (Functions)
A Function is a mini-recipe inside your main recipe. You define it once, then use its name any time you need those same steps.
# 1. DEFINE the mini-recipe
def cook_toast(slices):
"""This function takes slices and prints cooking steps."""
print("Put " + str(slices) + " slices in the toaster.")
print("Press the lever.")
print("Wait for the pop.")
return "Toast is ready."
# 2. USE (CALL) the mini-recipe
result = cook_toast(2)
print(result)
VII. 🗣️ Talking to the Robot (Input and Output)
A program is most useful when it can communicate with the outside world (the user).
A. Output: The print() Function
We already used print() to see the value inside a box. It's how the robot speaks. We can combine text and variables easily using an f-string.
Syntax: Start the string with the letter
fand put the variables you want to display inside curly braces{}.
name = "Robot Alpha"
code_version = 2.1
# The f-string simplifies combining text and variable values
print(f"I am {name}, running on version {code_version}.")
# Output: I am Robot Alpha, running on version 2.1.
B. Input: The input() Function
This is how the robot listens to the user. When input() is called, the program stops and waits for the user to type something and press Enter.
Important Caveat: The
input()function always collects information as a Text (String) type, even if the user types a number. If you need to use the input as a number in a calculation, you must convert it.
# 1. Ask the user a question and store the text result in the 'answer' box
answer = input("How many fuel cells do you need? ")
print(f"You requested the number {answer}.")
# 2. CONVERSION: Change the text to a number (integer)
# This is called 'Type Casting'
num_cells = int(answer)
# Now we can do math with it
cost = num_cells * 10
print(f"The total cost will be ${cost}.")
VIII. 🛠️ Borrowed Tools (Modules and Libraries)
Python is powerful because you don't have to write every instruction yourself. You can borrow pre-written, complex recipe steps (called Modules or Libraries) from others.
Think of a module as a complete set of special kitchen tools (like a mixer or a calculator).
# Example 1: The 'math' tool set
import math
# Use a specific tool from the math set (the sqrt tool for square roots)
result = math.sqrt(25)
print(f"The square root of 25 is: {result}") # Output: 5.0
# Example 2: The 'random' tool set
import random
# Use the tool to pick a random integer between 1 and 6 (inclusive)
dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}.")
IX. 💥 Kitchen Disasters (Error Handling)
What happens if your robot tries to do something impossible, like dividing a number by the number zero? The program will crash and stop its instruction flow. This is an Exception or Error.
To prevent a crash, we wrap the risky part of the recipe in a safety block: the try...except structure.
try: "TRY to run this part of the code."except: "If thetryblock fails (a disaster occurs), jump here and run this recovery code instead."
try:
# 1. TRY to get a number from the user
num1_text = input("Enter the first number: ")
num2_text = input("Enter the second number: ")
# 2. TRY to convert and divide (This is the risky step)
a = int(num1_text)
b = int(num2_text)
# If the user enters '0' for the second number, this will cause a crash
result = a / b
print(f"The result of the division is: {result}")
# 3. If an error (a 'ZeroDivisionError' specifically) occurs, the code skips to here
except ZeroDivisionError:
print("WARNING: You cannot divide by zero. Please retry the calculation.")
# 4. We can catch other errors, like trying to convert 'hello' into a number
except ValueError:
print("WARNING: You must enter valid numbers (like 5 or 10), not text.")
print("Program continues smoothly.")

