Assignment is used to store a value in a variable. The equals sign = is used to assign values to variables, meaning that the variable on the left takes on the value on the right.
total = 0
message = 'Hello World'
rating = 3.8
correct = False
In some languages, Boolean values use true and false, but in Python, they must be True and False (capitalized).
Arithmetic operations are used to carry out calculations.
There are arithmetic operators for:
+ Add
- Subtract
* Multiply
/ Divide
^ Exponent
# Three variables
num1 = 5
num2 = 7
sum = 0.0
# Addition
sum = num1 + num2
# Subtraction
sum = num1 - num2
# Division
sum = num1 / num2
# Multiplication
sum = num1 * num2
# Raise to a power
sum = num1 ** num2
Concatenation is the process of joining two or more strings to form a single string. This is useful when combining words, sentences, or user input.
display "Hello " + name + ", how are you?"
Hello Lucy, how are you?
Alternative (Modern Method)
Programs often need to make decisions based on conditions. These decisions are controlled using IF Statements., which allow a program to execute specific code only when a condition is met.
The if statement always starts with the word if, followed by a condition. A condition checks that something is equal to, greater than or less than something else.
In this example, the user is asked to enter a password. If they enter “hello123”, access is granted:
# Ask the user to enter a password
passwd = input("Please enter the password")
# Is access granted?
if passwd == “hello123”:
print("Access granted")
We use indentation for any code that we want to be inside the if statement (this means we tab it in). Notice that the print statement is tabbed in slightly from the left. This means that it only happens if the if statement above it is true. We could have multiple lines of code inside the if statement.
The if statement always ends in a colon :
Sometimes, we want the program to do something if data meets a condition, or otherwise, it is to do something else. This is called an else statement.
A program could check that someone’s age is greater than or equal to 17. If so, they are allowed to drive. If this is not so, they are not allowed to drive:
# Ask the user for their age
age = int(input("Please enter your age"))
# Old enough to drive?
if age >= 17:
print("Broom broom")
else:
print("Sorry, no drive yet”)
In these examples, the program always does one thing, or the other. They are mutually exclusive. You cannot be both age >= 17 and not >= 17 at the same time, so only one branch of the decision is carried out.
If a program decision could have multiple branches, we use ELIF.
This is very efficient, because the program only needs to check for a B or C if the person did not get an A. If they did get enough marks for an A, the program never has to check those conditions.
# Ask for percentage mark
mark = int(input("Please enter percentage mark"))
# Check which category mark goes in
if mark >= 70:
grade = “A”
elif mark >= 60:
grade = “B”
elif mark >= 50:
grade = “C”
else:
grade = “F”
# Print the grade
print(grade)
Logical operators allow us to combine multiple conditions in a single if statement. The three main logical operators in Python are:
Both conditions must be true.
if age >= 17 and age <= 100:
print(“You are between 17 and 100”)
At least one condition must be true.
if weather == “rain” or weather == “cloudy”
print(“It is not nice weather today”)
Reverses a condition (makes true become false and vice versa)..
if not age < 17
print(“You are not less than 17”)
print(“So you must be at least 17 or over”)
A fixed loop repeats a set number of times, regardless of user input or conditions. This is useful when we know in advance how many times a task should be repeated.
So, instead of this:
# This is repetitive...
print("Hello world")
print("Hello world")
print("Hello world")
print("Hello world")
We can use this:
for counter in range(10):
print(“Hello world”)
The word loop is a variable that we could use within our code. It is called the loop counter, because it counts how many times the loop has run so far.
A running total keeps track of a cumulative sum as numbers are entered. This is useful in programs that need to calculate sums, averages, or scores.
# Example with a running total
total = 0
for loop in range(10):
number = int(input("Please enter a number"))
total += number
# Show total once the loop is done
print(total)
A conditional loop runs as long as a condition remains true. Unlike a fixed loop, it doesn’t have a set number of iterations—it continues looping until the condition becomes false.
You can use all of the same conditions in a while loop that you would in an if statement.
In this example, the user is asked to enter a number. If the number is more than 100, part of the program repeats, asking them to enter the number again.
It only repeats while their input is more than 100. Once that condition is met, the loop stops repeating and the program continues:
Alternative (more modern, flexible method)
Pre-defined functions are built-in functions in Python that help us perform common tasks without needing to write extra code. Using these functions makes our programs simpler, faster, and more efficient.
There are three pre-defined functions for National 5: random, round and length.
`random` generates unpredictable numbers.
`round` simplifies numbers to a chosen precision.
`len` finds the length of text.
Something that is random is open to chance - like rolling dice, or tossing a coin.
random.randint(a, b) returns a random integer between a and b (inclusive). This is useful for dice rolls, guessing games, and generating unpredictable values.
Before we use a random number, we have to put this line at the top of the program:
# This program is going to use random numbers
import random
This program asks the user to enter a number between 1 and 10.
It then generates a random number in that range and uses an IF to compare the two values.
If the numbers are the same, it displays that the user has guessed correctly.
Using a round function, we can round a real number either:
To the nearest whole number
To a certain number of decimal places
round(x) rounds x to the nearest whole number. We can also specify decimal places using round(x, d), where d is the number of decimal places.
We could round to any number of decimal places by adding it as a parameter in brackets:
This would print 3.14.
num2 = round(3.14159265, 2)
print(num2)
The length function, shortened to len() returns the number of characters in a string, including spaces. This is useful for checking word lengths, validating input, and processing text.
This example gets the length of a word, stores it in a variable called “howLong”, and displays it on the screen.