Skip to the content.

After your first steps with Python

At the TechJams you can get started with the Python programing language by working through some of our pre-prepared exercises. In these exercises you will have used things like variables, functions and control flow but you might not have realised what these can do. As you take on your own projects it will really help if you understand these things a little more so that you can use them yourself.

This guide includes:

The sections have some simple explanations and examples, reminders of some common problems, exercises to try and where you can learn more when you are ready.

Using a Python workspace

Practising is better than just reading so use this section to find a place to practice your Python.

Raspberry Pi

Thonny is usually already installed and can be used for these exercises

PC

You can install Thonny on a PC or search for ‘Python’ in your PC’s App Store

Web

There are quite a few online Python editors available. You can search for one yourself or just try Programiz

Remembering and naming things

Variables are a way for your programs to remember or save information and give them a name so that they are easier to use. Here is an example:

number_of_columns = 10

This makes a variable called “number_of_columns” and saves the number 10 in it. If you need the number of columns somewhere in your programme you can use this variable. For example:

for next_column in range(number_of_columns):
  ...

or

number_of_cells = number_of_columns * number_of_rows

The simplest way to make a variable is with an assignment statement that follows this pattern

variable_name = value_to_remember

Later we will see that other statements can create special variables. For example, the code we saw earlier:

for next_column in range(number_of_columns):

This makes a special variable called “next_column” which we can use inside the “for” loop.

Common problems with variables

Python won’t understand your program if you try to put spaces in your variable names. You can use these tricks so your variable names don’t have spaces:

use_underscores_instead_of_spaces
pushallthewordstogether # but this is hard to read
useCapitalLetters

Python can get confused if you use a variable name that is already used for something else e.g. print, for, import.

When you use a variable name you must match it exactly. Python won’t understand if you use capital letters in one place and not the other. For example:

myVariable = 10
print(myvariable) # Python won't work out that you meant to have a capital V

Practice with variables

Use a python editor to try these exercises:

Learning more about variables

There is lots more to learn about variables. You can search for more help online or just look at w3schools.

Once you feel ok with variables you can learn more about data and types of data in Python.

Python has modules you can import for more complex data structures but these are probably for quite advanced programers.

Small helper programs

Functions are small programs which help you make bigger, more complicated programmes. You will have already used some functions that are built into Python or added in with an import. You can also make these yourself. Here is a simple example:

def double_it(original_value):
  new_value = original_value * 2
  return new_value

This makes a function called “double_it” which takes one input, doubles it and returns the result. Once we have told Python about our helper programme we can use it in lots of different ways. Here are some examples:

print(double_it(5)) # Will print the number 10
child=1.4
giant=double_it(child) # Uses a variable as the input and puts the result in a variable

When you try this yourself notice that the block of code inside the function doesn’t run when you define the function. At the define stage Python just remebers the function for later. When you use the function later, Python remembers the definition and runs that block of code then. If this doesn’t make sense try some of practice challenges and add in some print commands and watch when they appear.

All function definitions follow a similar pattern.

def function_name (names_of_parameter):
  line of code
  line of code #lines of code inside the function
  line of code
  return some_value

line of code # this code is not part of the function

Some things to notice:

Here are some more helper functions which shows we can make helper functions using other functions.

def multiplyer(first_value, second_value):
  return first_value * second_value

def triple_it(input_value):
  return multiplyer(input_value, 3)

Common problems with functions:

Practice with functions

Use a Python editor to try these exercises:

Learning more about functions

There is lots more to learn about functions. You can search for more help online or just look at w3schools.

There are other sorts of subprogram in Python but make sure you are really confident with basic functions first. When you are ready look at modules, classes and lambdas

Writing less code and reacting to events

When you write a program Python will normally perform each line in sequence.

line of code # 1st step
line of code # 2nd step
line of code # 3rd step
... # more steps

For almost any interesting program this won’t be enough on its own. Here are some reasons:

Python gives you ways to change the flow of the program so that you can make your code easier to read, quicker to write and react to events. These are sometimes called control structures. The main structures are:

It is normal to use all of these structures in your program.

Switching between different bits of code

Your program can do different things in different circumstances. Here is a simple example.

your_age = int(input("Enter someone's age:"))
print('You have entered: ', your_age)
if your_age < 16:
    print('A responsible adult needs to stay with them at a TechJam')
print('Thank you')

The second print command is in a branch of code. The if statement tells Python to check the value saved in the variable your_age and only uses the branch if the value is less than 16. Otherwise, Python skips past the branch and carries on. You tell Python which lines are part of the branch by indenting them (shifting right).

Here is a slightly different example with two branches.

your_age = int(input("Enter someone's age:"))
print('You have entered: ', your_age)
if your_age < 16:
    print('A responsible adult needs to stay with them at a TechJam')
else:
    print('They can stay at TechJam on their own, but only if they act responsibly!')
print('Thank you')

You can have lots of branches. Here is an example with three.

your_age = int(input("Enter someone's age:"))
print('You have entered: ', your_age)
if your_age == 0:
    print('Are you sure? They might be a little too young for TechJam')
elif your_age < 16:
    print('A responsible adult needs to stay with them at a TechJam')
else:
    print('They can stay at TechJam on their own, but only if they act responsibly!')
print('Thank you')

Things to note:

You can have any number of lines of code in each branch. Just like for functions you use indents (shift the line to the right) so that Python can see where each branch starts and finishes.

Common problems with branches:

Practice with branches

Try out the example branches in your Python editor and change them to see what happens. Here are some extra things to try:

Learn more about branches

There is lots more to learn about branches. You can search online or look at W3Schools

There are some more advanced kinds of branches to investigate. Make sure you can use basic if-statements first. When you are ready have a look for match ... case statements and try ... except statements.

Repeating code many times

If you are working with lots of information it is easy to have boring repetitive code like this.

# Clear all the LEDs in the LED strip
LEDStrip[0]=(0,0,0)
LEDStrip[1]=(0,0,0)
LEDStrip[2]=(0,0,0)
... # lots more similar lines
LEDStrip[199]=(0,0,0)

If you look carefully, each line is the same except for the index (the number inside the [] brackets). We have already learnt about helper functions but, in this case it doesn’t save us much effort. Here is an example.

# Clear one LED in the LED strip
def clear(LED_num):
    LEDStrip[LED_num]=(0,0,0)

# Clear all the LEDs in the LED Strip
clear(0)
clear(1)
clear(2)
... # lots of similar lines
clear(199)

For this kind of repetition we can use a Python loop instead. Here is the same program using a for loop.

# Clear all the LEDs in the LED strip
for LED_num in range(200):
    LEDStrip[LED_num]=(0,0,0)

Things to note:

We don’t have to use range in our loops and we aren’t limited to lists of numbers but for with a range is a very common pattern you will notice quite a lot.

Here is another type of loop we can use in Python which is introduced with the key word while. This example looks different to the for loop but does exactly the same job.

LED_num = 0
while LED_num < 200:
    LEDStrip[LED_num]=(0,0,0)
    LED_num = LED_num+1

Some things to note:

In this example the for version is a bit easier than the while version. In some cases you may find the while option better. For example, if you need to step through two lists in parallel a while loop will be easier to understand than a for loop. Another example is looping forever like this.

While True: # With a capital 'T'. Not 'true'
    ... 
    ... # Repeat this block of code forever!
    ...

... # Python won't get to this code unless we do something special to 'break' out of this loop.

Common problems with loops

Common problems with loops are very similar to the ones you have already seen for branches:

Practice with loops

Try out the example loops in your Python editor:

Learn more about loops

There is lots more to learn about loops. You can search online or look at W3Schools. Look for some special key words that work with loops like break, continue, else.

There are some more advanced kinds of loops to investigate. Make sure you can use basic for and while first. When you are ready have a look for list comprehension and recursion. For advanced Python users there are also iterators and generators.

Mixing controls for big and complex programs

Functions, branches and loops are useful on their own but are even more powerful when used together. Earlier we saw how we could use a loop to control lots of LEDs at once. Putting the loop inside a function can make it even easier to use.

# Function to clear all the LEDs in the LED strip
def clear_LEDs(): # defines the helper function
    for LED in range(200):
        LEDStrip[LED_num]=(0,0,0)

# Clear all the LEDs in the LED strip
clear_LEDs() # Use the helper function.

Things to note:

Here is an example of using a function and a branch inside a loop.

import keyboard

while True: # Loop forever unless we do something special
    clear_LEDs() # Function used inside a loop
    ...
    ... # more code that might display a pattern
    ...
    if keyboard.read_key() == 'q': 
        # branch to break out of the loop
        break
print("Finished")

Things to note:

You can combine or ‘nest’ functions, branches and loops as much as you like but take care. It is easy to make mistakes with lots of indents. Splitting things up into helper functions makes the code much easier to manage.

Practice combining functions, branches and loops

Look at loop forever example above. Notice the last print command:

Go back to quiz game you started in the section about branches. Change your programme by mixing in functions and loops and some new branches. Add these features and make sure each one works before trying the next one. Remember to use small helper functions to keep your blocks of code small and easy to understand:

Even more practice

There are loads of online places to get more practice but please check with a responsible adult to make sure you meet any age limits and get permission for anything that has a cost. Codewars (14+ years) offers free challenges and lets you earn points and badges as you progress. You can also try a computer vision challenge we have created for TechJam