How to Python (GCSE/basics)

By CodingCactus

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:

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

In python, you have different 'types' of data. This means that the way that they are used/handled is different.

There are 4 main different data types:

How to make them


Concatenation

Concatenation is where you combine strings together.

This is where data types are important. If you try to concatenate something which isn't a string, you will get an error.

How to do

To concatenate something, just simply put a + between them.

e.g.

print("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.
So how are you supposed to print a number with a string?

It is pretty simple, just turn the number into a string.

e.g.

print("Python is " + str(31) + " years old")

That will convert the int into a string, which means that it can be concatenated successfully with the other strings.

Obviously, for this example, we could just do:

print("Python is 31 years old")


Variables

A variable is a 'thing' that holds information for use later 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 data that it holds (so not just 'a' or 'b' or something like that)

And something is the piece of data that you want the variable to hold (i.e. an an int, string etc.).

e.g.

age = 31
print(age)

Here, a variable is being made, called 'age', the int value '31' is then assigned to that variable.

The data stored in 'age' is then printed, which is '31'

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 data stored in it to be used.

e.g.

age = 14
print("Python is " + 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 = 31
print("Python is " + str(age) + " years old")
age = age + 1
# age is now 32
print("Next year Python will be " + str(age) + " 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 an appropriate string telling them what to input.

Normally, you will save their input to a variable, to do that all we need to write is varName = input(prompt).

The input's data type will default to a string, but if you want to use their input in calculations, then you can do: int(input(prompt)) or float(input(prompt)) depending on what data type you want.

Be aware, that if you are doing int(input(prompt)) that if they were to input something other than an int (string, float etc.) then you will get an error.

e.g.

name = input("Enter name: ")
age = input("Enter age: ")
print("Hello " + name + ", you are " + age + " years old!")

Operators

Operators are the symbols that are used to perform mathematic calculations.

They are:

e.g.

To put seconds into 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 + "mins " + seconds + "secs")

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, as they return the boolean values of True or False.

The Comparative operators are:

== and != can be used with strings and bools as well as other data types, but the others can only be used with ints and floats.

When you use these, they return a boolean value of 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 for assigning variables.


Boolean Comparatives

They are used with the boolean values that are returned by other comparatives.

They are:

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


Conditional Statements (if, elif, else)

You will almost always need a Conditional Statement in your Python program, so it is very important that you understand what they do and how they work.

We use things called 'if statements' to check if a certain piece of code should be run.

Indentation is very important in Python, extremely important here.

Basically, they will normally have a form of comparative statement and if that statement is True, the indented code below will be run.

A simple if statement will look something like:

if num == num2:
# do something

Here you can see that a comparative is being used, which will return a Boolean value depending on what is stored in the variables.

The code on the indented lines below will only run if the expression is True.

Another example:

secretNum = 14
guess = int(input("Enter a number: "))
if guess == secretNum:
print("You guessed the secret number correctly!")

Don't do this:

if num == 5 or 7 or 24:

You need to do:

if num == 5 or num == 7 or num == 24:

With if, you can use else. Basically, the code on the indented lines underneath an else statement will only be run if the if statement above (on same indentation level as else) is False.

e.g.

secretNum = 14
guess = int(input("Enter a number: "))

if guess == secretNum:
print("You guessed the secret number correctly!")

else:
print("Sorry, you were incorrect")

As well as else, there is also something called elif.

The code on the indented lines below the elif statement is only run if the elif/if above it (on same indentation) is False. You can think of it like an else with a conditional statement.

e.g.

secretNum = 14
guess = int(input("Enter a number: "))

if guess == secretNum:
print("You guessed the secret number correctly!")

elif guess >= secretNum - 10 and guess < secretNum:
print("Sorry, you were just beneath it.")

elif guess <= secretNum + 10 and guess > secretNum:
print("Sorry, you were just above it.")

else:
print("Sorry, you were incorrect")

Make sure that you don't forget the indents or the : at the end of the statement.


While Loop

A while loop is something that will repeat (loop) the code indented below it while the while statement is True.

e.g.

password = input("Enter password: ")
while password != "password123":
password = input("Invalid. Enter password: ")
print("logged in")

String Manipulation

You can manipulate strings using the positions of the characters in them. These positions are called indices (sing. index).

The first character in a string is at index 0.

The second character in a string is at index 1 and so on.

The last character is at -1.

The second to last character is at -2 and so on.

How to use

If you want to see what character is at a certain index, what you do, is you write the variable name with the string in (or the string itself) and after it, you put the index that you want to look at, in square brackets.

e.g.

string = "Hello World"
print(string[4]) # prints the letter 'o'
print(string[-3]) # prints the letter 'r'

You can also find the letters between a range of indices

e.g.

string = "Hello World"
print(string[2:8]) # prints the string 'llo Wo' (from index 2 to index 8 but not including 8)

Please note that when using the range of indices, that the last index in your selection is not included. If you had: print(string[1:4]) then it would print from the index 1, up to but not including index 4.

If you wanted all of the characters before a certain index, then you would write: string[:num] where num is the index of the fist index that you don't want

If you want to find all the characters after a certain index, then you write: string[num:] where num is the index of the first index that you want.


There are lots of built in string functions.

An example is the len() function, which returns the number of characters (including spaces) in the string in its brackets.

You can also find some string methods here.


Lists

A list is something that can hold multiple pieces of data in one variable.

An example of a list is:

colours = ["red", "green", "blue"]

To make a list, all you need to do is, inside some square brackets, write your elements separated by commas.

How to check if something is in a list

All you need to do, is write:

if "green" in colours:
print("The string 'green' is at least 1 of the elements in that list")

That will also work with strings

All of the index things that wok for strings, work with lists (see string manipulation here).


For Loops

A for loop is a loop that will repeat a certain amount of times, depending on how you are using it.

How to make a for loop:

First, you need to write for, then you will to to make up a variable name (that isn't already being used) which will be changed every time it completes a loop.

You will then need to specify how may times it will loop.

There are 2 ways to do this:

The first is with the keyword in.

This is pretty difficult to explain in words, so here is an example:

colours = ["green", "red", "blue"]
for element in colours:
print(element)

Firstly, we are making a list (works with strings as well) called colours, with some strings with colours in.

Next, we have our for loop. What is happening, is that we have a variable called element being made and every time that the for loop repeats, that variable (element) will become the next element in the list called colours.

It will then print what is stored in the variable 'element', which in this case, will be: 'green' on the first loop, 'red' on the second loop and 'blue' on the third loop.

Once it reaches the end of the list, it will stop looping.


The next way to use a for loop is with the in range function

An example of this is:

for loops in range(1,11,1):
print("Hello World")

This code above will print 'Hello World' 10 times.

How it works:

A variable is made again, like you always must when using a for loop.

Then the number in the brackets are looked at.

The first number in the brackets is what the variable 'loops' will start at.

The second number is up to what value the variable 'loops' will reach.

The third number is by how much the variable 'loops' will change every loop.


Another example:

for num in range(20, 31, 2):
print(num)

This will count the even numbers from 20-31, because the first number is 20, the end number is 31, and it steps by 2.

You can also have negative steps
e.g. for num in range(30, 19, -2):

By default, the step is 1 and the start value is 0, so if you wanted to loop 10 times you could just write:

for num in range(10):

Standard Libraries

Libraries are things which you can import, so that you can do extra things in/with your code.

How to import and use a library

There are 2 ways to use a library.

Firstly, you can do this:

import libraryName

And then when you want to use it:

libraryName.libraryFunction()

The other way is:

from libraryName import libraryFunction

And then when you want to use it:

libraryFunction()

Time library

The main functions in the time library are:

time() and sleep()

time() will return the amount of time that has passed since 12:00AM 1st January 1970. Normally used to find the amount of time that has passed between 2 points.

sleep() pauses the program for the number of seconds in the brackets.

Random library

Main functions 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 in the brackets).

Math library

The main functions are sqrt(), floor() and ceil()

sqrt() will square root the number in the brackets.

floor() will round down the float in the brackets.

ceil() will round up the float in the brackets.