This study material has been compiled from various sources, including lecture transcripts and provided text documents, to offer a comprehensive overview of Python programming concepts related to variables, lists, and program design.
Python Programming: Variables, Lists, and Program Design
📚 Introduction
This study guide provides a detailed explanation of fundamental Python programming concepts: variables, lists, and how to write more effective programs using these structures. We will explore these topics through practical examples, including a case study of "Tech Co.", a design company that creates and sells computer devices in various colors. The goal is to learn how to store product information, particularly coordinated colors, using Python.
1. 📖 Understanding Variables
1.1. 📚 What is a Variable?
A variable is a named area in computer memory used for storage. ✅ It stores a single value or piece of data. 💡 The name of a variable should clearly indicate the value it holds to improve code readability.
1.2. 📊 Stages of Variable Involvement
Variables are crucial throughout a program's lifecycle:
- Input: Receiving data from the user or another source.
- Example Code:
colour = input("enter a colour: ")
- Example Code:
- Processing: Modifying or manipulating the stored data.
- Example Code:
colour = colour + "dark"(This example from the source is a bit misleading for string concatenation, but it illustrates modification.)
- Example Code:
- Output: Displaying the stored data.
- Example Code:
print(colour)
- Example Code:
1.3. ✅ Key Variable Operations
- Assignment: The equals sign (
=) is used to assign a value to a variable.my_variable = "hello"
- Output: The
print()command displays the value of a variable.print(my_variable)
1.4. 💡 Prior Knowledge (Spiral Back)
You should recall writing Python programs from previous studies, including the use of variables, for loops, and while loops. These skills will be applied in this unit.
2. 📝 Working with Lists
2.1. 📚 What is a List?
A list is a special type of variable that can store multiple different data values. ✅ It's a much more efficient way to store collections of data compared to creating a separate variable for each item.
2.2. 🛠️ Creating and Printing Lists
- Creation: Lists are defined using square brackets
[], with items separated by commas.- Example Code:
colourlist = ["red", "yellow", "blue", "green"] - Longer lists can span multiple lines for readability.
- Example Code:
- Printing the Whole List: The
print()command will output the entire list, including square brackets, quotation marks, and commas.- Example Code:
print(colourlist)
- Example Code:
2.3. ➕ Appending to a List
append()command: This command adds a value to the end of a list, making the list longer.- Example Code:
colourlist.append("orange")
- Example Code:
- User Input for Appending: Programs often take input from the user and append it to a list.
- Example Code:
colour = input("enter a colour: ") colourlist.append(colour)
- Example Code:
2.4. 💬 Comments in Code
- Purpose: Comments are notes within the code that are ignored by the computer but are helpful for programmers to understand the code.
- Syntax: Comment lines begin with a hash symbol (
#).- Example Code:
# make the list colourlist = ["red", "yellow", "blue", "green"] # append one value to the list colour = input("enter a colour: ") colourlist.append(colour) # output the list print(colourlist) # Note: The source had print(colour) here, which is an error. Corrected to print(colourlist).
- Example Code:
3. 🔄 Appending Items Using Loops
When you need to add multiple items to a list, loops are essential. Python offers two main types of loops.
3.1. 🔁 for Loop (Counter Loop)
- Control: A
forloop is controlled by a counter. You set the exact number of times the loop will repeat. - Use Case: Ideal when you know precisely how many items you want to add to a list.
- Example: Adding exactly seven values to
colourlist.
💡 Tip: You can search for "colour names" online for ideas.# make the list colourlist = ["red", "yellow", "blue", "green"] for i in range(7): # Loop will repeat 7 times colour = input("enter a colour: ") colourlist.append(colour) # output the list (after the loop) print(colourlist)
3.2. 🔄 while Loop (Conditional Loop)
- Control: A
whileloop is controlled by a logical test (a condition). The loop continues as long as the condition isTrueand stops when it becomesFalse. - Use Case: Ideal when you don't know exactly how many items you want to add.
- Key Principles for
whileloops:- Initialize the control variable: The variable used in the logical test must be set before the loop starts so it can begin.
- Change the control variable: There must be a way to change the variable's value inside the loop, otherwise, it could become an infinite loop.
- Example with
repeatvariable:# make the list colourlist = ["red", "yellow", "blue", "green"] # append values using a while loop repeat = "y" # 1️⃣ Initialize control variable while repeat == "y": # 2️⃣ Logical test colour = input("enter a colour: ") colourlist.append(colour) repeat = input("Do you want to add another? (Y/N) ") # 3️⃣ Change control variable # output the list (after the loop) print(colourlist) - Alternative
whileloop with!=(not equal to): You can use the relational operator!=(not equal to) to control the loop.
💡 This version is often more user-friendly as the user explicitly decides when to stop.colour = "" # Initialize colour colourlist = ["red", "yellow", "blue", "green"] while colour != "STOP": # Loop continues until user types "STOP" colour = input("enter a colour (type STOP to finish): ") if colour != "STOP": # Only append if not "STOP" colourlist.append(colour) print(colourlist)
4. 📍 Accessing List Items by Index
4.1. 📚 Index Numbers
- Each item in a list has its own unique identifier, which is its index number.
- Numbering starts at 0.
- For
colourlist = ["red", "yellow", "blue", "green"]:colourlist[0]is "red"colourlist[1]is "yellow"colourlist[2]is "blue"colourlist[3]is "green"
- For
- To access a single item, use the list's name followed by the index number in square brackets:
list_name[index_number].
4.2. 🖨️ Printing a Single Item
- Example Code:
colourlist = ["red", "yellow", "blue", "green"] i = input("which colour do you want to see? (enter a number): ") i = int(i) # Convert input to an integer print(colourlist[i])- Output Example:
which colour do you want to see? 2 blue
- Output Example:
4.3. ⚠️ Out of Bounds Error (Run-time Error)
- Problem: If a user enters an index number that is too large (or negative, though not covered here), the program will crash.
- Error Message:
IndexError: list index out of range - Definition: This is a run-time error because the code itself is syntactically correct, but the program is asked to do something impossible during execution (access a non-existent item).
- Out of Bounds Error: Specifically refers to using an index number that falls outside the valid range of a list's indices.
4.4. 📏 Finding the Length of a List (len())
- Function: Python's built-in
len()function returns the number of items in a list. - Use Case: Crucial for preventing out of bounds errors.
- Example Code:
listlength = len(colourlist) print(listlength) # If colourlist has 4 items, this prints 4
4.5. 🛡️ Preventing Out of Bounds Errors (Robust Programs)
To make programs more robust (meaning they don't crash even with bad input) and user-friendly, we can implement checks:
- User Message: Inform the user about the valid range of index numbers.
- Example Code:
listlength = len(colourlist) print("type a number from 0 to", listlength - 1) # Max index is length - 1
- Example Code:
- Validation Check (
if...else): Use anifstructure to check if the input index is valid before attempting to access the list item.- Definition: A validation check blocks bad inputs.
- Example Code:
listlength = len(colourlist) i = int(input("which colour do you want to see? ")) if i < listlength and i >= 0: # Check if index is within valid range print(colourlist[i]) else: print("that number is too big or too small") # Or "invalid index"
4.6. 🖨️ Printing All Items with a for Loop
You can use a for loop to iterate through every item in a list and print each one.
- Example Code:
# output the whole list listlength = len(colourlist) for i in range(listlength): # range(listlength) generates numbers from 0 to listlength-1 print(i, colourlist[i])- Output Example:
0 red 1 yellow 2 blue 3 green
- Output Example:
5. ✏️ Editing, Removing, and Sorting List Items
Designers often need to review and modify their lists. A program with a menu interface makes these operations user-friendly.
5.1. 🖥️ Program Interface and Menus
- Interface: The part of the program that makes it easy for the user to interact with it.
- Menu: A common interface element that presents options to the user.
- Example Menu Options:
A: ADDR: REMOVEP: PRINTS: SORTX: EXIT
- Empty Line Command:
print("\n")creates a blank line for better readability in the output.
5.2. ➕ Appending a Value (Recap)
If the user chooses 'A' (Add), the program should prompt for a new item and append it.
- Code:
name = input("type the new colour: ") colourlist.append(name) print(name, "has been added")
5.3. ➖ Removing a Value (remove())
If the user chooses 'R' (Remove), the program should ask which item to remove.
- Command: The
remove()method removes the first occurrence of a specified value from the list. - Code:
⚠️ Caution: If the specified item is not in the list,name = input("which colour do you want to remove? ") colourlist.remove(name) print(name, "has been removed")remove()will cause aValueError.
5.4. 🔠 Sorting a List (sort())
If the user chooses 'S' (Sort), the list items will be put in order.
- Command: The
sort()method sorts the list in-place (modifies the original list).- For strings, it sorts alphabetically.
- For numbers, it sorts numerically.
- Code:
💡 No user input is needed for this command; it acts directly on the list.colourlist.sort()
5.5. 🗑️ Alternative Removal: del with Index
Instead of removing an item by its value, you can remove it by its index number using the del keyword.
- Command:
del list_name[index_number] - Code:
⚠️ Warning: This method is also susceptible to out of bounds errors if an invalid index is provided. Robust programs should include validation checks (as discussed in section 4.5).i = input("which item number do you want to delete? ") i = int(i) del colourlist[i]
6. 🐞 Debugging and Enhancing User Experience
This section focuses on identifying and fixing program errors, and improving the overall user experience.
6.1. 📚 Introduction to Debugging
- Case Study: Rio's To-Do List program, which he wants to create and display.
- Debugging: The process of finding and fixing errors (bugs) in a program.
6.2. ❌ Types of Errors
-
Syntax Errors:
- Definition: Mistakes that break the rules of the programming language (its syntax).
- Detection: Python's interpreter will usually catch these errors and provide an error message that points to the location of the mistake.
- Example: Missing a closing bracket
)in aprint()statement.print ("T O - DO LIST"(Incorrect)print ("T O - DO LIST")(Correct)
-
Run-time Errors:
- Definition: Errors that occur while the program is running, even if the syntax is correct.
- Detection: The program crashes during execution.
- Example:
NameError: name 'choice' is not defined- Cause: Trying to use a variable (e.g.,
choice) in a logical test (like awhileloop condition) before it has been assigned any value. - Fix: Initialize the variable with a default value before the loop starts.
choice = "" # Initialize choice with an empty string while choice != "X": # ... rest of the loop
- Cause: Trying to use a variable (e.g.,
-
Logical Errors:
- Definition: Errors where the program runs without crashing, but it doesn't do what the programmer intended. These are often the hardest to find.
- Detection: The program produces incorrect output or behaves unexpectedly.
- Examples from Rio's program:
- Incorrect Loop Condition:
- Problem:
while choice == "X":(Loop repeats if choice is 'X'). This causes the program to exit immediately if 'X' is not the initial choice. - Fix: Change to
while choice != "X":(Loop repeats as long as choice is not 'X').
- Problem:
- List Initialization Inside Loop:
- Problem:
todolist = [](creating an empty list) is placed inside thewhileloop. This means the list is reset to empty with each iteration, and items added previously are lost. - Fix: Move
todolist = []to the very beginning of the program, before thewhileloop, so it's initialized only once.
- Problem:
- Incorrect Loop Condition:
6.3. ✨ Improving User Experience (UX)
After fixing errors, focus on making the program more user-friendly.
-
Formatted Output for Lists:
- Goal: Display the list with a title, each item on a new line, and numbered.
- Original Output:
['Maths homework', 'Visit cousin's new baby', ...] - Desired Output:
TO-DO LIST 1 Maths homework 2 Visit cousin's new baby ... - Implementation:
- Copy title
print()commands to the 'Print' section. - Use a
forloop to print items one by one, along with their index.
💡 Note: If you change the display to 1-based numbering (print("========") print("TO-DO LIST") print("========") listlength = len(todolist) for i in range(listlength): print(i + 1, todolist[i]) # Print (index + 1) for 1-based numberingi + 1), remember that internal list indexing remains 0-based. This might require adjustments in other parts of the code (e.g., when deleting by number).
- Copy title
-
Removing Items by Number vs. Name:
- Removing by Name (
remove()):- Code:
item = input("item to remove: ") todolist.remove(item) - Disadvantages: Requires exact typing, prone to
ValueErrorif item not found.
- Code:
- Removing by Number (
delwith index):- Code:
i = input("which number do you want to delete? ") i = int(i) del todolist[i] - Advantages: Easier for the user (less typing, less chance of typos).
- ⚠️ Warning: Still susceptible to out of bounds errors. Implement validation checks (as in section 4.5) to make it robust.
i = int(input("which number do you want to delete? ")) # Adjust for 1-based display if applicable, convert back to 0-based for del actual_index = i - 1 if actual_index >= 0 and actual_index < len(todolist): del todolist[actual_index] else: print("number too big or invalid")
- Code:
- Removing by Name (
-
Creative Interface Design:
- Even with simple text output, you can use
print()commands to create visually appealing text-art titles or menu layouts to enhance the user experience.
- Even with simple text output, you can use
🔑 Key Concepts
- 📚 Variable: Named storage area for a single value.
- 📚 List: Special variable storing multiple data values.
- ✅
=(Assignment): Assigns a value to a variable. - ✅
print(): Outputs values to the console. - ✅
append(): Adds an item to the end of a list. - ✅
remove(): Removes the first occurrence of a specified value from a list. - ✅
sort(): Sorts the items in a list (in-place). - ✅
del: Deletes an item from a list by its index. - 📚 Comment: Non-executable notes in code, starting with
#. - 📚
forloop: Counter-controlled loop, repeats a set number of times. - 📚
whileloop: Condition-controlled loop, repeats as long as a condition is true. - ✅
!=(Not Equal To): Relational operator. - 📚 Index Number: Position of an item in a list, starting from 0.
- 📚
len(): Function to get the number of items in a list. - ⚠️ Out of Bounds Error: Attempting to access a list item using an invalid index.
- 📚 Run-time Error: Error occurring during program execution.
- 📚 Robust Program: A program that does not crash due to bad user input.
- 📚 User-friendly: Easy for the user to understand and interact with.
- 📚 Validation Check: Code that blocks bad inputs.
- 📚 Interface: The part of a program that allows user interaction.
- 📚 Syntax Error: Error breaking the rules of the programming language.
- 📚 Logical Error: Program runs but produces incorrect or unintended results.
🧠 Practice Questions
Section 1 & 2 Review
- List Items:
- Given
trees = ["oak", "beech", "willow"]:- How many items are in this list?
- What is the value of item 0?
- Write the command to print item 2 of the list.
- Given
- Appending: Write the command to append the value "pine" to the
treeslist. - User Input & Append: Write the commands to get user input and add it to the
treeslist. - Error Analysis: The user entered
print(trees[6]). This command caused an error. Explain why. - Error Prevention: Describe one way you could avoid the error in question 4.
- Loop Choice: You want the user to add multiple items to the list, but you are not sure how many items. What type of loop would you use?
Section 3 Review
- List Type: Given
trees = ["oak", "beech", "willow", "pine", "apple"], are these items strings, integers, or Boolean? - Sorted Order: If the
treeslist was sorted, which item would come first? - Deletion: Write the command to delete "willow" from the
treeslist. - List Length Output: Write a command, or commands, to print the length of the
treeslist as a number value.
Section 4 Review
- Loop Control: A programmer made a menu interface inside a
whileloop. The first line of thewhileloop iswhile more == "y":.- What is the name of the variable used in this command?
- What value could the user input to make the loop continue?
- Give an example of a line you would include before the loop, to set the value of the variable.
- Give an example of a line you would include inside the loop, that lets the user stop the loop.
- Menu Interaction: Consider the following menu code snippet:
colourlist = ["red", "yellow", "blue", "green"] choice = "" while choice != "z": print("A: Add a new colour to the list") print("B: Print the colour list") # ... other options choice = input("input your choice: ") if choice == "A": new = input("Type a new colour: ") colourlist.append(new) elif choice == "B": print(colourlist) # ... other if/elif- What choice should the user enter in order to print the list?
- The user types 'A'. What do they see next?
- What happens if the user types 'C' (assuming 'C' is not defined in the snippet)?
- What choice will stop the loop?
🚀 Stretch Zone Challenges
- Delete by Index (Advanced): Add a new menu option to your
colourlistprogram called "Delete by Index". Implement thedelcommand to remove an item by its index number. Remember to include validation checks to prevent out of bounds errors. - Sort To-Do List: Add an extra menu option to Rio's to-do list program to allow the user to sort the list alphabetically. Ensure the code works properly.
- 1-Based Numbering: In the to-do list program, modify the print output so that items are numbered starting from 1 instead of 0. Then, adjust the "remove by number" functionality to correctly handle this 1-based display while still using 0-based internal indexing for deletion.
- Alternative Interface: Create a new version of the to-do list program with a different user interface style, where the to-do list is displayed first, followed by the menu options.
- Text-Art Title: Design and create an interesting text-art title for your program using only Python
print()commands.








