SECTION 1: GETTING STARTED
Welcome to your journey into computer programming! In this section, you'll learn the basics of setting up your development environment and writing your very first program. We'll be using Python, a popular programming language, and EasyGui, a module that makes creating simple graphical interfaces easy and fun.
What You Will Learn:
- Installing Python
- Preparing EasyGui
- Producing output
1.1 Installing Python and EasyGui
Installing Python
For this course, you are going to create computer programs using Python and EasyGui. Python is a powerful programming language used by companies like Google, YouTube, Meta, and Netflix. EasyGui is a module that simplifies creating GUIs (Graphical User Interfaces), making your programs more user-friendly with buttons, textboxes, and other visual elements.
First, let's check if you have Python installed on your computer:
- Press the Windows key on your keyboard and type 'Python'.
- Look for an app named IDLE (Python 3.11 64-bit). If you see it, you likely have Python installed.
- Important: The instructions in this workbook are for Python 3.11. Make sure you have this version.
- If you don't have Python (or have the wrong version), please ask your teacher for help with installation.
1.2 Preparing EasyGui
The EasyGui module needs to be in the same folder as your Python files for your programs to use it.
- Create a folder to save all your programs for this course. Name it 92004 programs.
- Get the easygui folder from your "Workbook Resources" and place it inside your 92004 programs folder.
- Your folder structure should look something like this:
92004 programs/ ├── easygui/ │ └── (EasyGui files here) └── (Your Python programs will go here)
Now that Python and EasyGui are set up, let's write your first program!
1.3 Producing Output: Your First Program
We'll use Python's built-in IDLE editor to write, edit, and save your code.
Opening IDLE and Creating a New File:
- Press the Windows key and type 'IDLE'. Click on IDLE (Python 3.11 64-bit).
- Once IDLE is open, press Ctrl + N or go to File > New File to open a new Editor window.
Write Your Code:
Now, type the following code into the Editor window. Pay close attention to the quote marks!
Remember: Don't leave out the quote marks (" "). They tell the computer this is text, not a number.
Run Your Program:
- Press F5 on your keyboard or go to Run > Run Module.
- You will be prompted to save the file. Click OK and save it as prog_1.py in your 92004 programs folder.
- A message box should appear on your screen! Click OK to dismiss it.
Let's Unpack the Code:
from easygui import *: This line calls the EasyGui module and imports all (*) its functions, making them available for use in your program.msgbox("This is my first program!"):msgboxis an EasyGui function that displays a message box on the screen.- The text inside the brackets (
"This is my first program!") is an argument. It tells themsgboxfunction what message to display.
Adding New Lines:
You can add new lines to your message box using \n. Each \n creates a new line.
Notice the \n\n for two new lines.
Learning Activity 1.1: Output Program
It's your turn to write some code!
- Create a new Python program.
- Write code for a program that greets the user and tells them what your name is.
- There should be two line spaces between the greeting and your name.
- The output should look similar to this (but with your name):
Hi! My name is Tama - Save the program with the file name hi1.py.
- Run the program and check your output!
Your Code Here:
Remember:
- To use EasyGui functions, you must first call EasyGui and import all the functions (at the start of your program):
from easygui import * - The
msgboxstatement must be followed by brackets(). - You must put what you want to output inside the brackets.
- For text, you must have quote marks (
" ") at the start and end of the text. - Use
\nto add line spaces.
SECTION 2: VARIABLES AND GETTING NUMBER INPUT
Great job with your first program! Now that you know how to display output, let's learn how to store information in your programs and get input from the user. This is where variables come in handy!
What You Will Learn:
- What variables are and how to use them
- How to change variable values
- Getting number input from the user
- Doing calculations with variables
2.1 Variables and Getting Number Input
What is a Variable?
Think of a variable as a named 'memory box' inside your computer. You can store different pieces of information (like numbers or text) in these boxes, and then retrieve or change that information later in your program.
Variables are incredibly useful because they allow your programs to be dynamic and react to different inputs or situations.
Assigning Values to Variables:
You create a variable and give it a value using the equals sign (=), which is called the assignment operator.
Variable names usually start with a lowercase letter and can contain numbers or underscores.
Getting Number Input with EasyGui's integerbox:
Just like msgbox shows a message, integerbox allows your program to ask the user for a whole number (an integer). The number the user types in will be stored in a variable you specify.
Notice str(age). We convert the number `age` to text so it can be combined (concatenated) with other text.
Understanding integerbox Arguments:
- The first argument is the message (e.g., "How old are you?").
- The second argument is the title for the pop-up window (e.g., "Age Input").
- The third argument is the default value that appears in the input box (e.g.,
18).
Learning Activity 2.1: Changing Variable Values
Time to put your knowledge of variables to the test!
- Create a new Python program.
- Use
integerboxto ask the user to enter a number between 1 and 100. Store this in a variable named num. - Change the value of num to
50. - Display the new value of num using
msgbox. The message should clearly state the new value. - Save the program as change_num.py.
- Run the program and check your output!
Your Code Here:
Remember:
- Variables are like containers for information.
- Use
=to assign a value to a variable (e.g.,my_variable = 10). - Use
integerbox(...)to get number input from the user. - Convert numbers to text using
str(...)when combining them with other text inmsgbox.
Learning Activity 2.2: Doing Calculations
Now that you know how to get numbers from the user and store them in variables, let's make your program perform some calculations!
- Create a new Python program.
- Use
integerboxtwice to ask the user to enter two different numbers. Store them in separate variables (e.g., num1 and num2). - Add these two numbers together and store the result in a new variable called total.
- Display the sum using
msgbox. The message should clearly state the calculation and its result (e.g., "The sum of [num1] and [num2] is [total]"). - Save the program as calculator_v1.py.
- Run the program and check your output!
Your Code Here:
Remember:
- The
+operator is used for addition. - Always convert numbers to strings with
str(...)when combining them with text inmsgbox. - Make sure your variable names are clear and descriptive.
SECTION 3: DATA TYPES AND GETTING TEXT INPUT
You've mastered numbers and basic calculations! Now let's explore different types of information your computer can handle and how to get text-based input from the user.
What You Will Learn:
- Understanding data types (numbers vs. text)
- Getting text input from the user using EasyGui's
enterbox - Converting between data types when necessary
3.1 Data Types and Getting Text Input
Data Types: Numbers vs. Text (Strings)
In programming, different kinds of information are called data types. So far, you've primarily worked with numbers (like `10`, `50`, `18`). When we talk about text, like "Hello World" or "My name is Tama", programmers call this a string.
- Numbers (Integers/Floats): Used for mathematical calculations.
- Strings (Text): Used for names, messages, sentences – anything that's text. Strings are always enclosed in quote marks (`" "`).
It's important to remember that numbers stored as strings cannot be directly used in mathematical calculations unless you convert them. You saw `str()` to convert numbers to strings; you'll soon see `int()` to convert strings to numbers.
Getting Text Input with EasyGui's enterbox:
To get text input from the user, we use EasyGui's enterbox function. It works similarly to `integerbox` but is designed for any type of text.
Notice how we can combine strings using the `+` operator.
Understanding enterbox Arguments:
- The first argument is the message (e.g., "What is your name?").
- The second argument is the title for the pop-up window (e.g., "Name Input").
- The third argument is the default value that appears in the input box (e.g.,
"Your Name Here").
Learning Activity 3.1: Percentage Calculator Program
Let's combine text input with number calculations to create a useful program!
- Create a new Python program.
- Use
integerboxto ask the user to enter the total marks possible for a test. Store this in a variable. - Use
integerboxto ask the user to enter their marks received for the test. Store this in a variable. - Calculate the percentage:
(marks received / total marks possible) * 100. Store the result in a variable (e.g., percentage). - Display the percentage in a
msgbox. The message should be clear and friendly (e.g., "Well done! You scored [percentage]%"). - Save the program as percentage_calc.py.
- Run the program and check your output!
Your Code Here:
Remember:
- Use the correct EasyGui function for the type of input you need (numbers with `integerbox`, text with `enterbox`).
- The division operator is
/and multiplication is*. - You might need to use parentheses `()` to control the order of operations in your calculation.
- Convert numbers to strings with
str(...)when combining them with text for display.
SECTION 4: SEQUENCE AND SELECTION CONTROL STRUCTURES
So far, your programs have run from top to bottom, executing each line in order. This is called sequence. But what if you want your program to make decisions? That's where selection comes in!
What You Will Learn:
- The importance of sequence in programming
- How to use `if`, `elif`, and `else` statements to make decisions
- Understanding comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`)
4.1 Sequence and Selection Control Structures
Sequence - The Order of Things
Every program you've written so far executes instructions one after another, from the first line to the last. This step-by-step execution is known as sequence. It's the fundamental building block of all programs!
Selection - Making Choices with `if`, `elif`, `else`
Programs often need to respond differently based on certain conditions. This is where selection (also known as branching or conditional logic) comes in. You use `if` statements to tell your program, "If this condition is true, do this; otherwise, do something else."
The basic structure is:
if condition_1:
# Do this if condition_1 is True
elif condition_2: # Optional: 'else if' another condition is True
# Do this if condition_2 is True (and condition_1 was False)
else: # Optional: If none of the above conditions are True
# Do this
Remember the colon (`:`) after `if`, `elif`, and `else`, and the indentation for the code blocks!
Comparison Operators:
Conditions are created using comparison operators:
==Equal to (e.g., `age == 18`)!=Not equal to (e.g., `name != "Bob"`)<Less than (e.g., `score < 50`)>Greater than (e.g., `temperature > 25`)<=Less than or equal to>=Greater than or equal to
Example: Age Checker
Learning Activity 4.1: Calculator App v1
Let's build a simple calculator that can perform addition, subtraction, multiplication, and division based on user choice!
- Create a new Python program.
- Use
integerboxto get two numbers from the user. Store them in variables (e.g., num1, num2). - Use
choiceboxto ask the user to choose an operation: "+", "-", "*", or "/". Store their choice in a variable (e.g., operation). Remember thatchoiceboxtakes a list of options! - Use
if,elif, andelsestatements to perform the chosen calculation. - Display the result using
msgbox. Make sure the output is clear (e.g., "10 + 5 = 15"). - Handle division by zero if the user chooses division and `num2` is 0.
- Save the program as simple_calc.py.
- Run the program and test all operations!
Your Code Here:
Remember:
- Use
integerboxfor numbers andchoiceboxfor selecting from a list of options. - The choices for
choiceboxmust be provided as a Python list (e.g., `["Add", "Subtract"]`). - Pay close attention to indentation for your `if`/`elif`/`else` blocks.
- Test your code thoroughly with different inputs and operations!
Learning Activity 4.2: Number Game v1
Let's create a simple number guessing game! The computer will "think" of a secret number, and the user will try to guess it.
- Create a new Python program.
- Set a variable, e.g., secret_number, to a fixed number (e.g., `7`).
- Use
integerboxto ask the user to guess a number between 1 and 10. Store their guess in a variable. - Use `if`, `elif`, and `else` statements to check the guess:
- If the guess is equal to the `secret_number`, display "Congratulations! You guessed it!"
- If the guess is less than the `secret_number`, display "Too low! Try again."
- If the guess is greater than the `secret_number`, display "Too high! Try again."
- Save the program as guess_game.py.
- Run the program and play the game!
Your Code Here:
SECTION 5: ITERATION CONTROL STRUCTURES AND TESTING
You've learned how to make your programs follow a sequence and make decisions. What if you need your program to repeat a task multiple times? That's where iteration (or loops) comes in!
What You Will Learn:
- How to use `for` loops for repeating tasks a known number of times
- How to use `while` loops for repeating tasks as long as a condition is true
- Basic concepts of testing your programs
5.1 Iteration Control Structures
The Power of Loops: `for` and `while`
Iteration allows your program to execute a block of code repeatedly. This saves a lot of typing and makes your programs more efficient!
The `for` Loop (Known Number of Repeats):
A `for` loop is used when you know exactly how many times you want to repeat a task. We often use it with the `range()` function.
`range(3)` generates numbers 0, 1, 2. The variable `i` takes on each of these values.
The `while` Loop (Repeat Until Condition is False):
A `while` loop is used when you want to repeat a task as long as a certain condition remains true. The loop continues until the condition becomes false.
If `count` was never incremented, this would be an infinite loop!
Testing Your Programs
After writing your code, it's crucial to test it. Testing means running your program with different inputs to ensure it behaves as expected in all situations.
- Normal cases: Inputs you expect.
- Edge cases: Minimum/maximum values, zero, empty input.
- Error cases: Invalid inputs to see how your program handles them.
Learning Activity 5.1: Countdown Program
Let's create a program that counts down from a number entered by the user.
- Create a new Python program.
- Use
integerboxto ask the user to enter a starting number for the countdown (e.g., `5`). Store it in a variable (e.g., start_num). - Use either a `for` loop with `range()` or a `while` loop to count down from `start_num` to 1.
- Inside the loop, display the current countdown number using
msgbox. - After the loop finishes, display a "Blast off!" or "Countdown complete!" message.
- Save the program as countdown.py.
- Run and test your countdown!
Your Code Here:
Learning Activity 5.2: Quiz Program v1
Let's create a simple quiz that keeps asking a question until the user gets it right.
- Create a new Python program.
- Define a secret_answer variable (e.g., `"Python"`).
- Use a `while` loop that continues as long as the user's guess is not equal to the secret_answer.
- Inside the loop, use
enterboxto ask the user a question (e.g., "What is the capital of New Zealand?") and store their answer in the guess variable. - If the guess is wrong, use
msgboxto tell them "Incorrect! Try again." - Once the loop finishes (meaning they guessed correctly), display "Correct! Well done!" using
msgbox. - Save the program as quiz_v1.py.
- Run and test your quiz!
Your Code Here:
SECTION 6: LISTS AND COMMENTING
You're making great progress! Now let's look at how to store multiple pieces of information in a single variable using lists, and how to make your code easier to understand with comments.
What You Will Learn:
- Creating and using lists to store collections of data
- Accessing elements in a list
- Adding and removing items from lists
- Writing effective comments to explain your code
6.1 Lists
What are Lists?
A list is a fundamental data structure in Python that allows you to store an ordered collection of items. Think of it like a shopping list or a list of names – all grouped under one variable name. Lists are created using square brackets `[]`.
Creating and Accessing Lists:
Modifying Lists:
.append(item): Adds an item to the end of the list..remove(item): Removes the first occurrence of an item.del list[index]: Deletes an item at a specific index.- You can also change an item:
list[index] = new_value.
Example: Modifying a List
6.2 Commenting
Why Comment?
As your programs get more complex, it becomes harder to remember what each part of your code does. This is where comments come in! Comments are lines in your code that are ignored by the computer, but they are incredibly important for humans.
- Explain complex logic: Help others (and future you!) understand difficult parts.
- Describe purpose: State what a function or block of code is supposed to achieve.
- Debugging: Temporarily disable lines of code without deleting them.
How to Write Comments:
In Python, any text after a hash symbol (`#`) on a line is a comment.
Learning Activity 6.1: Shopping List App
Let's create a simple shopping list application where you can add items and view your list.
- Create a new Python program.
- Initialize an empty list called shopping_list.
- Use a `while` loop to create a menu:
- Ask the user if they want to "Add Item" or "View List" or "Quit" using
choicebox. - If "Add Item" is chosen, use
enterboxto get the item name and add it to `shopping_list` using `.append()`. - If "View List" is chosen, display the current `shopping_list` using
msgbox. Make sure the list is displayed nicely (e.g., join items with `\n`). - If "Quit" is chosen, break out of the loop.
- Ask the user if they want to "Add Item" or "View List" or "Quit" using
- Add comments to your code to explain different parts.
- Save the program as shopping_app.py.
- Run and test your shopping list app!
Your Code Here:
Learning Activity 6.2: Quiz with List of Questions
Let's enhance our quiz program by storing multiple questions and answers in lists!
- Create two lists: questions and answers. Make sure the answer at index `i` in the `answers` list corresponds to the question at index `i` in the `questions` list.
- Use a `for` loop to iterate through your `questions` list.
- Inside the loop:
- Use
enterboxto ask the current question. - Compare the user's answer to the correct answer from your `answers` list.
- Use
msgboxto tell the user if their answer is "Correct!" or "Incorrect. The answer was [correct_answer]."
- Use
- Keep track of the user's score and display it at the end.
- Add comments to explain your code.
- Save the program as quiz_v2.py.
- Run and test your multi-question quiz!