Unit 6: Data Structures – Storing Multiple Items

Overview

So far, you’ve learned to work with single values like numbers or strings. But in real-world tasks, you often deal with collections of items:

       •      A list of student names

       •      A dictionary of countries and their capitals

       •      A set of unique user IDs

This is where data structures come in. They help you group, store, and organize multiple values efficiently.

1. Lists – Ordered, Changeable Collections

Analogy:

A list is like a shopping basket. Each item has a specific order, and you can add, remove, or change things as needed.

Creating a List

fruits = [“apple”, “banana”, “cherry”]

Accessing Items by Index

print(fruits[0])  # Output: apple

print(fruits[2])  # Output: cherry

Modifying an Item

fruits[1] = “orange”

print(fruits)  # Output: [‘apple’, ‘orange’, ‘cherry’]

Adding Items

fruits.append(“grape”)  # Adds to the end

fruits.insert(1, “kiwi”)  # Inserts at index 1

print(fruits)  # [‘apple’, ‘kiwi’, ‘orange’, ‘cherry’, ‘grape’]

Removing Items

fruits.remove(“orange”)

print(fruits)  # [‘apple’, ‘kiwi’, ‘cherry’, ‘grape’]

fruits.pop()  # Removes the last item

print(fruits)

Looping Through a List

for fruit in fruits:

    print(“I like”, fruit)

2. Tuples – Ordered, Immutable Collections

Analogy:

A tuple is like a locked briefcase. You know what’s inside, and the order matters, but you can’t change the contents once it’s packed.

Creating a Tuple

dimensions = (1920, 1080)

Accessing Items

print(dimensions[0])  # Output: 1920

Why Use Tuples?

       •      Safer when you don’t want values to be changed accidentally

       •      Often used for fixed collections (like coordinates or screen sizes)

3. Dictionaries – Key-Value Pairs

Analogy:

A dictionary is like a real-world dictionary: you look up a word (key) to find its definition (value).

Creating a Dictionary

capitals = {

    “France”: “Paris”,

    “Japan”: “Tokyo”,

    “India”: “New Delhi”

}

Accessing Values

print(capitals[“Japan”])  # Output: Tokyo

Adding or Changing Values

capitals[“Germany”] = “Berlin”

capitals[“India”] = “Delhi”  # Update

Removing Entries

del capitals[“France”]

Looping Through a Dictionary

for country, city in capitals.items():

    print(country, “→”, city)

4. Sets – Unordered, Unique Items

Analogy:

A set is like a collection of club members: each person is unique, and the order doesn’t matter.

Creating a Set

unique_numbers = {1, 2, 3, 3, 4}

print(unique_numbers)  # Output: {1, 2, 3, 4}

Explanation: Sets automatically remove duplicates.

Adding and Removing Items

unique_numbers.add(5)

unique_numbers.discard(2)

Why Use Sets?

       •      To remove duplicates

       •      For fast membership testing (checking if an item exists)

5. Summary Table

Type       Ordered Changeable  Duplicate Allowed       Syntax

List  Yes  Yes  Yes  []

Tuple     Yes  No  Yes  ()

Dict Keys: No Yes  Keys: No {}

Set  No  Yes  No  {}

6. Real-Life Example: Student Grades System

Let’s combine data structures into a simple application:

# Dictionary of students and their grades

grades = {

    “Alice”: [90, 85, 88],

    “Bob”: [78, 81, 74],

    “Charlie”: [92, 90, 95]

}

# Print average grade for each student

for student, marks in grades.items():

    average = sum(marks) / len(marks)

    print(student, “Average Grade:”, average)

Output:

Alice Average Grade: 87.666…

Bob Average Grade: 77.666…

Charlie Average Grade: 92.333…

Conclusion

In this unit, you learned how to use data structures to store and organize multiple values:

       •      Lists: Ordered, editable sequences

       •      Tuples: Ordered, unchangeable collections

       •      Dictionaries: Key-value lookups

       •      Sets: Unordered collections with unique items

These tools help you manage real-world data in Python and prepare you for more advanced programming tasks like databases, APIs, and algorithms.

Unit 5: Functions – Breaking Down Code

Overview

As your programs grow, writing the same logic repeatedly becomes messy and inefficient. Functions solve this by letting you write a block of code once, give it a name, and reuse it anytime.

Analogy:

Think of a function like a blender in your kitchen. You put in ingredients (inputs), press a button (call the function), and it gives you a smoothie (output). Once it’s built, you can reuse it whenever you want, with different ingredients.

1. What Are Functions?

A function is a named block of code that performs a specific task.

Why Use Functions?

       •      Avoid repetition: Write once, use many times

       •      Make code modular: Easier to understand and maintain

       •      Simplify debugging: Isolate and test specific parts of your code

2. Defining Functions

Syntax:

def function_name(parameters):

    # code block

       •      def: Tells Python you’re defining a function

       •      function_name: A name you choose (just like a variable)

       •      parameters: Values the function will use (like ingredients)

       •      The function body is indented

Basic Example:

def greet():

    print(“Hello, world!”)

Calling a Function:

greet()

greet()

Output:

Hello, world!

Hello, world!

The function is defined once but can be reused any number of times.

3. Functions with Parameters

Functions become more useful when you give them inputs (called parameters). These are like ingredients going into the blender.

Example:

def greet(name):

    print(“Hello,”, name + “!”)

Calling It:

greet(“Alice”)

greet(“Bob”)

Output:

Hello, Alice!

Hello, Bob!

You’re passing a value (“Alice” or “Bob”) into the name parameter.

4. Return Values

Some functions don’t just print—they return a value. Think of this as getting a result back from a math calculation.

Syntax:

def add(a, b):

    return a + b

Using the Return Value:

result = add(3, 4)

print(“The sum is”, result)

Output:

The sum is 7

Here, add(3, 4) evaluates to 7, and we store it in result.

5. Multiple Parameters and Multiple Calls

You can define functions with more than one parameter and call them multiple times with different arguments.

Example:

def describe_pet(animal, name):

    print(“I have a”, animal + ” named”, name)

Calling It:

describe_pet(“dog”, “Rover”)

describe_pet(“cat”, “Whiskers”)

Output:

I have a dog named Rover

I have a cat named Whiskers

6. Local vs Global Variables

Local Variables: Exist only inside the function

Global Variables: Exist everywhere in the program

Example:

name = “Global”

def show_name():

    name = “Local”

    print(“Inside function:”, name)

show_name()

print(“Outside function:”, name)

Output:

Inside function: Local 

Outside function: Global

The variable name inside the function doesn’t affect the global name.

7. Real-Life Example: Temperature Converter

Let’s use a function to convert Celsius to Fahrenheit:

def celsius_to_fahrenheit(celsius):

    fahrenheit = (celsius * 9/5) + 32

    return fahrenheit

print(celsius_to_fahrenheit(0))    # 32.0

print(celsius_to_fahrenheit(100))  # 212.0

This function is reusable for any temperature and avoids writing the formula over and over.

8. Optional Parameters (Default Values)

You can give parameters default values, so users don’t have to supply them.

def greet(name=”friend”):

    print(“Hello,”, name + “!”)

greet(“Alice”)  # Output: Hello, Alice!

greet()         # Output: Hello, friend!

If no name is provided, it uses “friend” as the default.

Conclusion

In this unit, you learned how to create and use functions, which help make your code:

       •      Reusable (write once, use many times)

       •      Modular (each function does one job)

       •      Readable (clear structure and purpose)

You now know how to:

       •      Define a function with def

       •      Pass in parameters (inputs)

       •      Return values (outputs)

       •      Use local and global variables

       •      Build default arguments for flexibility

In the next unit, we’ll dive into Data Structures—you’ll learn how to store and organize many values at once using lists, dictionaries, and more.

Unit 4: Loops – Repeating Tasks in Python

Unit 4: Loops – Repeating Tasks in Python

Overview

Imagine you have to write “I will practice Python” 100 times. You could copy-paste the line 100 times… or you could tell Python:

“Repeat this line 100 times.”

That’s what loops are for—automating repetition in your code.

Python provides two main types of loops:

       •      for loops: Best for repeating over a known sequence (like a list or a range of numbers)

       •      while loops: Best when you want to repeat something until a condition changes

1. For Loops: Iterating Over a Sequence

Analogy:

Think of a for loop like going through a playlist. You hit play, and the player goes through each song, one by one.

Syntax:

for item in sequence:

    # do something with item

Looping Over a List

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

    print(“I like”, fruit)

Output:

I like apple 

I like banana 

I like cherry

Each time through the loop, fruit holds the next item from the list.

Using range() to Loop a Specific Number of Times

The range() function gives you a sequence of numbers.

for i in range(5):

    print(“Number:”, i)

Output:

Number: 0 

Number: 1 

Number: 2 

Number: 3 

Number: 4

Explanation:

range(5) gives numbers from 0 to 4. It starts at 0 by default and stops before 5.

Using range(start, stop, step)

for i in range(1, 10, 2):

    print(i)

Output:

9

This starts at 1, stops before 10, and increases by 2 each time.

2. While Loops: Repeat Until a Condition is False

Analogy:

A while loop is like a light with a motion sensor: it stays on while it detects movement. As soon as the condition stops being true, the loop ends.

Syntax:

while condition:

    # repeat this block

Simple Example:

count = 0

while count < 5:

    print(“Count is:”, count)

    count += 1

Output:

Count is: 0 

Count is: 1 

Count is: 2 

Count is: 3 

Count is: 4

Explanation:

As long as count < 5, the loop continues. The count += 1 increases the number by 1 each time.

3. Breaking Out of Loops

Sometimes, you want to exit a loop early, even if the loop’s condition is still true.

Using break: Exit Immediately

for i in range(10):

    if i == 3:

        break

    print(i)

Output:

2

Explanation:

As soon as i reaches 3, the loop stops completely.

4. Skipping an Iteration

Using continue: Skip This Turn

for i in range(5):

    if i == 2:

        continue

    print(i)

Output:

4

Explanation:

When i == 2, Python skips the print(i) and jumps to the next iteration.

5. Real-Life Example: Password Checker

correct_password = “python123”

attempt = “”

while attempt != correct_password:

    attempt = input(“Enter password: “)

print(“Access granted!”)

Explanation:

The loop keeps asking for the password until the user types “python123”. Once the input matches, the loop ends and “Access granted!” is printed.

6. Nested Loops: Loops Inside Loops

Example: Multiplication Table

for i in range(1, 4):

    for j in range(1, 4):

        print(i * j, end=” “)

    print()  # Line break

Output:

1 2 3 

2 4 6 

3 6 9

Explanation:

The outer loop runs for each row. The inner loop runs for each column. You get a 3×3 multiplication table.

Conclusion

In this unit, you learned how to repeat tasks using loops:

       •      for loops: Use when looping over items or a known range

       •      while loops: Use when repeating until a condition changes

       •      break and continue: Control the loop flow

       •      range(): Useful for counting or creating number sequences

       •      Nested loops: Use when looping within loops (e.g. tables, grids)

These tools let your programs automate work—no need for copy-paste repetition!

Next up: Unit 5 – Functions: Breaking Down Code. You’ll learn how to organize your programs into reusable, modular blocks. Let’s keep going!

Unit 3: Control Flow – Decision Making in Python

Overview

In real life, we make decisions constantly:

       •      If it’s raining, we bring an umbrella.

       •      If we’re hungry, we eat.

Python lets you do the same thing in your code using control flow tools like if, elif, and else. These help your program make decisions and choose different paths depending on the data it sees.

1. Conditional Statements: if, elif, else

What is a condition?

A condition is something that evaluates to True or False. Python uses these conditions to decide which block of code to run.

The if Statement

Think of if as a traffic signal:

       •      If the light is green, go.

       •      If not, do nothing.

Syntax:

if condition:

    # do something

Example:

temperature = 35

if temperature > 30:

    print(“It’s a hot day!”)

Explanation:

       •      Python checks if temperature > 30. Since it’s True, it prints the message.

       •      If it were 25, the condition would be False, and nothing would print.

The else Statement

else is like the “default” choice.

“If the condition is not true, do this instead.”

Example:

temperature = 20

if temperature > 30:

    print(“It’s a hot day!”)

else:

    print(“It’s not that hot.”)

Output:

It’s not that hot.

The elif Statement

What if you have multiple conditions to check?

That’s where elif (short for “else if”) comes in.

Analogy:

Think of getting dressed:

       •      If it’s cold → wear a coat.

       •      Else if it’s raining → bring an umbrella.

       •      Else → wear regular clothes.

Example:

temperature = 15

if temperature > 30:

    print(“It’s a hot day!”)

elif temperature > 20:

    print(“It’s a nice day!”)

else:

    print(“It’s cold!”)

Output:

It’s cold!

How it works:

       •      Python checks the first condition: temperature > 30 → False.

       •      Then checks temperature > 20 → False.

       •      Goes to else and prints “It’s cold!”

2. Boolean Expressions: Comparing Values

What is a Boolean?

A Boolean is a value that can be True or False.

Comparison Operators

Operator       Meaning Example

==  Equal to 5 == 5 → True

!=    Not equal to 3 != 4 → True

>     Greater than 7 > 4 → True

<     Less than       2 < 9 → True

>=  Greater than or equal to    5 >= 5 → True

<=  Less than or equal to  6 <= 8 → True

Example:

score = 85

if score >= 90:

    print(“Grade: A”)

elif score >= 80:

    print(“Grade: B”)

else:

    print(“Grade: C or lower”)

Output:

Grade: B

3. Combining Conditions: and, or, not

You can combine multiple conditions using logical operators:

Logical Operators

Operator       Description   Example

and Both conditions must be True   x > 5 and x < 10

or    At least one condition must be True       x < 5 or x > 10

not  Reverses a condition   not True → False

Example with and:

age = 25

if age > 18 and age < 65:

    print(“You are an adult.”)

Output:

You are an adult.

Explanation:

Both conditions (age > 18 and age < 65) are True, so the message is printed.

Example with or:

day = “Saturday”

if day == “Saturday” or day == “Sunday”:

    print(“It’s the weekend!”)

Output:

It’s the weekend!

Example with not:

is_tired = False

if not is_tired:

    print(“Let’s get to work!”)

Output:

Let’s get to work!

4. Real-Life Example: Activity Planner

Let’s put everything together into a practical program.

temperature = 22

is_raining = False

if temperature > 25 and not is_raining:

    print(“Go to the beach!”)

elif temperature > 15 and not is_raining:

    print(“Go for a walk.”)

elif is_raining:

    print(“Stay indoors and read a book.”)

else:

    print(“Wear a jacket and go outside.”)

Output:

Go for a walk.

Conclusion

In this unit, you learned how to control the flow of your Python programs with decision-making tools:

       •      if, elif, else to create branching paths in your code

       •      Boolean logic (True, False) to test conditions

       •      Logical operators (and, or, not) to combine conditions

These tools are the foundation of all smart programs—from calculators to games to AI decision engines. Next up, we’ll explore loops, which help you repeat tasks automatically.

Ready for Unit 4: Loops – Repeating Tasks? Let’s keep going!

Unit 2: Basic Syntax and Variables

Overview

Now that you have Python installed and understand how to run code, it’s time to explore Python’s syntax (the rules for writing Python code) and variables (used to store information).

Python is known for its clean and readable syntax. Unlike other programming languages, it does not require semicolons (;) at the end of statements or curly braces ({}) to define blocks of code. Instead, Python relies on indentation (spaces or tabs) to structure code properly.

1. Understanding Python Syntax

Indentation: The Structure of Python Code

In many programming languages, blocks of code are enclosed in curly brackets {}. However, in Python, indentation (spaces or tabs at the beginning of a line) determines the structure of the program.

✅ Tip: Always be consistent with indentation. The standard convention is 4 spaces per indentation level.

Comments: Writing Notes in Your Code

Comments are lines of text in your code that Python ignores. They are useful for explaining what your code does.

       •      Single-line comment: Starts with #

       •      Multi-line comment: Enclosed in triple quotes ”’ or “””

2. Variables and Data Types

What Are Variables?

A variable is a name that stores a value. You can think of it as a box that holds data, which can be changed later.

📌 Rules for Naming Variables:

✔️ Must start with a letter or underscore _

✔️ Can contain letters, numbers, and underscores

❌ Cannot start with a number (1name is invalid)

❌ Cannot use Python keywords (e.g., if, else, print)

3. Data Types in Python

Python has several built-in data types, including:

Data Type     Example

String (str)     “Hello”

Integer (int)   42

Float (float)   3.14

Boolean (bool)     True, False

4. Basic Operators in Python

Operators in Python allow us to perform operations on variables and values.

Arithmetic Operators (Used for mathematical calculations)

Operator       Description   Example

+     Addition 5 + 3  → 8

–     Subtraction   10 – 2  → 8

*      Multiplication       4 * 3  → 12

/      Division  8 / 2  → 4.0

//    Floor Division       9 // 2  → 4

%     Modulus (Remainder) 10 % 3  → 1

**    Exponentiation    2 ** 3  → 8

Comparison Operators (Used for comparing values)

Operator       Meaning Example

==  Equal to 5 == 5 → True

!=    Not equal to 5 != 3 → True

>     Greater than 10 > 5 → True

<     Less than       3 < 8 → True

>=  Greater than or equal to    5 >= 5 → True

<=  Less than or equal to  7 <= 10 → True

5. Writing and Using Variables in Code

Let’s combine what we’ve learned to create a simple Python program.

📌 Explanation:

       •      We create variables for name, age, and is_student.

       •      We use print() to display their values.

       •      We calculate birth_year using subtraction.

Conclusion

In this unit, you learned about:

       •      Python syntax (indentation, comments)

       •      Variables (naming rules, assigning values)

       •      Data types (str, int, float, bool)

       •      Basic operators (arithmetic and comparison)

       •      Writing simple Python programs using variables

Now that you understand variables and data types, you’re ready to start making decisions in Python with if statements, which we’ll cover in Unit 3: Control Flow! 🚀

Tutorial Articles U1

Unit 1: Introduction to Python

What is Python?

Python is a high-level, easy-to-read programming language that allows you to write code in a simple and straightforward way. It’s popular for its clean syntax and versatility, making it ideal for beginners and experts alike. Python is used in web development, data science, automation, machine learning, and more.

Why Python is Great for Beginners

       1.    Readable and Simple Syntax:

Python’s syntax closely resembles the English language, making it easier to understand. It doesn’t require punctuation like semicolons or curly braces, which are common in other languages. Instead, Python uses indentation to organize code.

       2.    Versatility:

Python is used in a wide range of fields:

       •      Web Development (e.g., Django, Flask)

       •      Data Science (e.g., pandas, NumPy)

       •      Machine Learning (e.g., TensorFlow, scikit-learn)

       •      Automation (e.g., scripts to automate repetitive tasks)

       3.    Large Community:

Python has a huge community of developers. This means you’ll always find resources, tutorials, and forums to help you solve problems and improve your skills.

Setting Up Python

       1.    Installing Python:

       •      Go to python.org, download the installer for your operating system, and run it.

       •      Ensure to check the box to “Add Python to PATH” during installation. This allows you to run Python from the command line.

       •      After installation, open the terminal and type python –version to check if it installed correctly.

       2.    Choosing a Text Editor or IDE:

You can use any text editor to write Python code, but an IDE like VS Code, PyCharm, or Jupyter Notebook makes it easier to write, debug, and test your programs.

Basic Python Syntax

1.    Printing Output:

The print() function displays text or data on the screen.

2.    Variables:

Variables are used to store data. You can assign values to variables using the = sign.

3.    Data Types:

       •      Strings: Text wrapped in quotes (“Hello”).

       •      Integers: Whole numbers (10).

       •      Floats: Numbers with decimals (3.14).

       •      Booleans: True or False values.

 4.    Basic Arithmetic:

Python allows you to perform arithmetic operations like addition, subtraction, multiplication, and division.

Control Flow

 1.    If Statements:

Use if to make decisions. You can also use elif (else if) and else to check multiple conditions.

2.    Loops:

       •      For Loops: Iterates over a sequence (like a list).