Programming – It All Adds Up (Unit 4):
Detailed Study Notes
4.1 Logical Tests and Choice
Conditional Structures:
- A structure that makes decisions in a program.
- Also called an if structure.
- Works by checking a logical test: commands run if True, skipped if False.
Logical Tests:
- Result in True or False.
- Compare two values using relational operators.
Relational Operators:
- Scratch: > (greater), < (less), = (equal)
- Python: == (equal), != (not equal), >, <, >=, <=.
Examples:
- 4 > 8 -> False
- 3 + 4 == 7 -> True
Scratch Example: Ask if user wants to add numbers, if Y then add.
Python Example:
number1 = 70
number2 = 80
answer = input('Do you want to add? (Y/N) ')
if answer == 'Y':
result = number1 + number2
print(result)
If…Else: Allows two branches based on True or False conditions.
4.2 Loops – Add Up a Total
Loops:
- Repeat commands multiple times.
- Types: Counter (fixed times) and Conditional (until a condition is met).
Scratch Counter Loop: repeat 10 {commands}.
Python Counter Loop:
for i in range(10):
print('Hello')
Increase a Variable:
- Pattern: total = total + number
- Python example with user input converting string to int.
4.3 Conditional Loops
Controlled by a logical test.
Scratch: repeat until <condition>.
Python: while <condition>:
- Scratch stops when test is True.
- Python continues while test is True.
Python Example:
total = 0
answer = int(input('Enter a number: '))
while answer != 0:
total += answer
answer = int(input('Enter a number: '))
print(total)
4.4 Class Project – Bird Counter
Objective: Count bird visitors.
Steps:
- Use a variable starting at 0.
- Use a conditional loop.
Common Errors: Syntax errors (wrong keywords, missing :, no indent, = instead of ==).
Plan:
1. Set total = 0
2. Ask for input (Y if bird seen)
3. Loop while input == 'Y': total += 1, ask again
4. Print total.
4.5 Extend the Project – Bird Addition
Birds may arrive in groups. Program should accept numbers of birds.
Use variable 'visits', convert input to integer, and use 99 as exit condition.
Final Program:
total = 0
visits = int(input('Enter the number of visits: '))
while visits != 99:
total += visits
visits = int(input('Enter the number of visits: '))
print('Total number of visits was:', total)
4.6 Readability and User-Friendliness
User-Friendly:
- Clear inputs and prompts.
- Clear outputs with explanations.
- Helpful messages.
Readable:
- Good variable names.
- Use comments (#) to explain code.
Example with comments and prompts to guide users and display totals clearly.