Skip to content
← Back to Community
How to python (GCSE/The Basics)
Profile icon
h
has Hacker Plan
CodingCactus

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
  • 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)

e.g.

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


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 False and 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 :)

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:

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

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 :)

Voters
Profile icon
TinTin212
Profile icon
HarshitaBajpai
Profile icon
AsaUeno
Profile icon
AranAranB
Profile icon
LucasMitchell5
Profile icon
ravsangha
Profile icon
YOELMIGARCIA
Profile icon
BrunoRipper
Profile icon
DragonKing11
Profile icon
elizabethduffy
Comments
hotnewtop
Profile icon
KobeFF

I swear, @CodingCactus you're DEFINETLY going to get the content creator role...

Profile icon
morganny16

I agree @KobeFF this tutorial really helped me with my recent python assignment

Profile icon
KobeFF
Profile icon
amasad
Profile icon
CodingCactus

wow thank you sooooo much @amasad!!!!!!

Profile icon
Wilke000

Congrats @CodingCactus!!

Profile icon
lariyaabubakar

@CodingCactus Hey, what does it means being a content creator?

Not trynna be rude or anything just wanted to know

and congratulation!

Profile icon
CodingCactus

@lariyaabubakar I just think it is when you make a good tutorial?

Profile icon
Wilke000

It means that he
image(Creates awesome tutorials and templates for repl.it) @lariyaabubakar and @CodingCactus (sorry about the zoom window in the corner, I'm doing a zoom meeting right now)

Profile icon
[deleted]

@Wilke000 oh u naughty boi being on replit during zoom

Profile icon
Wilke000

:)

Profile icon
SixBeeps

Dang, the GCSE does Python? The more you know.

Profile icon
CodingCactus
Profile icon
CodingCactus

If anyone is interested, here are the post's, stats
image

and if you want to see the markdown that is used https://repl.it/@CodingCactus/How-to-python

Profile icon
Vochong

This has been tremendously helpful. Thank you!

Profile icon
codingduck

all variables before the "dont start variables with caps" are capitalized lol

Profile icon
CodingCactus

@codingduck ye, ms word auto capitalises stuff lol, i'll change it

Profile icon
LincolnMiddle

very useful for beginners

Profile icon
CodingCactus

@DSAEvan thanks!

Profile icon
HahaYes

YOU WANT ME TO GRAMMAR POLICE THIS

Profile icon
CodingCactus

@HahaYes lol, if you're up to the challenge
:D

Profile icon
HahaYes

@CodingCactus Yeah why not I better get a cycle though

Profile icon
CodingCactus

@HahaYes of course!!

Profile icon
HahaYes
Profile icon
Bookie0

WOOOOOOOW so long! I’m gonna learn from this because this is more complex than I know!

Profile icon
CodingCactus

@Bookie0 lol It took a large amount of time!!

Profile icon
Bookie0

( ͡° ͜ʖ ͡°) @CodingCactus

Profile icon
Kingworm2089

Hehehe

Profile icon
osmund94

very helpful for beginners!

Profile icon
HahaYes

@CodingCactus Whoa, this has exactly 100 upvotes! Yayyyyyy

Profile icon
Abhiram9

It's good

Profile icon
YeasinArafatAra

Thanks for this

Profile icon
17lwinn

this is why im glad i chose GCSE computer science

Profile icon
DigitCommander

Awesome, and very helpful! Thanks for the info!

Profile icon
DungeonMaster00

found a typo

"Concatenation I where you 'stick together' some strings."

"I" should be turned into "is"

Profile icon
CoolJames1610

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

Profile icon
CodingCactus

@CoolJames1610 I'm making it into a website

Profile icon
CoolJames1610

ooh nice! tell me when you do! :D @CodingCactus

Profile icon
[deleted]

You have a lot of freetime CODINGCACTUS!

my unt sin say for me ur the best coder in repl.it
Profile icon
AndreySloan

@CodingCactus can you make more python tutorials like this?

Profile icon
CodingCactus

@AndreySloan well, to be honest, if you know all of this, then you can pretty much do most things. The thing is, the only other thing that I know that isn't on this, is 2d arrays and I'm able to do most things using python without them

Profile icon
AndreySloan

@CodingCactus Ok thank you!

Profile icon
GarretThyCarrot

Wow this is super cool! I love it! I’m gonna learn so much from this! Thank you!
This carrot 🥕 likes this a lot!

Profile icon
jeremykyleisgod

the randint code doesn't work for me I have tried but it might be something to do with the online tutorial I followed before I came here @CodingCactus please do a quick summary for how to use randint commands

Profile icon
CodingCactus

@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 :)

Profile icon
jeremykyleisgod

@CodingCactus thanks I did some research 2 o 3 days ago and finally found it. this explanation has helped me understand it further though so thank you!

Profile icon
grace97464

:)

Profile icon
jeremykyleisgod

it woul of been funny if you spelt any thing on the last line incorrectly

Profile icon
jeremykyleisgod

how do i create a random number generator that loops 6 times from 0-50 and 2 times from 1-12

Profile icon
3mmarald

This tutorial is AMAZING, it's my first on this site (and the first time I have used python), and I found it intuitive and easy to use

Profile icon
CodingCactus

@MoziBeast123 I'm glad you like it!

Profile icon
jeremykyleisgod

the while loop doesn't work for me please explain why

Profile icon
CodingCactus

@jeremykyleisgod what are you trying to do with it?

Profile icon
jeremykyleisgod

@CodingCactus do you remember that code breaker game I want to make a loop so if you get the answer wrong it keeps looping until you get it right

Profile icon
[deleted]

Anybody can help me with this assignment: Repl.it post

Profile icon
[deleted]

Anybody can help me with this assignment: Repl.it post

Profile icon
CodingGoose

I didn't know GCSE does python

Profile icon
jeremykyleisgod

@DannyIsCoding yeah and I should be fun but well it would be if I had a damn teacher who would teach it we just did online work and some people had to teach others about coding

Profile icon
k9chelsea2

yep this is pretty useful I am learning computer science and I wish I had read this tutorial before I started