Basic Python Tutorial

This is an article for a friend who is learning Python from scratch. I will be adding to it over the next few weeks when I have time.

If you are using Python on Windows, use the install here. I would also recommend downloading Visual Studio here. It is an IDE which will give you some tips as you go along. After installing, go to the extensions on the top left of the screen and install the Python extension.

Extensions is the fifth icon down

Very Basic Python

A few basic functions:

  • print() will write whatever is in the brackets to the screen. Eg print(10) would appear as 10 on the screen.
  • # the hashtag sign on Python is the for commenting. It means that the program won’t read whatever is after the hashtag on that line.

Variables

When coding, data is assigned is to words or letter with the use of variables. A variable is way of storing and referencing that data within a piece on code. Variables are assigned on Python using the equals sign. Think of this as writing data to that variable name.

x = 10
y = 15
z = x + y 
print(z)

If you ran this program, it would print 25 to screen, as the x stores the value of 10 and y stores the value of 15.

Rules with variable names:

  • They can contain letters, numbers and underscores. They must have no spaces. They can contain numbers but must not start with one.
  • When referencing a variable you must spell it correctly.

Data Types

When the computer stores the data, it must know what type the data is. But what is a data type? Data can take a variety of different forms. Example: the ball was red and 10.0cm in radius are two bits of data about the ball, but one is a word and one is a value. The ball being red is a piece of string type piece of data. A string is a sequence of letters, numbers or characters which make up a word or a sentence. The radius of the ball is what is known as a ‘float’ value. This simply means a number with a decimal after it.

Numbers can be stored in a variety of ways on Python, depending on what they are being used for. Luckily, Python will automatically handle most of that for you. It is however worth being aware of, as some functions, such as indexing, will require a certain data type. You will also need to specify the data type before taking user inputs.

Data TypeUse
IntegerStores whole numbers. Ie no decimal point. Convert a variable to an integer using int().
FloatStores decimal numbers with a decimal. Convert to a float using float()
StringStores words or sentences as an array of characters. Eg “hello word”. Create a string variable by putting the letters or words you want to assign to it inside quotation marks.
BooleanThis stores True or False values.
The most basic and important data types

Basic operators

When running a program you will most likely need to do some maths. Below are the basic maths operators on Python:

OperatorUse
+Addition. Will add together whatever is either side of it. Eg z = 10 + 10 will give z a value of 20.
Subtraction. Same as addition but will subtract instead.
*Multiplication
** Exponentiation (powers). Eg 2**2 = 4. It will raise the number before it to the number after it.
/Division will divide whatever is before it by whatever is after it
%Modular division. Will return an integer with no decimal or remainder. Eg 4%3 = 1, 7%3 = 2, 15%2 = 7
// Remainder of the division. Eg 4//3 = 1, 7//3 = 1, 15//4 = 3

if statements

In order to write a useful program, you will most likely have to check some conditions whilst you are running it. To do this you will use an if statement. It does what it says on the tin, it checks whether something is true and if so it will run the code in the indentation below. I am aware I have not mentioned indentation yet, but I will cover that in the next section.

To write an if statement, you first need to be able turn what you are checking for into a true or false statement. For example, if I was writing a program where I checked whether someone was tall enough to go on a ride at theme park, I would write:

height = int(input("Enter your height here: "))
minHeightForRide = 150

if height > minHeightForRide :
      print("You are allowed on the ride")
else: 
      print("Sorry, you are too short")

As you can see, being tall enough to ride the ride is turned into a true or false statement. If height is greater than the minimum height for the ride, it will run the code within the indentation below.

I am aware I have added a few levels of complexity here, so I will cover them one by one.

  • Indentation: code is broken up into blocks on Python using indentation. Below an if statement, the block of code that will only run conditionally is below until the indentation returns to the same level as the if statement. The code that would run is highlighted below in red. As you can see it is all the code until the else statement, as that is on the same level of indentation as the if.
height = int(input("Enter your height here: "))
minHeightForRide = 150

if height > minHeightForRide :
      print("You are allowed on the ride")
      # any code here would also be run conditionally if the
        if statement returned a true
else: 
      print("Sorry, you are too short")
  • Else: this is a pretty simple bit of code. An else statement must come after an if statement and will only run if the if statement is not true. In this case, it will only run if the height is less than the minimum height for a ride.
  • User input: int(input(“Whatever”)) will print “Whatever” to the screen and wait for the user to type and enter something. The int() around the input specifies it will take an integer input.
  • Colon: after writing an if statement or any code that will have an indented block after, use a colon to initialise the initialise the block.

Elif: It is not used here, but elif is short for else if. Like else, it must be paired with an if statement and will only run if the original if statement is false. Unlike else, it has a condition. For example, we want to add a feature to the above code that recommends another ride if the rider is above 140cm, but it only wants recommend it if they are too short for the current ride.

height = int(input("Enter your height here: "))
minHeightForRide = 150

if height > minHeightForRide :
      print("You are allowed on the ride")
      # any code here would also be run conditionally if the
        if statement returned a true
elif height > 140 :
      print("Sorry, you are too short for this ride, but you                                                 nn    are tall enough for ride X")
else: 
      print("Sorry, you are too short")

This will only run the code if height is between 140 and 150, as if it is more than 150 it will trigger the first if statement.

Comparators. In order to write if statements you must have a way of comparing data. This is done by these comparators.

ComparatorUse
==Checks if two pieces of data are equal
>=Greater of equal to
>Greater than
<= Less than or equal
<Less than
!=Checks if two bits of data are not the same

Lists

When coding you will often be dealing with lots of pieces of related data. You will therefore need a way to store that data. A list is a data structure which can store multiple values under one variable name. It will store them in a specific order such that each piece of data can be accessed with an index number.

Data in a list is separated by commas and stored within square brackets:

heights = [180, 170, 175, 140]

To access a value within a list, you use the variable name with square brackets around the number that the piece of data you want to access is within the list. NOTE: indexing on Python starts at 0, not 1.

heights[0] # This would be 180
heights[3] # This would be 140

You can also change values in the list using =

heights[0] = 170
print(heights)

This would give:

[170, 170, 175, 140]

It is often very useful to add values to lists, so that data can be stored. To do this, use the append function. This adds a value to the end of the list

heights.append(165)
print(heights)

This would give:

[170, 170, 175, 140, 165]

Looping

When programming, you will normally loop over a bit of code until you achieve a certain goal. There are two types of loop on Python: for loops and while loops. A for loop is used when the number of iterations that the code will need to do is already known. A while loop is used when the number of iterations required is unknown. It will run until a certain condition is no longer met.

Some examples:

  • You want to check each element in a list to see if is greater or smaller than a known value. You would use a for loop. You know how many elements there are in the list and therefore how many iterations there will be.
  • You are simulating a ball being thrown in the air and want to run the simulation until it hits the ground. You would use a while loop as you don’t know how many iterations it will take for it to hit the ground.

While loops

While loops will repeat code until a condition is met. This is best displayed by an example.

fibonacci = [0,1]
while fibonacci[-1] < 1000:
    nextNumber = fibonacci[-2] + fibonacci[-1]
    fibonacci.append(nextNumber)

This code will print return a list of Fibonacci numbers up to the first number over 1000. It has added levels of complexity. As you can see, it will repeat the code will fibonacci[-1] is less than 1000. But what does this mean? Negative numbers start indexing from the other end of the list, so fibonacci[-1] will return the last element in the list. It will therefore repeat the iterations until the last element in the list is greater than 1000. It returns:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

For loops

For loops are used when the numbers of iterations that will be required is known. For example, we want to check if any of the Fibonacci numbers in the list above are multiples of 3. There are two ways of doing this, I will show both for understanding.

for i in range(0,len(fibonacci)):
    remainder = fibonacci[i]//3
    if remainder == 0:
       print(fibonacci[i])

This for loop will increase the value of i by one each iteration until it is equal to the len(fibonacci). This is returns the length of the fibonacci list. This will therefore check every element in the list.

for number in fibonacci:
    remainder = number//3
    if remainder == 0:
       print(number)

This is a nice feature of Python. This will make number equal to the next element in the array with each iteration.