Wikijunior:Raspberry Pi/Introduction to Python

Python is a general-purpose programming language that is easy to learn and is used in nearly all of the tutorials in this wikibook.

Getting started

edit
 
Open IDLE from the Programming menu on Raspberry Pi OS.

Python 3 and IDLE are pre-installed on Raspberry Pi OS. IDLE can be opened from the Programming menu.

If you don't have a Raspberry Pi, you can install a copy of Python 3 on just about any computer from the official website.

Using the IDLE Shell

edit

IDLE (Integrated Development and Learning Environment) is included with Python 3 and is easy to use. It is an Integrated Development Environment (IDE) which is a type of software that is designed to make it easy and convenient to write source code.

The first window that opens is the IDLE Shell, which is the Python 3 shell. You can run a quick line of Python in the shell, for example Python is a calculator so let's try adding 2 + 2:

Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>2+2
4

Feel free to play with Python's calculator and try using the different operators:

  • Plus +, such as 1 + 1
  • Minus -, such as 3 - 2
  • Multiply *, such as 6 * 2
  • Divide /, such as 10 / 2
  • Square ** 2, such as 2 ** 2
  • Modulo (gives the remainder from a division) %, such as 10 % 3

You can also access the Python 3 shell by typing python3 into the   Terminal program and pressing the ↵ Enter key.

Hello World

edit

Whenever a programmer starts with a new programming language. The first thing to do is to output the phrase "Hello World".

Open IDLE, select File, then New File (Ctrl+N) (or press the Ctrl and N keys together), create a new file and name it helloworld.py, then type the following:

print("Hello World")

Run the code in IDLE by selecting Run, then Run Module (F5) (or press the F5 key) and it should display in the Python shell as:

Hello World

print is a built-in function that outputs text onto the screen. As it's a word that has already be defined by Python to do something, programmers call it a "keyword".

Comments

edit

Sometimes you may need to make notes in your code or remove a line to troubleshoot why it is not working (which is referred to as debugging).

In Python, you can add a comment using the hash symbol # (in the US, this is confusingly called a "pound sign"). Let's add a comment to our Hello World program from earlier:

print("Hello World") # Let's say Hello World!

Once the hash symbol has been typed, the Python interpreter will ignore the rest of the line which allows us to make notes.

Variables

edit
 
A variable is like a bucket as it can carry a value.

Variables are a container that is used to store values that we can define in our program.

In Python, variables are assigned with a name, a variable assignment operator = and a value. Some examples of values are:

Booleans

edit

True or false such as True or False.

x = True  # x is a Boolean with a value of True
y = False  # y is a Boolean with a value of False

Integers

edit

Positive or negative whole numbers such as 5 or -10.

x = 5  # x is an integer with a value of 5
y = -10  # y is an integer with a value of -10

Floating-point numbers

edit

Positive or negative numbers that use a decimal point such as 3.14 or -0.5.

x = 3.14  # x is a floating-point number with a value of 3.14
y = -0.5  # y is a floating-point number with a value of -0.5

Strings

edit

A series of letters, numbers or symbols such as "Hello World". In Python, either single quotes ' ' or double quotes " " can be used to define a string.

x = "Hello World"  # x is a string with a value of "Hello World"
y = 'This is a string'  # y is a string with a value of 'This is a string'

Lists

edit

A list is an ordered collection of values each separated by a comma , of any of the values above. Any Python 3 datatype can be used.

fruits = ["apple", "banana", "mango"] # fruits is a list with the values: apple, banana, mango
numbers = ["1", "2", "3", "4"] # numbers is a list with the values: 1, 2, 3, 4

Python 3 has a built-in functions for modifiying lists. For example, let's try combining the two lists together:

fruits = ["apple", "banana", "mango"]
numbers = ["1", "2", "3", "4"]

fruits.extend(numbers)
print(fruits)
["apple", "banana", "mango", "1", "2", "3", "4"]

Dictionaries

edit

A dictionary is like a list but for each entry there are two values. Here's an example:

capitals = {
    "United States": "Washington, D.C.",
    "France": "Paris",
    "Japan": "Tokyo",
    "Brazil": "Brasília"
}
# To print out a country's capital, do this
print(capitals["Japan"])

# To add a new value to the dictionary, do this:
capitals["Australia"] = "Canberra"

Other datatypes

edit

These are just a few examples of the variable types that are available in Python. There are many other types as well including complex numbers, tuples, sets and more.

If statements

edit
 
An if statement is like a fork in the road.

The if statement is used to make parts of the source code run providing a certain condition is met. For example, let's make a variable called "x" and set it to 5.

The keyword else is used for defining what the source code should do if the condition x == 5 is not met.

#Create the variable "x" and set it to 5.
x = 5

# This if statement checks if a variable "x" is equal to 5
if x == 5:
    # If the condition is true, this block of code will be executed
    print("x is equal to 5")
    
else:
    # If the condition is false, this block of code will be executed
    print("x is not equal to 5")
x is equal to 5

What about if statements that have more than just two conditions? We use the keyword elif (which just means "else if"). In the example below, we use the less than < and greater than > symbols to determine if a number is positive, negative or zero.

Try running this example in IDLE and change the value of x to get all 3 outputs:

x = input("What is the value of x?")

# This if statement checks the value of a variable "x"
if x < 0:
    # If "x" is less than 0, this block of code will be executed
    print("x is negative")
    
elif x == 0:
    # If "x" is equal to 0, this block of code will be executed
    print("x is zero")
    
elif x > 0:
    # If "x" is greater than 0, this block of code will be executed
    print("x is positive")

Loops

edit

Sometimes you will want the code to repeat which can be done using loops. There are 2 kinds of loops used in Python:

For loops

edit

For loops are useful when you know how many times the code needs to repeat itself.

In this example, there is a list of numbers from 1 to 5. The square brackets [] are used as lists are a specific variable datatype that is used to store multiple values.

# This for loop will iterate through a list of numbers
for number in [1, 2, 3, 4, 5]:
    # Each time through the loop, the value of "number" will be updated
    # to the next value in the list
    print(number)
1
2
3
4
5

While loops

edit

A while loop repeats endlessly until the condition is met. For example, printing the numbers from 1 to 10:

i = 0

# Start a while loop that will continue as long as "i" is less than 10
while i < 10:
  # Increment "i" by 1 each time through the loop
  i += 1

  # Print the value of "i"
  print(i)
1
2
3
4
5
6
7
8
9
10

Modules

edit

Modules are Python source code written by other software developers. By default, Python can't do very much but we can make our Python programs do more by importing a module.

You can use the import keyword to add a module. Use the from to be more specific if you just want to do one thing from that module.

For example, let's print the number Pi. The number Pi is often shortened to 3.14, but it actually continues on forever in real-life (mathematicians call this an irrational number). In Python, pi prints Pi to 15 decimal places.

from math import pi

print(pi)
3.141592653589793
 
The blue line is the radius and the black line is the circumference.

Now we have Pi, we can create a simple program that calculates the area of a circle. The formula for this is: area = pi × radius2

  • Circumference – the outside line of a circle
  • Radius – a straight line that connects the center of the circle to the circumference

The single asterisk * is used to multiply one number by another (just like the multiplication sign ×). The double asterisk ** with a 2 is used to square a number such as: 22 = 4

from math import pi

r = input("Enter the radius of the circle:")
area = pi * r ** 2

print("The area of the circle is:" + area)

If you want to go a step further, you can try to find the length of the circle's circumference. The formula is: circumference = pi × diameter

  • Diameter – a straight line that goes through the centre of the circle from one side of the circumference to the other. This line is double the length of the radius.
  • Pi – the ratio of the length of the circumference to the diameter. This means that the circumference of every circle is about 3.14 times as long as the diameter. It is named after the Greek letter Pi (π).
from math import pi

d = input("Enter the diameter of the circle:")
c = pi * d

print("The circumference of the circle is:" + c)

Glossary

edit

General

edit
 
The first bug was a moth that was found trapped in the Aiken Relay Calculator while it was being tested in 1947.
  • Bug – An unwanted mistake in the source code.
  • Comment – A line of source code that is ignored by the interpreter/compiler, so it can be used for making notes or debugging.
  • Debugging – Removing bugs from the source code. Most IDEs have tools that allow debugging at runtime to make it easier to see where the bugs are.
  • Hello World – A popular test program used by software developers when they are learning a new programming language.
  • If statement – A conditional section of source code that runs certain source code based on the condition that was used.
  • Indentation – The use of tabs (with the Tab ↹ key) or spaces (with the spacebar) before a line of source code. In Python, this is required for the interpreter to understand how the program works.
  • Integrated Development Environment (IDE) – A program designed for software development. A typical IDE includes a text editor to write the source code, an interpreter (or compiler) for running the sourcing code and debugging tools to troubleshoot mistakes made when writing the source code.
  • Interpreter – A program that reads and runs the source code of an interpreted programming language such as Python.
  • Keyword – A word that is reserved for use by a programming language. Examples in Python include: print, if, else, elif, for and while.
  • Source code – The text of the programming language that makes up the program.

Loops

edit
  • For loop – A repeated section of source code that runs a certain number of times.
  • While loop – A repeated section of source code that is exited by a condition.

Variables

edit
 
The boolean datatype was named after the English mathematician George Boole.
  • Boolean – A variable datatype that can either be True or False.
  • Datatype – The type of data which a variable holds. Python is a dynamically typed programming language, so you can just assign the value to the variable.
  • Integer – A variable datatype for any positive or negative whole number (including zero) without a decimal point.
  • String – A variable datatype that defines a string of characters such as "Hello World".
  • Variable – A value with a particular datatype that is defined by the programmer usually at the top of a program.

Modules

edit
  • Module – A Python source code file written by other software developers. Many modules are included with the default Python installation, but there are also external Python modules which need to be installed using pip or Anaconda.
  • pip – A command-line Python package manager for installing external modules that aren't included in the standard Python installation.

Further reading

edit

The official Python website has an informal introduction to Python.

There is a Python Programming guide on Wikibooks.

Issue 53 (January 2017) of the official Raspberry Pi magazine MagPi has a Python 3 tutorial from page 14. The PDF files for every issue of MagPi can be downloaded for free from the Raspberry Pi website and can be re-shared under the lenient CC BY-NC-SA 3.0 licence.

There are a lot of books about the Python programming language, perhaps too many! Al Sweigart's books can be read on his website for free, though do buy these books if you find them useful.

TitleAuthorYearISBN
Automate the Boring Stuff with Python (2nd Edition)Al Sweigart2019ISBN 978-1593279929

If you are 14 years old or older, you can become a formally qualified Python programmer by taking the Certified Entry-Level Python Programmer (PCEP) certification. Cisco's SkillsForAll e-learning platform has a free course called Python Essentials 1.