A whole number
A decimal number
A single character in quote marks ("A")
Multiple characters in quote marks ("Hello")
True or False
Note: Python does not have characters as a data type and just treats them as strings
Store data that can be accessed within the code.
Can be entered by programmer or by user
Can change whilst program is running
Store data that can be accessed within the code.
Usually set by the programmer
Can't change whilst program is running, meaning it stays the same throughout
Below is a python program that calculates the VAT of a purchase in a shop.
The VAT is 20% so this is a constant (you can tell by it being in capitals)
The order is a variable as the user is entering the cost of each order
The total is a variable as it calculates the total cost of the order + VAT for each order
VAT = 0.2
order = float(input("Enter cost of the order: "))
total = order + (order * VAT)
print(f"your total cost including VAT is: £{total}")
inputs are used to allow the user of the program to type in data, usually in response to a question asked by the program.
name = input("Please enter your name: ")
outputs are used to show data to the user from within the program, usually the result of something the user has asked for or the program is built to do.
in the input section, we get the user to enter their name, let's output a welcome message that is personalised to them. (the user typed in John Connor
print(f"Welcome {name}!")
would show the user:
>> Welcome John Connor!
A set of events, actions, numbers, etc. which have a particular order and lead to a particular result.
Example:
Here are the instructions to a morning routine:
Get dressed
Brush teeth
Have breakfast
Make the bed
Get out of bed
Have a shower
The order in which tasks are done here do not make sense, how can you make the bed before you get out of it, likewise why would you get dressed and then have a shower or brush your teeth before you have had breakfast. It may make more sense to do it in this order:
Get out of bed
Make the bed
Have a shower
Get dressed
Have breakfast
Brush Teeth
The same principle applies in programming, each instruction is carried out one after the other. So they need to be a logical order for the computer to be able to run the program successfully.
All programs have a series of steps to be followed In sequence. Here is an example in which the steps are simple assignment statements:
score1 = int(input("Enter score for Round 1: "))
score2 = int(input("Enter score for Round 2: "))
average = (score1 + score2) / 2
print(f"The average score is: {average}")
Deciding what comes next based on the meeting of a condition.
Example:
Imagine a game of guess who, 2 players, each player has a person that they "are".
They then take it in turns to ask questions like "Does your person wear glasses?"
If your person does wear glasses, you say "yes" and they get rid of all possible people without glasses.
Else, you say "no" and they get rid of all possible people with glasses.
The same principle applies in programming, you ask the user a question and depending upon what they say, you tell the program to take a specific course of action.
Here is an example of guess who implemented in Python:
answer = input("Does your person wear glasses? ")
if answer == "yes":
wearsGlasses = True
else:
wearsGlasses = False
Repeating until an amount or condition is met.
Example:
If I said to you: "say hello 5 times"
you would go: "hello, hello, hello, hello, hello"
but in your brain, as you have said each of those hello's you have gone 1,2,3,4,5.
This is a for loop, for each number in this amount of times, do this.
Alternatively, I could say to you: "while you are doing your GCSE in Computer Science, say hello" and then who knows how many times you will say the word hello for 2 years straight without stopping.
This is a while loop, while something is the case, do this.
So, there are 2 types of iteration:
Definite iteration - a count-controlled loop that will definitely run and we know how many times it will run (finite) - For loop.
example:
total = 0
scores = int(input("How many scores would you like to enter? "))
for score in scores:
newScore = int(input("Enter Score: "))
total = total + newScore
Indefinite iteration - a condition controlled loop that may never run, may run a number of times we don't know or may run forever (infinite) - While loop.
example:
total = 0
loop = True
while loop == True:
scores = input("Do you have more scores to enter? "))
if scores == "yes":
newScore = int(input("Enter Score: "))
total = total + newScore
else:
loop = False
With integers and floats you can perform arithmetic (mathematical) operations.
Addition is carried out with the + symbol
num1 = 13
num2 = 18
print(num1 + num2)
would output
>> 31
Subtraction is carried out with the - symbol
num1 = 18
num2 = 13
print(num1 - num2)
would output
>> 5
Multiplication is carried out with the * symbol
num1 = 3
num2 = 8
print(num1 * num2)
would output
>> 24
Exponent means the power of, for example 5 to the power of 2 = 25
Exponent is carried out with **
num1 = 3
num2 = 8
print(num1 ** num2)
would output
>> 512
Division is carried out with the / symbol
num1 = 17
num2 = 2
print(num1 / num2)
would output
>> 8.5
Integer Division returns the whole number result of a division
Integer Division is carried out with //
num1 = 17
num2 = 2
print(num1 // num2)
would output
>> 8
Remainder Division returns the remainder result of a division
Remainder Division is carried out with %
num1 = 17
num2 = 2
print(num1 % num2)
would output
>> 1
num1 = 3
num2 = 5
if num1 < num2:
print("num2 is bigger")
else:
print("num1 is bigger")
num1 = 3
num2 = 5
if num1 > num2:
print("num1 is bigger")
else:
print("num2 is bigger")
age = 18
if age <= 17:
print("you are legally a child")
else:
print("you are legally an adult")
age = 18
if age >= 18:
print("you are legally an adult")
else:
print("you are legally a child")
password = "abc123"
user_pwd = input("Enter password: ")
if user_pwd == password:
print("access granted")
else:
print("incorrect password")
password = "abc123"
user_pwd = input("Enter password: ")
if user_pwd != password:
print("incorrect password")
else:
print("access granted")
if weather == "sunny" and temperature >= 20:
print("picnic!")
else:
print("eat inside")
if weather == "sunny" or temperature >= 20:
print("ice cream")
else:
print("cake")
found = False
if not found:
print("not found")
else:
print("found")
In Python, all inputs are strings, but sometimes, you need the user to be able to input a whole number or a decimal number, to do this, we need to do something called type casting.
To do this, Python has a couple of built-in functions that take the string and turn it into a integer or a float (decimal).
num = int(input("Enter a number: "))
it is important to recognise that the int() function has its own brackets and so does the input() function, therefore you put the input inside the brackets for the int() function.
num = float(input("Enter a decimal: "))
Just like the int() function, the float() function has its own brackets.
It is also possible to turn integers and floats into strings using a built-in function.
print(str(num))
in this example, the print() function has its own brackets and so does the str() function, however, unlike our inputs above that went inside the int() and float() functions, this time we are outputting the string version of num and therefore, the print() goes on the outside.
Strings are a sequence of characters enclosed in quote marks, because of this, we can manipulate them to access each individual letter. Python has a few built-in functions that are used to manipulate strings.
To find the length of a string, Python has a function called len().
animal = "hippopotamus"
print(len(animal))
will return:
>> 12
It is important to note that if there is more than 1 word in the string, the spaces will be counted too.
A substring is a set of characters within a string.
To do this in python, we give the name of the string followed by square brackets we then give a start index, an end index and a step (optional).
format:
string[start:stop:step]
example:
word = "Computer Science"
print(word[3:5])
would output
>> put
Notice, we didn't use the step value here, it is optional and we didn't need it, however, you could do this:
print(word[::2])
would output every other letter in Computer Science
>> Cmue cec
To find the position of a letter or substring in a string, we use the index() function.
To do this in python, we give the name of the string followed by .index() but inside the brackets we need to put the character or substring we are looking for.
Optionally, you can also give index() a start and end of you want to look for a particular value within a certain range of text.
format:
string.index(value, start, end)
example:
word = "Computer Science"
print(word.index("put"))
would output
>> 3
because the word put starts at index 3 in the word Computer.
IsType functions are extremely useful when trying to check if a user input is the correct data type.
For example:
If you asked the user to enter their age, you would be expecting an integer (whole number) so you can use the .isdigit() function to check they entered a whole number.
format:
string.isdigit()
example:
age = int(input(“enter your age: ”))
if age.isdigit():
print(“Thank you”)
else:
print(“not a number”)
there is also . isupper() and .islower() to check if a string input is uppercase or lowercase.
example:
word = "hello"
if word.isupper():
print("capitals")
else:
print("lowercase")
As well as built-in functions, Python allows you to import functions from other banks of Python code, these are called libraries.
One such library is the random library, where there are functions that allow us to randomly choose between options or randomly generate numbers.
To make use of these functions, you have to tell your Python program to import the random library, this is done like this:
import random
The randint funtion is a part of the random library that allows us to generate random whole numbers (int being integer). The function takes 2 arguments, the lowest number you would like it to consider and the highest.
Here is an example of a basic number guessing game using randint to randomly pick the number to guess:
import random
rand_num = random.randint(1,100)
guess = int(input("Enter your guess: "))
if guess == rand_num:
print("you guessed it!")
else:
print("nope")
The choice function is a part of the random library and allows us to randomly pick an option from a set of options.
Here is an example of a basic word guessing game using choice to randomly pick the word to guess:
import random
words = ["apple","grape","pear"]
rand_word = random.choice(words)
if guess == rand_word:
print("you guessed it!")
else:
print("nope")