Python Workshop for Beginners

Updated 22 January 2024

Welcome to the Python Workshop, where you will learn everything you need to hit the ground running with the worlds most popular programming language Python. My name is Tim and am a passionate maker and cherish free exchange of knowledge. I have attempted to create here the most honest, best way to dip your toes into the programming realm which surrounds us in this modern life. Programming is something any modern maker should have a grasp on, and I am keen to help you sink your teeth in.

To follow along with this workshop you will need a few things. An open mind, a thinking cap, internet connection to download software and a functional computer with peripherals to type and run the codes.

Course Goals

I have created this course to enable someone with little or no prior experience with programming to feel empowered in this world and springboard into future Pythonisering confidently no matter the direction. There are also several great reference pieces throughout so someone experienced in programming will find utility in this workshop.

So by the end of this course you will be able to use Python to create fun and exciting codes. Some final scripts in this workshop will allow you to interact with real world live data and others will demonstrate graphical user interfaces to bring flair to your coding ventures.

Furthermore, this workshop will also teach you how to access the massive repositories of great Python scripts available online. The official online site alone has over a quarter of a million unique packages, all free to download, and every one improves the potential of Python. You will just have to decide what you want.

So when you are ready, let’s take the leap!

Beautiful Snake Boi

Course Outline  

- 1.0 Chapter Overview
- 1.1 Python Rundown and Main Windows
- 1.2 Hello World! First Python Script

2.0 Chapter Overview
- 2.1 Python Variables and Types
- 2.2 All the Keywords in Python!
- 2.3 All the Operators in Python! Precedence too
- 2.4 All the Built-in Functions of Python

3.0 Chapter Overview
3.1 Control Structures with Python
- 3.2 If, Elif and Else Keywords in Python
- 3.3 Loops in Python
- 3.4 Pass, Break and Continue Keywords in PythonSnaku

- 4.0 Chapter Overview
- 4.1 Making Your Own Python Functions!
- 4.2 Scope in Python
- 4.3 Import, From and As Keywords in Python
- 4.4 Installing Python Packages

5.0 Chapter Overview
- 5.1 Swell Python Scripts with the Turtle Library
- 5.2 Cool API Python Scripts
- 5.3 GUI with Tkinter in Python

- 6.0 Chapter Overview
- 6.1 Where to Find Further Knowledge and Inspiration
6.2 Where to Find Help

 

All Code created in this workshop can be downloaded by the link at the bottom of this guide. The codes will be in a zip folder which you will need to extract. Once doing so you will see all the files organised by each particular chapter and can be run by opening them using Python.

If you run into any issues throughout this Python Workshop, then please reach out to us on our Core Electronics Forum. We are full-time makers and are always here to help.


Chapter 1 - First Steps

1.0 Chapter Overview

In this chapter what is Python, how to install it, other ways to access it, what interfaces does it provide for you and how to go about writing your first script will all be explained. Furthermore, it will demonstrate to you exactly why Python is such a brilliant language for educators, makers and those just starting off in the coding sphere. So, come along and dip your toes into the powerhouse programming language of Python.


1.1 Python Rundown and Main Windows

This guide will be a rundown on Python, the open-source programming language built by the hugely intelligent Guido van Rossum. This guide will also contain external links to Python resources and download links. Programming is the implementation of logic to facilitate specified computing operations and functionality. Put more simply it is the process of creating instructions for a computing device to comprehend and execute. Instructions are referred to as a software program. Once the software program is executed the computing device will perform the specified task. A programming language is a set of commands, directives and other syntaxes which gives you a vocabulary to create these software programs. 

There are three main Python screens. These are Python Command-Line Shell, Python IDLE Shell and Python Program Window. You will be able to open these after completing installing Python onto your computing device.

 

 

Python Interfaces

 

For Deeper Information Click Here


1.2 Hello World! First Python Script

For those just starting, looking at the Python Program Window the potentials can seem immense. It can leave you wondering just how exactly do I begin my Python journey? The answer to this, my dear reader, is by writing a 'Hello World' script. So let us dive right in and start learning Python! This guide will be a dive into what these programming files are saved as and also give an analysis of the code. Furthermore, it will introduce the concept of variables, strings and commands.

The code written below is the same code done in the video. This code can also be downloaded using the link at the bottom of this page. This script demonstrates a number of different ways to use the print function in Python. A function is a block of organized, reusable code that is used to perform a single, related action that only runs when called upon. 

#Hello World! First Python Script

#Print Function is being used below to display Hello World
#What you want displayed needs to be in ' ' or " " and they need be a matching
#pair. Quotations Marks are not required if printing a number.


# (1) Simplest example of print function.
print('Hello World!')


# (2) Print function method of pulling two strings variables and printing them 
#     together.
print("Hello Again "   "World!")


# (3) Print function allowing you to separate what is printed with a paragraph
#     using \n to denote a new paragraph.
print("Hello\nOnce\nAgain\nBig\nWorld!")


# (4) Printing function method with all info displayed on one line but allows
#     a delay to be coded in between the first part and second part 
print('Guess what...', end='')
#     Right here, between these two prints you can code in a pause (perfect
#     for loading screens) 
print(' Hello World!')


# (5) Final method of printing Hello World. This uses a variable referred to
#     as x. Below we tell the computing device what the value of x is. 
x = ('Final ''Hello ''World')
#     Now the print function is used to display the variable x with an
#     Exclamation mark at the end
print(x, end='!')

Chapter 2 - Learning the Tools

2.0 Chapter Overview

Now that you know what Python is and you have successfully written your first script it is time to learn about some of the tools Python comes equipped with. Making captivating and unique code is just moments of conception away and we can do it best when we have knowledge of all the nuts and bolts. This chapter will provide great references pieces to keep you motivated throughout your daring voyages across the Python programming landscape. 


2.1 Python Variables and Types

Variables are one of the most fundamental concepts and exist in pretty much all programming languages. Variables are by no means specific to just the language of Python and they will certainly be required in most of your programming escapades. Python provides a simple and dynamic way to create variables in your code, yet it maintains a powerful type categorisation system to ensure safe operations with your data.

There is a huge variety of data types which Python can use and create variables from. Different data types allow you to do different things to the data whilst maintaining safe operation. Python will track the value of a variable, letting you access it via the identifier, and it will also track the type of the value assigned to a variable.

Now it is useful to know that variables do not need to be manually declared with any kind of variable type. To figure out what the type a variable is you can use the | type() | function in the Python Shell Window and by typing the associated indicator inside the brackets. This function is installed by default into Python. Below is a list of every single Python variable types built into the programming language and a table showing code examples of setting a variable to a specific type.

For Deeper Information Click Here


2.2 All the Keywords in Python!

This guide will introduce an overview of all keywords within Python, provide an understanding of what exactly a keyword is and how to make simple codes with them.

Keywords are the nuts and bolts vocabulary of the Python programming language. They serve as fundamental building blocks and tools for communication between you and your computing device. They form the syntax and structure of a Python software program. A keyword is a combination of letters, usually forming a word, that has a special meaning. This special meaning can be commands or parameters which will be executed as soon as the computing device encounters the keyword when the code is run. This is the reason keywords are reserved by programming languages. Reserved means they cannot be used in defining variables, classes or functions. Keywords in Python are also case sensitive.

 

For the Great Reference Table and Deeper Information Click Here


2.3 All the Operators in Python! Precedence too

This guide will provide a complete understanding of what operators within Python are. Furthermore, it will elucidate every single operator type, summarise their purposes and demonstrate to you how they can be useful in your coding ventures. Operators are used to perform operations on variables and values. Depending on what they are they can be a method of comparison, give tools for calculations or even assign values to identifiers. They can be applied to all types of data such as binary, decimal and hexadecimal values. Below is a list of the different types of operators grouped.

                - Comparison Operators
                - Arithmetic Operators
                - Assignment Operators
                - Bitwise Operators
                - Bitwise Assignment Operators
                - Logical Operators, Identity Operators and Membership Operators

Order is very important when it comes to calculations and without consistent precedence, predictable reliable results would be impossible. Python has a predilection to perform certain calculations before others when they are written on a single line of code. Python has a predilection to perform certain calculations before others when they are written on a single line of code. If a line of code is beneath another line of code the above code will always be run before it. Below is a table demonstrating this precedence.

Precedence Table

2.4 All the Built-in Functions of Python

A function in Python is a block of code which only runs when it is called. It is organised, reusable and performs a single related action. Functions are all about making it easier for the user whilst increasing modularity and improving code reusability. Python gives you many built-in functions. Built-in functions do not need to be imported and can be utilised instantly as they are installed into Python by default. We have explored print and its complexities together in previous guide, along with a few other built-in functions, but here are all of them.

The goal of this reference point is to prevent you from being sideswiped by some function that you have never heard of. Or if there is a function you have not seen you will be able to realise its not part of the default Python selection of functions. It is worth noting that it is possible to create your own personal functions. These are referred to as user-defined functions. If you are going through someone else code, particularly one that has not been commented well, you can run into user-defined functions without even realising it. Having a grasp of all the default tools available to you will keep morale and motivation high on your coding travels.

For the Great Reference Table and Deeper Information Click Here


Chapter 3 - Controlling the Flow

3.0 Chapter Overview

This chapter focuses on control flow. This is the sequence in which individual statements, instructions or functions of a software program are executed and evaluated. The control flow is also be referred to as the flow of control. Simply put, flow is a general term describing the order in which your lines of code are executed and evaluated. This flow becomes increasingly intricate as your courageous coding capers climb in complexity. By the end of this chapter you will understand the flow of control and the various tools to manage and alter it.


3.1 Control Structures with Python

This guide will introduce control structures and establish them as a fantastic tool for control flow conceptualisation. Control structures are a flowchart method to represent the flow of programming languages.

The shape of the box can represent either a command statement, a variable creation, a condition, or a decision. When drawn the flow tends to be from top to bottom and each box is connected with arrows. This you can see below left in the table. Below to the right is common scenarios of control flow visualised using these shapes.

These flowcharts are used worldwide as a method of grasping the movement of the code execution by the computing device. Once learned this knowledge will be applicable no matter what programming language you end up utilising.

Control structure tables and Generalisations

For Deeper Information Click Here


3.2 If, Elif and Else Keywords in Python

Imagine all these keywords as the traffic controllers telling the control flow where to go. By having a firm grasp on how to use these keywords effectively and efficiently you will be able to crush any programming scenario where a choice needs to be made. Making choices and decisions is a part of life. The world is continuous flux and is impermanent. Nothing is constant except for change.

The | if | keyword is a control flow statement which enables us to execute a part of the software script only when a certain condition is satisfied. The | elif | keyword is shorthand for else if. This keyword is effectively an evaluation method that asks the question - if the previous conditions were not true, then try this new condition. Then if that new condition is met the code executes this particular true branch of the software program. The | else | keyword is a catch-all method, meaning anything which is not caught by the preceding conditions the control flow will still undergo a unique branch of the software program.

For Deeper Information Click Here


3.3 Loops in Python

So, this guide is to stop Python from throwing you for a loop! It will present an overview of all the loop types within Python. Also, nested loops will be investigated. A nested loop is a loop within a loop, ergo, an inner loop within the body of an outer one. 

Loops are among the most basic yet also the most powerful features in programming. Utilised by all modern programming languages loops effectively instruct a computer to repeat a process until a specified condition is reached. This specified condition can be thought of as a question to the computer. The same question is asked again and again until the criteria are fulfilled and no further looping action is necessary. Each time the question is asked it is called an iteration. Iteration is a general term for taking each item of something, one after another. The need for defining the loop in a software program can arise for many, many reasons depending on the task performed by the computing task.  Loops are wonderfully helpful, allowing the flow of code to become circular and iteration to transpire. Without them, it would often take lines and lines of code to enact similar results.


Loop SnakeThere are two distinct types of loops in Python, for statements and while statements, which are explained further below. It is worth noting both loops can be used interchangeably for any situation, they just require altered syntax or approaching the programming conundrum in a different way.

- For Loop. In Python, they are started by using the | for | keyword. This is a looping structure that runs a sequence of statements multiple times for a pre-set number of times. The sequence of statements that are repeated is referred to as the loop body. This means they are explicitly bounded iteration methods. Once the fixed number of loops are completed the code will move onto the next stage. Typically, for loops will run through each element in a list using the index number as the iteration method.

- While Loop. In Python, they are started by using the | while | keyword. This is a looping structure that is repeated if a conditional expression is true. It will test this each time before executing the loop body. Conditional expressions are features of a programming language that performs different actions depending on whether a specified Boolean condition evaluates to true or false. While loop is used in situations where we do not know how many times the loop needs to be executed beforehand. Often unbounded iteration which means it will continue to loop until some condition is met.

For Deeper Information Click Here


3.4 Pass, Break and Continue Keywords in Python

There may arise a situation where you want to exit the loop completely, ignore parts of the internal code for an iteration cycle or even skip an entire iteration cycle. Perhaps you may even want to create a new internal condition or stop a nested loop and start the next iteration of the external loop. All of this can be done with loop control statements!

This guide will focus on the | pass || continue | and | break | keywords. These are all loop control statements which are tools to change the execution flow from its normal sequence.

The pass statement is a null statement. The pass statement acts as a placeholder and usually employed when there is no need for code or commands to be executed but a statement is still required to make the Python syntax to be correct. This is a great tool to use in places where your code will eventually go but has not been written yet. In these situations, the Pythonista simply types the | pass | keyword. In fact, you can use this keyword anywhere inside a Python script. The rules of Python syntax is that empty code is not allowed in loops, function definitions, class definitions, or if statements. By correctly using a pass statement you can avoid error messages for all empty code situations.

Snake Lollipop 2The break statement is a method inside Python which terminates the current loop and pushes the control flow out of the loop body to the next line of code in the script. The most common use for a break statement is in conjunction with a unique condition, different from the looping condition, which when met requires a rapid cancellation of the loop structure. With the | break | keyword it makes it possible to stop a loop before the Python interpreter has executed through all of the planned iterations (or before the original loop condition has been met).

The continue statement is a method inside Python which will return the control flow back to the start of the loop body. The continue statement effectively rejects all the unexecuted statements within the current iteration of the loop and instead pushes that control flow to the loop body beginning. Thus, the continue statement is an excellent tool to skip the effects of particular loop iterations.
 

For Deeper Information Click Here


Chapter 4 - Functions and External Packages

4.0 Chapter Overview

This chapter is focused on increasing the capabilities of Python. I will provide you the keys to unlock all the dynamo features. This chapter starts with the creation of your own unique functions. In Python a function is a block of code which only runs when it is called. New capabilities does mean different ways to handle them are required so next the concept of scope is explored. Next, I explain how to use the keys to unlock the treasure chests of python features. Finally, the locations of the bounty will be mapped out. Thus, by the end of this chapter over a quarter of a million unique packages, each full of functionality, will be obtainable for you to utilise. Each one will improve the potential of Python, all you will need to do is unlock the right one for you. So let's dive right in!


4.1 Making Your Own Python Functions!

Now as a quick refresher, a function in Python is a reusable block of programming statements (code) which only runs when it is called, designed to perform a certain task. It is organised, reusable and performs a single related action. Functions are all about making it easier for the Pythonista whilst increasing both the modularity and reusability of the code. Leading from that, a user defined function is a programmed routine that has parameters set by the user of the system. Simply, a user defined function would be a Python script, that you have created, which can be called upon and run by different programs. 

User-defined functions can seem very different for new programmers, particularly in the way they are called into action, but understand that they are there to enable the best potential out of the Python programming language. The keyword | def | is the method Python uses to create user-defined functions. All user defined functions begin with a def statement followed by the function name. Let me give you a guide example of the syntax to produce a user created function which also uses the | return | keyword. 

def  Name ( Parameters 1, Parameter 2, Parameter 3):
                Block of Code
                return 

The block of code usually incorporates parameter information. Coded into the calling environment will be the name of the function desired and the necessary information to fill out the parameters. The calling environment can also be referred to as the caller program. Parameters are information that is passed onto the function. These can also be referred to as arguments. You can add as many parameters as you want just separate them with a comma. Crucially the same number of actual arguments must be provided as those asked for by the function.

For Deeper Information Click Here


4.2 Scope in Python

In programming the scope of a name defines the area of a program in which you can unambiguously access that name. Name in this case means variables, functions, objects or classes. A name will only be visible to and accessible by the code if it is within scope. A name can also be referred to as an identifier or a namespace. Namespace is the system Python uses to have a unique name for every variable or method within Python. Python itself maintains namespaces in the form of a Python dictionary.

Python under the scope in the crosshairs!Before there was scope there was only global names. This meant any part of the program could modify any variable at any time. This was how it was in many early programming languages such as BASIC. The greatest disadvantage of this was when creating large programs, it became critical that each and every variable had a unique name. If not major problems would occur as parts of the software start to interact in ways not planned. Thus the programmer would have to remember every variable which would eventually become impossible as codes became increasingly larger.

So now most programming languages use scope to avoid this. Scope prevents you from accessing all the variables in a program at all locations in that program. For Python the ability for a code to access a given name will depend on where exactly that name has been defined. When you can access the value of a given name from your code, this will mean the name is in scope. If you cannot access the name, this will mean the name is out of scope.

For Deeper Information Click Here


4.3 Import, From and As Keywords in Python

This guide will focus on the | import || from | and | as | keywords. These keywords distinctly focus on ways to introduce new functionality to Python. For stock Python to retain its lightweight and speedy status it allows access only for a small core of modules. Modules are simply Python files which when accessed can allow for unique functionality. So, when extra functionality in a Python script is desired, it is up to the Pythonista to import the desired functions to the script or manually create the functions by hand. This is where the | import | keyword becomes invaluable. Utilising this keyword bestows all the modules you have ever desired right to your fingertips.

To make use of the functions within a module in your script you will need to import the module with an import statement. All import statements are made up of the | import | keyword along with the name of the module. In most Python scripts import statements are declared at the top of the code under any general comments. This is done to ensure they are executed from the get-go. You can see this happening in the script example below.

Also while the import command is very straightforward it lacks efficiency. In many scenarios you may need only a small portion of the module. To solve this the | from | keyword is born. It is possible to modify the names of modules and the name of the functions within Python. This is achieved using the | as | keyword.

Script example of Import

For Deeper Information Click Here


4.4 Installing Python Packages

So, you want Python to do something very functional but do not feel like writing heaps of code to achieve that functionality? Then look no further, this guide will teach you exactly how to do that by utilising Python Packages. Python Packages are collections of handwritten scripts that will increase the capabilities of the programming language exponentially! Python Packages can be found online with the official distribution repository being the Python Package Index (PyPI). This is an excellent repository of packages for the programming language with over a quarter of a million unique packages available to download. Each and every one will improve the potential of Python, all you need to do is install the right one for you.

It is important to have the same Python version to the particular package. Also having pip, setup tools and wheel projects installed and up-to-date will allow the easiest installation method. Pip is the standard package-management system used to install and manage software packages written in Python. Wheel projects are a pre-built distribution format that provides faster installation.

The code in this guide will demonstrate that these packages in combination with Python means you can produce intricate Mandelbrot images from just three lines of code which you can see below. The Mandelbrot set is an interesting way of seeing how complex functions behave under repeated iterations and looks very beautiful. This would take numerous codes of line to create without utilising external packages.

Just three lines of code to Mandelbrot your way to heaven

For Deeper Information Click Here


Chapter 5 - Crafting Codes

5.0 Chapter Overview

In this chapter we show off some of the coding muscles we have been building throughout this python journey. By the end of this chapter you will be able to create graphical user inputs, generate animations using the Turtle Standard library and access data from real world data at utilise it to drive decisions in your codes. So without further ado let's build some practical codes!


5.1 Swell Python Scripts with the Turtle Library

The scripts in this guide all use functionality from the Turtle Standard Library. This is pre-installed into Python by default and is a graphical library. In this guide we will be making geometric shapes with Python. Then the last script in this guide will generate a turtle race! Perfect for an afternoon coding session. Thus, this guide will ease you into the first steps of coding with an objective.

Think of the turtle library as a whiteboard with a small robot turtle situated on top of it. This robot turtle leaves a pen line behind itself whenever it moves. The size and dimensions of this pen line can be pre-decided in code. Also, the robot turtle can be controlled by code. Thus, by commanding the robot turtle to move you can draw lines all over the board. This white board is a pop-up window which is white unless otherwise specified. All of this can be seen in the image below.

A Python Turtle and the Python Turtle Graphic Pop-Up Window

 
 

Code for the Turtle race is below. It has been extensively commented with depth to explain the inner workings. Copy and paste it into your Python Programming Window, write it out or download the code from the bottom section and open it using the Python IDLE Shell. Either way it will run on any default install of Python.

#As it is traditional to do so all the extra functionality desired for this turtle race is imported at the start.
#All the particular functionality utilised will comes pre-installed on a default installation of Python.
import time
import turtle
from turtle import Turtle
from random import randint

#Setting up the pop-up window! And placing the title words in the centre top of the Python Turtle Graphics Window
#The function turtle.penup() effectively is lifting the robot turtle off the page and moving it, thus no pen line
window = turtle.Screen()
window.title("Turtle Racing Occuring in this Pop-Up Window!")
turtle.bgcolor("Green")
turtle.color("White")
turtle.speed(0)
turtle.penup()
turtle.setpos(-420, 260)
turtle.write("Come one, Come all! It is Turtle Racing Time!", font=("Arial", 30, "bold"))
turtle.penup()

#Adding some dirt to the base, This is similar to the star example above using the turtle.begin_fill() and is similar to drawing with a CNC machine.
#The starting point is decided on, the turtle is put onto the page and then movement commands are given to the robot turtle. 
turtle.setpos(-280, 225)
turtle.color('Brown')
turtle.begin_fill()
turtle.pendown()
turtle.forward(520)
turtle.right(90)
turtle.forward(445)
turtle.right(90)
turtle.forward(520)
turtle.right(90)
turtle.forward(445)
turtle.end_fill()

#Create a finishing line! Every turtle race needs one
#This used the turtle.stamp() functionality which when set like below let's you stamp white squares  
stamp_size = 20
square_size = 15.5
finish_line = 180

turtle.color('white')
turtle.shape('square')
turtle.shapesize(square_size / stamp_size)
turtle.penup()

#Now to make the finish line look checkered! It uses two loops to fill fourteen white stamp sections of colour

for i in range(14):
    turtle.setpos(finish_line, (211 - (i * square_size * 2)))
    turtle.stamp()

for j in range(14):
    turtle.setpos(finish_line   square_size, ((211 - square_size) - (j * square_size * 2)))
    turtle.stamp()

#And with all the above the field is now set!
#Now it is time to get our robot turtle competitors ready!
#Robot Turtle Number One, aka Franklin. Think of below as the stat blocks for the starting location and colour of turtles.

turtle1 = Turtle()
turtle1.speed(0)
turtle1.color("Black")
turtle1.shape("turtle")
turtle1.penup()
turtle1.goto(-275, 140)
turtle1.pendown()

#Turtle Number Two, aka Sonik (possibly a hedgehog in disguise)

turtle2 = Turtle()
turtle2.speed(0)
turtle2.color("Yellow")
turtle2.shape("turtle")
turtle2.penup()
turtle2.goto(-275, 60)
turtle2.pendown()

#Turtle Number Three, aka Michelangelo

turtle3 = Turtle()
turtle3.speed(0)
turtle3.color("lightblue")
turtle3.shape("turtle")
turtle3.penup()
turtle3.goto(-275, -20)
turtle3.pendown()

#Turtle Number Four, aka Crush

turtle4 = Turtle()
turtle4.speed(0)
turtle4.color("Orange")
turtle4.shape("turtle")
turtle4.penup()
turtle4.goto(-275, -110)
turtle4.pendown()

#And with that our competitors are on the Field!

#Pauses the game for three seconds so that all the turtles and all the bets can be wagered ready for the race!
time.sleep(3)

#This loop decides the end of the race. The end of the race happens once i reaches 145 iterations.  
#Most races will be over by this point. Movement speed of the turtles is also decided here
#If you wanted to program in an unfair advantage this is the spot to do it. 

for i in range(145):
    turtle1.forward(randint(1,5))
    turtle2.forward(randint(1,5))
    turtle3.forward(randint(1,5))
    turtle4.forward(randint(1,5))

#Finally a simple and easy way to get out of window is coded in below. By clicking anywhere on the window
#You can exit the application

turtle.exitonclick()

Roll up and be ready! It is time for some racing to go down using the Python script we made above. Check out all the swell action in an epic race caught with multiple screen captures seen below. As you can see there was a close victory by the turtle in yellow today! 

Turtle Race Panels

For Deeper Information Click Here


5.2 Cool API Python Scripts

Let us set our codes free into the world wide web and design codes which access real world data! This real-world data will represent the current reality of the world around us. Application Programming Interface requests is the method that allows this to occur in Python Scripts. Application Programming Interface is often shortened to API. Data from the web can tell us the exact weather situation of any place on the globe, it can be used to tell us the location of faces on an image we provide or it could tell us the number of astronauts currently floating far far out there in space. Any information freely accessible on the World Wide Web is literally within our capacity to utilise inside our Python codes. 

There is numerous API online that are free to use so long as you create an account with their system. This is to stop their system being overloaded or made vulnerable. Thus, when we request information from API set up in this manner we need to provide some kind of input, most commonly an API key. In this case we will utilise OpenWeatherMap API for the following script. OpenWeatherMap API can be found at this location. This API will give us live information on the weather anywhere on the globe. To recreate this script you will need to make your own free account on this website. Once you have made an account and confirmed your email address you will be given an API key. The API key given to me you can see in the below screen capture.

API Key from PYOWM Website (Use it if you want)
 

Also, for the next script we will install another Python Package from PyPI called PyOWM. This is a Python Wrapper Library for OpenWeatherMap web APIs. It will give more functionality to Python particularly allowing for quick and easy consumption of OpenWeatherMap API data in a human-friendly fashion. To install the latest version of PyOWM Python Package you would type directly into the Command Prompt the below.

pip install pyowm

By pressing the enter key you will execute this line which will install PyOWM onto your system. Below you can see the installation of the Python Package PyOWM in the Command Prompt. An easy install that took less than a minute. PyOWM comes from the Python Package Index found in this location. Once this is done we are ready to get into our code! 

Installation of PyOWM occurring in the Command Prompt
 

Now we have all the preparation sorted let's get into whipping up the Python script. Seen below is a Python script which depending on whether it has rained recently will turn on or off the sprinkler system.  It has been extensively commented so that you can follow step by step. You can either type out the code in your Python Programming Window, copy and paste it there or download the code from the bottom section and open it using the Python IDLE Shell.  

#Imagine that this script is run every morning, informing you what the weather will be
#and telling you whether you need to turn the sprinklers on or off. A future
#step would be to turn the sprinklers on or off automatically.

#Start by importing PyOWM (this is what we installed before using the pip installer).
import pyowm

#Now we can use the functionality gained from PyOWM in our code.

#To access the OpenWeatherMapAPI we must have a API Key which is sent
#with our request to use data from OpenWeatherMap
#This is done by using the function owm=pyowm.OWM() and our unique APIkey.
owm = pyowm.OWM('a0c664323ffe4b57a627f7585eea0748')

#Now we can decide the location of the weather data we desire. You can also use
#latitude and longitude to decide location. The world is your oyster.
city = 'Glasgow'

#Now we utilise the functionality provided by PyOWM to get the weather at our
#desired location
loc = owm.weather_manager().weather_at_place(city)

#Below is an example of using latitude and longitude to get weather data from
#OpenWeatherMap API. Uncomment below and comment above to make this run.
#use the latitude and longitude values of your choice.
#loc = owm.weather_manager().weather_at_coords(34, 150)

#Below gives a variable name to the data we have pulled from OpenWeatherAPI
weather = loc.weather

#To see the raw data that you have pulled from the API uncomment the two lines below
#print(weather)

#Below is taking the data we desire from the OpenWeatherAPI and grabbing only what we desire
temp = weather.temperature(unit='celsius')
status = weather.detailed_status

#Cleaning up the tenp data is done below so we have just the average value
cleaned_temp_data = (int(temp['temp']))

#Print the weather details to Python IDLE shell in a human readable manner
print('The temperature today in', city,'is',cleaned_temp_data,'degrees celsius.')
print('The day today will have',status,'.')

#Now to decide whether to inform the human to turn sprinklers on or off.

#The Status variable is a class string variable. Uncomment what is below to demonstrates
#this. Thus means we can search it looking for the string 'rain' inside of it.
#print(type(status)) 

#Using an if statement we can decide whether to sprinkler or not to sprinkler.
#This is done by searching for rain in status or anything rain-esque.

if 'rain' in status or 'thunderstorm' in status or 'drizzle' in status or 'snow' in status:

    print('No need for sprinklers today. Time to turn them off.')
    
else:
    
    print('Sprinklers are needed today. Time to turn them on.')

#In a future video I'll dive into the specifics of automating real life sprinklers from Python code. 

What this script prints out can be see below in the Python IDLE Shell. The code was run twice from the Python Programming Window with the only difference between the two altering the target city. The first time the code was run the location was set to Newcastle Australia (the location of Core Electronics). Thankfully today is a nice sunny day so sprinklers were necessary to keep our grass green. The second time running the code the city was changed to Glasgow in Scotland. Thus, the program received the weather information for Glasgow. Naturally, it was raining so sprinklers were not necessary. The correct sprinkler reminders were accurately printed to the Python IDLE Shell as well as a message about the local temperature and status of weather.

Glasgow Vs Newcastle Weather

For Deeper Information and an Astronaut API Example Click Here


5.3 GUI with Tkinter in Python

Here we will be creating graphical user interfaces using the powerful Tkinter library. Graphical user interfaces are referred to as GUI and can be pronounced as Gooey. GUI is a visual way of interacting with a computer using items such as windows, icons, and menus. These are present in most modern operating systems and substantially improves communication between yourself and the computing device.

GUI can be created using many different external packages in Python however this guide will focus on the powerful Tkinter library. This library is pre-installed on all default Python. This means once you have utilised an import statement to your script all the functionality of this library will be ready and raring to go. This will also teach you how to check for and install Tkinter if you do not have it already installed.

So with that, let us crack on and create our first GUI. Below will demonstrate how to create an addition and subtraction calculator using Tkinter. This is an excellent script to put together as it highlights numerous functionalities of this library. Making practical tools like this demonstrates just a slice of the world of possibilities you can do with Tkinter. The script is seen below and has been extensively commented so you can follow through effectively. You can either type out the code in your Python Programming Window, copy and paste it there or download the code from the bottom section of this page and open it using the Python IDLE Shell. 

#Using the import * means we are importing everything inside the designated library
#Thus the line below imports all functionality from Tkinter library.
from tkinter import *

#This creates a GUI tk() Variable called calc.
calc=Tk()

#This function gives the window a name.
calc.title('Adding and Subtracting Calculator')

#Set the size of the GUI Window.
calc.geometry("720x180")

#Make our GUI a little more pleasing to the eye by altering the background colours.
calc['bg']="powder blue"

#Below is creating Labels on inside our GUI window. This is so users can
#understand how to use this calculator. The Labels are given a location on the window
#and also text is decided and made bold if important.
FirstLabel=Label(calc, text='First Number', font=('bold'))
FirstLabel.place(x=40, y=20)

SecondLabel=Label(calc, text='Second Number', font=('bold'))
SecondLabel.place(x=40, y=88)

ThirdLabel=Label(calc, text='Or')
ThirdLabel.place(x=358, y=83)

FourthLabel=Label(calc, text='Result', font=('bold'))
FourthLabel.place(x=556, y=52)

#This creates entry locations for the user to type numbers into the calculator. Also, a place
#for the result to be displayed is created.
FirstNumber=Entry()
FirstNumber.place(x=120, y=52)

SecondNumber=Entry()
SecondNumber.place(x=120, y=120)

ResultNumber=Entry()
ResultNumber.place(x=520, y=83)

#Below is the user-created function which will run whenever the Add button is clicked.
#First, we start by defining the function and giving it a name. All code of this function
#will be indented.
def add():

#Whenever this function is run initially we clear the result location. This is to stop
#number from stacking up and thus displaying the wrong result.
    ResultNumber.delete(0, 'end')

#Now it grabs the numbers from the first and second entry window. It also double-checks
#that the data by converting the data inputted into an integer type.
    First = int(FirstNumber.get())
    Second = int(SecondNumber.get())

#Here is the actual calculation occurring. Addition of both the numbers inputted    
    Calculation = First   Second

#Now you can display the number underneath the Result label.     
    ResultNumber.insert(END, str(Calculation))

#Same process is done below for the subtraction function.    
def sub():
    ResultNumber.delete(0, 'end')
    First = int(FirstNumber.get())
    Second = int(SecondNumber.get())
    Calculation = First - Second
    ResultNumber.insert(END, str(Calculation))

#Now that the functionality has been coded, we can create buttons that reference
#the above functionality. These buttons are also given a location on the window.
Button1=Button(calc, text='Add', command=add)
Button1.place(x=310, y=80)

Button2=Button(calc, text='Subtract', command=sub)
Button2.place(x=390, y=80)

#This is a way of creating an infinite loop. The application will run, wait for
#events to occur and process the events so long as the window is not closed.
#Another way to make an infinite loop would be creating while True infinite loop.
calc.mainloop()

Below shows the pop-up Tkinter window when running this code in the Python Programming Window. You can see two numbers being added together. Pretty swell!
 
Adding and Subtracting Calculator
 

For Deeper Information Click Here


Chapter 6 - Where to Go From Here

6.0 Chapter Overview

Now we have now covered all the foundations you need to springboard into the powerhouse programming language of Python. We have gone through from early steps of understanding interfaces all the way up to writing intricate scripts that utilise all kinds of unique functionality and live data. It has been a fantastic adventure creating this python workshop, I personally have had a ton of fun putting them together and producing them for you. But this is by no means the end and hope you perceive this workshop as a springboard onto future projects and a means for other daring python spelunking escapades.


6.1 Where to Find Further Knowledge and Inspiration

There are a lot of places to go from here which is one of the blessing of Python. If you are interested in furthering your Python education, I have linked several teaching platforms below.Snake Gurl

If you are interested in inspiration for a Python project a great place to start is with a piece of physical hardware (like a Raspberry Pi 4 Model B which is totally programable using Python) and find a well-documented, interesting project and mimic it. There are loads of cool projects on Instructables, Hackaday and at our Core Electroncs Projects Page. Doing this will really allow your Python codes to come alive! If you want to learn more about Raspberry Pi Hardware, we have a whole Raspberry Pi Workshop to immerse yourself in knowledge.


6.2 Where to Find Help

If your interesting in bringing Python to your personal maker projects we have numerous great guides and projects on our Core Electronics page. And if you want help with your own projects or get stuck in a Workshop our Core Electronics Forum is the best way to get in touch with us. We are always happy to give a helping hand. Google is also a lifesaver for speedy solutions. I will be continuously adding content and modifying this workshop to make it the best experience possible. As always if you have any questions, queries or things to add please let us know your thoughts!

And with that it brings us to the conclusion of the Core Electronics Python Workshop. I hope you have got something out of it and has made you excited to program. Thanks for going on the journey with me and be sure to share this workshop with a friend if you found it useful! Until next time, stay cozy.

Helpful Python Gurl

 

Attachment - All-Python-Workshop-Scripts.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.