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))
- The print function
- Data Types
- Input Function
- Boolean Comparatives
- Conditional Statements (if, elif, else)
- While loop
- String Manipulation
- For Loops
- Standard Libraries
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
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).
print("Hello World") # This is a comment # The code above will output Hello World
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.
- int = A whole number. e.g.
- float = A decimal value e.g.
- bool = A Boolean value.
How to make them:
- string = anything with
"around it is a string
- int = an integer (whole number) with no
- float = an decimal value without
- bool =
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.
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.
So, how do you print a number with a string?
It is simple actually, just turn it into a string
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")
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
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)
age = 14
There are a few key rules when naming variables.
- 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.
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.
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
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
float(input(prompt)) depending on what data type you want.
name = input("What is your name? ") age = input("Enter age: ") print("Hello " + name + ", you are " + age + " years old!")
Operators are basically the symbols used in maths.
+Adds numbers together (also used for concatenation)
**raises a number by another. (e.g. 5**2 = 25)
//divides numbers, but gets rid of anything after the decimal point in the answer
%divide numbers, but returns the remainder
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 are what are used mainly in conditional statements (they are coming next)
The Comparative operators are:
!=not equal to
<=less than or equal to
>=greater than or equal to
!= 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 (
1 == 1 #True 15 != 15 #False 17 <17 #False 21 >= 12 #True 14 > -12 #True 23 <= 23 #True
Make sure that you use
==for equal to,
=is just used for assigning variables
These are used in relation with the Boolean values returned by the other comparatives.
not will reverse the Boolean value that is put into it
if I were to put something that was
False into a not
gate, it would return
Used to compare two Boolean values.
If either of the Boolean values are
True, then it will return
Used to compare two Boolean values.
If both of the Boolean values are
True, then it will return
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
Don't do this
if num == 5 or 7 or 24:
You need to do
if num == 5 or num == 7 or num == 24
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
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
num2. Any code on the same indentation level as the comment, will only run if that expression id
Another example is:
secretNum = 14 if int(input("Enter a number: ")) == secretNum: print("You correctly guessed the secret number")
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
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, you can also use
elif (short for else if). The code after the
elif statement will only run if the previous
elif statement is
False and the elif statement is
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
A while loop is something that will repeat (loop) the code on the next indentation level underneath the initial statement until the statement is
I feel like the best way to learn this is through an example.
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.
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)
string = "Hello World" print(string) #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
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
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 :)
You can find others here
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.
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
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
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
This also works in the same way with strings.
Now, another way of using for loops, is with the
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.
You can also have negative steps
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):
A library is some extra functions that you need to import into your code to use
How to import and use a library
from libraryName import libraryFunction
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)
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)
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 :)
print("This is amazing, I'm doing Python in YR10 now. I know most of these but this is still a great REFERENCE! Can you make it into a book XD")
This is amazing, I'm doing Python in YR10 now. I know most of these but this is still a great REFERENCE! Can you make it into a book XD
You have a lot of freetime CODINGCACTUS!
my unt sin say for me ur the best coder in repl.it
@jeremykyleisgod here is an example:
import random num1 = random.randint(1,10) print(num1)
what this will do, is it will get a random number between 1 and 10 (inclusive) and save it to a variable called
num1 it will then print the variable
num1. You change the numbers in the brackets top the range that you want. e.g. between 1 and 50 will be
random.randint(1,50) hope this is what you wanted :)