Firstly, this is a guide on how to code in Python up to GCSE level, as I know it, so you may be on a different exam board, or there may be more that I don’t know about. So don't take this as an exact guide! But, hopefully it is still helpful :)
For the non-English people, sorry. Just think of it as the basics of python (or whatever your equivalent of a GCSE is (google it))
Contents:
The print function
Comments
Data Types
Concatenation
Variables
Input Function
Operators
Comparatives
Boolean Comparatives
Conditional Statements (if, elif, else)
While loop
String Manipulation
lists
For Loops
Standard Libraries
The print function
The print function is what we use to output something to the console (the black thing at the side of/underneath your code.
How to Use
To print something we write:
print()
Inside the brackets is where we write what we want to print. If you want to print words, we put the text we want to write between "
e.g.
print("Hello World")
Comments
A comment is just a line with anything written on, but isn't run. They are usually used to increase readability and explain parts of a program.
When you put a #, everything after that on that line will not be run (they will be a comment).
e.g.
print("Hello World")
# This is a comment
# The code above will output Hello World
Data Types
Data types are the type of 'thing' that a certain but of data is.
There are 4 data types (for GCSE):
string = some text with no numerical value. e.g. "Hello World"
int = A whole number. e.g. 3
float = A decimal value e.g. 3.1415
bool = A Boolean value. True or False
How to make them:
string = anything with " around it is a string
int = an integer (whole number) with no " around it
float = an decimal value without " around it
bool = True or False with no " around
Concatenation
Concatenation is where you 'stick together' some strings.
This is where data types are important. If you attempt to concatenate something which isn't a string, you will get an error.
How to do
To concatenate something, just simple put a + between them.
e.g.
print("Hello " + "world")
Will output: Hello World
Remember to add a space after 'Hello', or before 'world', otherwise it will output 'Helloworld'
Concatenating with something which isn't a string
You will get an error whenever you try to concatenate a string with another data type (i.e. int) So, how do you print a number with a string?
It is simple actually, just turn it into a string
e.g.
print("I am " + 14 + " years old")
Will throw an error, so we do this instead:
print("I am " + str(14) + " years old")
We turn the int (14) into a string by doing str(int) This works with all data types.
Obviously for that example, you could just do:
print("I am 14 years old")
Variables
This is really what the last section is used for.
A variable is a 'thing' that holds information for later use in a program.
How to make a variable
To declare a variable, simply write:
varName = something
Where varName is replaced with what you want to name the variable.
Make sure that you name your variable something that describes the information that it holds (so not just 'a' or 'b' or something like that)
Where 'something' is the thing that you want the variable to hold (i.e. an int or a string)
e.g.
age = 14
Naming variables
There are a few key rules when naming variables. They are:
No spaces
Don't start with a number
No keywords (e.g. print)
(Doesn't throw an error) don't start with capital letter
How to use
To use a variable, all you need to do is write its name whenever you want the value of it to be used.
e.g.
age = 14
print("I am " + str(age) + " years old")
# Notice that I have made age a string so that it can be concatenated
Variables can be overwritten with other values.
e.g.
age = 14
print("I am " + str(age) + " years old")
# I am 14 years old
age = 15
print("I am now " + str(age) + "years old")
# I am now 15 years old
Input Function
The input function is where we can start to allow the user to interact with your program
How to use
To use it, all you need to do is write input(prompt). Where prompt is replaced with a string to tell the user what to input.
Normally, you will save their input to a variable, to do that all we need to do is write varName = input(prompt)
The thing that is input, will default to a string, but if you want to use their input in calculations, then that will not work. You can do int(input(prompt)) or float(input(prompt)) depending on what data type you want.
e.g.
name = input("What is your name? ")
age = input("Enter age: ")
print("Hello " + name + ", you are " + age + " years old!")
Operators
Operators are basically the symbols used in maths.
They are:
+ Adds numbers together (also used for concatenation)
- Subtracts numbers
* Multiplies numbers
** raises a number by another. (e.g. 5**2 = 25)
/ divides numbers
// divides numbers, but gets rid of anything after the decimal point in the answer
% divide numbers, but returns the remainder
e.g. To put seconds to minutes and seconds
time = 80
minutes = time//60 #will return 1 in this situation
seconds = time%60 #will return 20 in this situation
print(minutes + "minutes " + seconds + "seconds") #will print '1 minutes 20 seconds' in this situation
If you want to increase a variable by a certain amount, you can do varName += value the + can be replaced with any operator.
Comparatives
Comparatives are what are used mainly in conditional statements (they are coming next)
The Comparative operators are:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== and != can be used with strings as well as ints and floats, but the others can only be used with ints/floats.
When you use these, they return a Boolean value (True or False)
Make sure that you use == for equal to, = is just used for assigning variables
Boolean Comparatives
They are:
not
or
and
These are used in relation with the Boolean values returned by the other comparatives.
not
not will reverse the Boolean value that is put into it
e.g. if I were to put something that was False into a not gate, it would return True
or
Used to compare two Boolean values.
If either of the Boolean values are True, then it will return True.
and
Used to compare two Boolean values.
If both of the Boolean values are True, then it will return True.
Examples
14 == 14 or 13<14 #True
14 == 14 or 17>20 #True
12 <= 10 or 20>17 #True
12 <= 10 or 17>20 #False
14 == 14 and 13<14 #True
14 == 14 and 17>20 #False
12 <= 10 and 20>17 #False
12 <= 10 and 17>20 #False
Note: Don't do this
if num == 5 or 7 or 24:
You need to do
if num == 5 or num == 7 or num == 24
Conditional Statements (if, elif, else)
You will find at least one conditional statement in all python programs, so it is important that you understand what they do.
Basically, the 'take in' Boolean values/statements and will only run if that statement is True This is where you will get introduced to the very important concept of indentation.
A simple if statement will look something like:
if num == num2:
#do something
Here, you can see the comparative being used, which will return true if num equals num2. Any code on the same indentation level as the comment, will only run if that expression id True.
Another example is:
secretNum = 14
if int(input("Enter a number: ")) == secretNum:
print("You correctly guessed the secret number")
With if, you can use else. What this basically does is the code after the else (indented) will only be run if the if statement above is False
e.g.
secretNum = 14
if int(input("Enter a number: ")) == secretNum:
print("You correctly guessed the secret number")
else:
print("Sorry, you were incorrect")
As you can see, the else is on the same indentation level as the if.
With if, you can also use elif (short for else if). The code after the elif statement will only run if the previous if/elif statement is Falseand the elif statement is True.
e.g.
secretNum = 14
userNum = int(input("Enter a number: "))
if userNum == secretNum:
print("You correctly guessed the secret number")
elif userNum <= secretNum + 10 or userNum >= secretNum - 10:
print("Sorry, you were 10 away from the number")
else:
print("Sorry, you were incorrect")
Make sure that you don't forget the indents, or the colon (:) at the end of the statement
While Loop
A while loop is something that will repeat (loop) the code on the next indentation level underneath the initial statement until the statement is True.
I feel like the best way to learn this is through an example.
e.g.
password = input("Enter password: ")
while password != "password123":
password = input("Invalid. Enter password: ")
print("logged in")
So in this example, if the password variable (user input) does not equal the string 'password123': the loop will run. The user is then asked for the password again. The password variable is then overwritten with the new input from the user. The statement is then asked again, if they input 'password123'. If the get it wrong again, then the loop will repeat until they get it correct. If they get it correct, then the loop will not run again and the code will be run as usual from the line after the last indented line in the loop.
String Manipulation
Strings have properties called indices (sing. index). Indices are just a position in a string. The first character in a string is at index 0 The second character in a string is at index 1
How to use
If you want to see what character is at a certain index, you write the variable and in square brackets, write the number of the index.
Also, you can go backwards in a list by using a negative index. (-1 is the last character in the list)
e.g.
string = "Hello World"
print(string[4]) #prints the letter 'o'
print(string[-3]) #prints the letter 'r'
You can find ranges of indices in strings like this:
string = "Hello World"
print(string[2:8])
This will print 'llo Wo' (it prints from index 2 until index 7 (8-1))
If you want to find all the characters up to a certain point, then do string[:num] where num is the index of the first index that you don't want.
If you want to find all the characters after a certain point, then do string[num:] where num is the index of the first index that you want.
There are lots of built in functions for strings, but I only use a few (you can find the others using google)
len(varName) returns the length of the string Oh, lol that is the only string function that I use :)
A list is something that contains multiple, strings or other data types. They are sometime called arrays.
A list looks like this:
colours = ["red", "green", "blue"]
It is defined by the square brackets, and the commas between the elements. They use the same index system as strings do (yay!)
How to see if something is in a list
It is nice and simple, just write:
if "f" in list:
print("One of the elements in the list is an f")
(this also works with strings)
You can do lots of things with lists. See image. Or go here and scroll down to near the bottom.
For Loops
A for loop is a loop that will loop a certain amount of times (depending on what you tell it to do)
how to make a for loop:
First you need to write for, then you will need to make up a variable name that will be changed every time it loops (you'll see).
Then you will need to say what/how many times to loop [through]. You do this with the keyword in
This needs to be done with examples, there is no way that I will be able to explain this clearly without them.
colours = ["green", "red", "yellow", "blue"]
text = ""
for element in colours: #This line will make a new variable called element, which will move to the next element in the list called colours
text += element + " "
print(text)
How that example works. I assume if you have read the rest of the post you will no what the rest of it does except the for loop. So, a new variable called elements is made. Every time a loop is completed, it changes to the next element in the list colours. Then it adds that list element to a variable (which was defined outside the loop) with a space in a string. Once it has looped/integrated through all of the elements in the list, it will not loop again and it will print the variable text
This also works in the same way with strings.
Now, another way of using for loops, is with the range() function.
Again, an example is easier than straight up explanation.
for loops in range(1,11,1):
print("Hello World")
This will print 'Hello World' 10 times.
How it works: Look at the numbers in the brackets, the first tells it what number the variable loops should start at. The second number, is what number (not inclusive) that the loops will get to before the loop stops. The last number is the increment/step that the variable loops is increased by each loop.
To see it in another example, here is something that will print even numbers from 20-30:
for num in range(20, 31, 2):
print(num)
Here it starts at 20, ends on 30 and steps by 2.
Note: You can also have negative steps e.g. for num in range (30, 19, -2):
Bu default, step is 1 and the start value is 0. So if you just want to loop ten times you can just write: for num in range(10):
Standard Libraries
A library is some extra functions that you need to import into your code to use
from libraryName import libraryFunction then: libraryFunction()
Time library
The main functions in the time library (that I use) are: time() and sleep()
time(): This will return the amount of time that has passed since 12:00AM 1st January 1970 (in seconds) It is usually used to see how much time has passed between 2 points by having a variable with a start time and one for an end time. You then subtract end by start to get the time passed.
sleep(): Pauses the program for a certain amount of seconds (write the number of seconds in the brackets)
Random library
The main functions in the random library (that I use) are: randint() and choice()
randint(num1, num2): chooses a random number between num1 and num2
choice() chooses a random element in a list (write the list/variable with the list in, in the brackets)
Math library
The main functions that I use in the math library are: sqrt(), pi, floor(), ceil()
sqrt(): Square roots the number in the brackets
pi: the number pi
floor(): rounds down the float in the brackets ceil(): rounds up the float in the brackets
THAT'S THE END!!!
Please tell me about the inevitable typos and errors that there will be :)
How to python (GCSE/The Basics)
Made into a website here: https://how-to-python.codingcactus.repl.co/
Firstly, this is a guide on how to code in Python up to GCSE level, as I know it, so you may be on a different exam board, or there may be more that I don’t know about. So don't take this as an exact guide! But, hopefully it is still helpful :)
For the non-English people, sorry. Just think of it as the basics of python (or whatever your equivalent of a GCSE is (google it))
Contents:
The print function
The print function is what we use to output something to the console (the black thing at the side of/underneath your code.
How to Use
To print something we write:
Inside the brackets is where we write what we want to print. If you want to print words, we put the text we want to write between
"
e.g.
Comments
A comment is just a line with anything written on, but isn't run. They are usually used to increase readability and explain parts of a program.
When you put a
#
, everything after that on that line will not be run (they will be a comment).e.g.
Data Types
Data types are the type of 'thing' that a certain but of data is.
There are 4 data types (for GCSE):
"Hello World"
3
3.1415
True
orFalse
How to make them:
"
around it is a string"
around it"
around itTrue
orFalse
with no"
aroundConcatenation
Concatenation is where you 'stick together' some strings.
This is where data types are important. If you attempt to concatenate something which isn't a string, you will get an error.
How to do
To concatenate something, just simple put a
+
between them.e.g.
Will output: Hello World
Concatenating with something which isn't a string
You will get an error whenever you try to concatenate a string with another data type (i.e.
int
)So, how do you print a number with a string?
It is simple actually, just turn it into a string
e.g.
Will throw an error, so we do this instead:
We turn the
int
(14) into a string by doingstr(int)
This works with all data types.Obviously for that example, you could just do:
Variables
This is really what the last section is used for.
A variable is a 'thing' that holds information for later use in a program.
How to make a variable
To declare a variable, simply write:
Where
varName
is replaced with what you want to name the variable.Where 'something' is the thing that you want the variable to hold (i.e. an int or a string)
e.g.
Naming variables
There are a few key rules when naming variables.
They are:
How to use
To use a variable, all you need to do is write its name whenever you want the value of it to be used.
e.g.
Variables can be overwritten with other values.
e.g.
Input Function
The input function is where we can start to allow the user to interact with your program
How to use
To use it, all you need to do is write
input(prompt)
. Where prompt is replaced with a string to tell the user what to input.Normally, you will save their input to a variable, to do that all we need to do is write
varName = input(prompt)
The thing that is input, will default to a string, but if you want to use their input in calculations, then that will not work. You can do
int(input(prompt))
orfloat(input(prompt))
depending on what data type you want.e.g.
Operators
Operators are basically the symbols used in maths.
They are:
+
Adds numbers together (also used for concatenation)-
Subtracts numbers*
Multiplies numbers**
raises a number by another. (e.g. 5**2 = 25)/
divides numbers//
divides numbers, but gets rid of anything after the decimal point in the answer%
divide numbers, but returns the remaindere.g.
To put seconds to minutes and seconds
If you want to increase a variable by a certain amount, you can do
varName += value
the + can be replaced with any operator.Comparatives
Comparatives are what are used mainly in conditional statements (they are coming next)
The Comparative operators are:
==
equal to!=
not equal to<
less than>
greater than<=
less than or equal to>=
greater than or equal to==
and!=
can be used with strings as well as ints and floats, but the others can only be used with ints/floats.When you use these, they return a Boolean value (
True
orFalse
)e.g.
Boolean Comparatives
They are:
not
or
and
These are used in relation with the Boolean values returned by the other comparatives.
not
not
will reverse the Boolean value that is put into ite.g.
if I were to put something that was
False
into a notgate
, it would returnTrue
or
Used to compare two Boolean values.
If either of the Boolean values are
True
, then it will returnTrue
.and
Used to compare two Boolean values.
If both of the Boolean values are
True
, then it will returnTrue
.Examples
Note:
Don't do this
You need to do
Conditional Statements (if, elif, else)
You will find at least one conditional statement in all python programs, so it is important that you understand what they do.
Basically, the 'take in' Boolean values/statements and will only run if that statement is
True
This is where you will get introduced to the very important concept of indentation.
A simple if statement will look something like:
Here, you can see the comparative being used, which will return true if
num
equalsnum2
. Any code on the same indentation level as the comment, will only run if that expression idTrue
.Another example is:
With
if
, you can useelse
. What this basically does is the code after the else (indented) will only be run if the if statement above isFalse
e.g.
As you can see, the
else
is on the same indentation level as theif
.With
if
, you can also useelif
(short for else if). The code after theelif
statement will only run if the previousif
/elif
statement isFalse
and the elif statement isTrue
.e.g.
While Loop
A while loop is something that will repeat (loop) the code on the next indentation level underneath the initial statement until the statement is
True
.I feel like the best way to learn this is through an example.
e.g.
So in this example, if the password variable (user input) does not equal the string 'password123': the loop will run. The user is then asked for the password again. The password variable is then overwritten with the new input from the user. The statement is then asked again, if they input 'password123'. If the get it wrong again, then the loop will repeat until they get it correct. If they get it correct, then the loop will not run again and the code will be run as usual from the line after the last indented line in the loop.
String Manipulation
Strings have properties called indices (sing. index). Indices are just a position in a string.
The first character in a string is at index 0
The second character in a string is at index 1
How to use
If you want to see what character is at a certain index, you write the variable and in square brackets, write the number of the index.
Also, you can go backwards in a list by using a negative index. (-1 is the last character in the list)
e.g.
You can find ranges of indices in strings like this:
This will print 'llo Wo' (it prints from index 2 until index 7 (8-1))
If you want to find all the characters up to a certain point, then do
string[:num]
wherenum
is the index of the first index that you don't want.If you want to find all the characters after a certain point, then do
string[num:]
wherenum
is the index of the first index that you want.There are lots of built in functions for strings, but I only use a few (you can find the others using google)
len(varName)
returns the length of the stringOh, lol that is the only string function that I use :)
You can find others here
Lists
A list is something that contains multiple, strings or other data types. They are sometime called arrays.
A list looks like this:
It is defined by the square brackets, and the commas between the elements.
They use the same index system as strings do (yay!)
How to see if something is in a list
It is nice and simple, just write:
(this also works with strings)
You can do lots of things with lists. See image. Or go here and scroll down to near the bottom.
For Loops
A for loop is a loop that will loop a certain amount of times (depending on what you tell it to do)
how to make a for loop:
First you need to write
for
, then you will need to make up a variable name that will be changed every time it loops (you'll see).Then you will need to say what/how many times to loop [through]. You do this with the keyword
in
This needs to be done with examples, there is no way that I will be able to explain this clearly without them.
How that example works.
I assume if you have read the rest of the post you will no what the rest of it does except the for loop.
So, a new variable called elements is made. Every time a loop is completed, it changes to the next element in the list
colours
.Then it adds that list element to a variable (which was defined outside the loop) with a space in a string. Once it has looped/integrated through all of the elements in the list, it will not loop again and it will print the variable
text
This also works in the same way with strings.
Now, another way of using for loops, is with the
range()
function.Again, an example is easier than straight up explanation.
This will print 'Hello World' 10 times.
How it works:
Look at the numbers in the brackets, the first tells it what number the variable
loops
should start at. The second number, is what number (not inclusive) that theloops
will get to before the loop stops. The last number is the increment/step that the variableloops
is increased by each loop.To see it in another example, here is something that will print even numbers from 20-30:
Here it starts at 20, ends on 30 and steps by 2.
Note:
You can also have negative steps
e.g.
for num in range (30, 19, -2):
Bu default, step is 1 and the start value is 0. So if you just want to loop ten times you can just write:
for num in range(10):
Standard Libraries
A library is some extra functions that you need to import into your code to use
How to import and use a library
Write:
import libraryName
then:
libraryName.libraryFunction()
or
from libraryName import libraryFunction
then:
libraryFunction()
Time library
The main functions in the time library (that I use) are:
time() and sleep()
time(): This will return the amount of time that has passed since 12:00AM 1st January 1970 (in seconds)
It is usually used to see how much time has passed between 2 points by having a variable with a start time and one for an end time. You then subtract end by start to get the time passed.
sleep(): Pauses the program for a certain amount of seconds (write the number of seconds in the brackets)
Random library
The main functions in the random library (that I use) are:
randint() and choice()
randint(num1, num2): chooses a random number between num1 and num2
choice() chooses a random element in a list (write the list/variable with the list in, in the brackets)
Math library
The main functions that I use in the math library are:
sqrt(), pi, floor(), ceil()
sqrt(): Square roots the number in the brackets
pi: the number pi
floor(): rounds down the float in the brackets
ceil(): rounds up the float in the brackets
THAT'S THE END!!!
Please tell me about the inevitable typos and errors that there will be :)
very useful for beginners
@DSAEvan thanks!