MBTechWorks.com    

Python Programming Reference for Raspberry Pi

March 22, 2019

Python is one of the most powerful and popular programming languages of our day. As Raspberry Pi enthusiasts and developers, we are fortunate that Python is included with our Raspbian operating system!

This article serves as a quick reference to Python's programming syntax, constructs and keywords and is not meant as an introductory tutorial. It assumes a basic knowledge of Python programming. If needed, see our Python Overview and Introduction articles.

Syntax - the Basic Rules

Following are some of the basic Python programming language rules.

Case

Python is a case sensitive language, meaning that it treats upper and lower case letters and identifiers as distinct and different. Example: variables firstname, firstName and FirstName are three different and unique variables. Care must be taken when writing code to keep the case of identifiers consistent to avoid program errors, or "bugs".

Indentation

Blocks of code are delimited, or grouped, through line indentation - by the number of spaces or tabs in front of the statement. Code statements with the same number of spaces or tabs at the beginning of the line belong to the same block of code. Those with more, or less, spaces or tabs do not belong to the same block. Python does not use curly braces '{ }' for delimiters as some other languages.

Identifiers

Identifiers are used for naming variables, functions, classes and other objects within Python code. An identifier must start with an a letter, upper or lower case, or an underscore character "_". After the first character, the identifier may have any number of letters, numbers or underscore characters. Other special characters are not allowed.

While not required, some "best practices" conventions are widely used for identifiers:

  • Normal Python variables start with a lower case letter.
  • Class names start with an upper case letter.
  • A private variable starts with an underscore "_" character (note: private variables not enforced in Python, this is by convention only).
  • Constants, a variable which should not be changed, use all uppercase characters. Example: PI = 3.14159.

Quotes

Use of either single and double quotation marks are used to create string literals. Single and double quotation marks must be paired or balanced. Examples: "Raspbian"  'Raspbian'  "he said 'the Raspberry Pi is awesome' ".

Comments

Good programming practices use comments throughout to make coding more clear. Comments can be inserted anywhere using hash character, #. Any text following the hash character becomes a comment and is not executed as Python code. Example: # this is a Python comment.

Escape Characters

Programming languages often use special characters. These are often called "escape" characters. Python uses the backslash "\" character in front of a character to indicate it has a special function. Examples: \t is a tab; \r is a carriage return; \n is a new line.


Python Elements - the Parts

Keywords

All programming languages use keywords, also called "reserved words". These keywords have special meaning to tell the Python interpreter to do something or to represent a special value. They cannot be used as variables, function names, identifiers or for other purposes. Following are Python 3 keywords:

and        except     nonlocal
as         False      not     
assert     finally    or      
async      for        pass    
await      from       raise   
break      global     return  
class      if         True    
continue   import     try     
def        in         while   
del        is         with    
elif       lambda     yield   
else       None               

Imports and Modules

Python code can be organized, or grouped, into modules. A module is a separate file containg Python code that can be used by other Python code files through the use of the import keyword. Example: import someModule

Note: Python files use an extension of .py, as in someModule.py. To import someModule.py into another source file, use: import someModule without the .py extension.

It is also possible to import individual objects (named code segments) from a module (rather than the whole module) by using the form: from someModule import specificObjectOrFunction.

Variables and Data Types

A variable is a named element in a program that reserves memory to hold data values. Almost all programs need to process data - input, output, calculate, store, retrieve, analyze, print, display and so on. Named variables can be referenced and processed in other statements within the program.

Each variable can hold different types of data - numbers, characters, strings, lists and more. A variable is defined (created) by simply giving it a name and assigning it an initial value, like myName = "Mike" In this case, myName is a String data type.

Python variables are dynamic and unlike some languages, do not have fixed data types. Thus, a Python variable myName = "Mike" could be changed in another statement to myName = 3.14, which is now a Number data type! This is perfectly legal - but, be careful to keep track of your data type usage or you may create some unpredictable and undesired results (also known as bugs!).

Python 3 Data Types

Data Type Description Example
Integer Whole numbers, positive or negative, without decimals. 0, 72, 149732, -84
Float Real, floating point numbers with decimals. 3.14, 149732.87, -84.60
Complex A combination of a real number and an imaginary number. 7 + 9i, 3.14 - 2.2i, .8 + i
Boolean Represents True or False - also evaluates to 1 or 0 respectively. var1 = True, variableXZY = False
String One or more characters. String literals use single or double quotes. 'String with single quotes', "String with double quotes", "This string has a string 'Python is awesome!' within".
List Contain a series of values. Can include strings, numbers and other data types. myList1 = [2, 4, 2, 6], namesList2 = ['Oliva', 'Jacob', 'Emily'], mixedList3 = [2, 4, "John"]
Set Contain a series of values similar to List, but cannot have duplicate values, which a List can have. mySet1 = {2, 4, 6}, namesSet2 = {'Oliva', 'Jacob', 'Emily'}, mixedSet3 = {2, 4, "John"}
Tuple Similar to List, contain a series of values, but cannot be changed once created (read only). someConstants = (3.14, 2.718, 1.618), daysOfWeek = ("Mon", "Tue", "Wed")
Dictionary A list with Key:Value pairs of data. Each data value has a key that can be used to reference its data value. classGrades = {'Oliva': 'C', 'Jacob': 'B', 'Emily': 'A'}, myConstants = {'Pi': 3.14, 'Eulers': 2.7182, 'GoldenRatio': 1.618}

Operators

Operators are the parts that invoke action in a statement. They may be mathematical, logical, assignment, comparison, bitwise, membership or identity operators.

Python Math Operators

Operator Function Example
- Subtraction 5 - 3 = 2
+ Addition 18 + 4 = 22
/ Division 9 / 2 = 4.5
// Floor Division 9 // 2 = 4
% Modulus 9 % 2 = .5
* Multiplication 10 * 2 = 20
** Exponent 10**3 = 1000

Comparison Operators

Operator Function Example
== Equal to x == y
!= Not equal to x != y
< Less than x < y
> Greater than x > y
<= Less than or equal to x <= y
>= Greater than or equal to x >= y

Logical Operators

Operator Function Example
and True if both operands are true if a == b and c == d :
or True if either operands are true if a == b or c == d :
not True if operand is false if not x :

Operator Precedence

Operator Description
(   ) Parentheses
** Exponent
+x   -x Positive or negative variables
*   /   % Multiplication and division
<   <=   >   >=   <>   !=   == Comparisons
and Boolean AND
or Boolean OR

Operands

Operands are the parts that the operators act upon. Operands are the object, while the operators are the action. In the arithmetic function 2 + 3, the 2 and 3 are the operands, while the + symbol is the operator.

Operators and Operands image

Example of Operators and Operands

Conditional Statements

Conditional statements handle decision making in a program. This is done primarily through the if and its supporting elif and else keywords. A variable or expression is tested using the if and then based on the result of the test, additional statements may or may not be executed within the conditional block. Conditional statements are structured as:

if logical expression:
    statements block
    
if logical expression:
    statement block
else
    alternative statement block
        
if logical expression:
    statement block
elif alternative2 logical expression
    alternative2 statement block
else
    alternative statement block if none above is true

For and While Loops

Loops provide a way to repeat, or iterate, code based on a condition or an expression. In Python, the for and while keywords are used to create loops.

For Loop

The for loop iterates, or loops, through a sequence in a string, list, tuple or dictionary. The value in each sequence is assigned to the variable in the for statement each loop.

#  format
for variable in sequence:
    code within for loop

# example using List
namesList = ['Michael', 'Emma', 'Evelyn', 'Oliver']
for nameVar in namesList:
    print (nameVar)

# example with break
primeNumbersList = [2, 3, 5, 7, 11, 13]
for num in primeNumbersList:
    if (num > 10):
        break
    print (num)


# example with continue - skips rest of code and continues loop
namesList = ['Michael', 'Emma', 'Evelyn', 'Oliver']
for nameVar in namesList:
    if (nameVar == 'Emma'):
        continue
    print (nameVar)
    
# example using Tuple with else
daysOfWeek = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
for day in daysOfWeek:
    print (day)
else:
    print ('All done')
    
# example with range()
for y in range(10):
    print (y)

While Loop

The while loop iterates, or loops, while its expression is true.

# format
while expression
    code within while loop

# example while loop
n = 0
while n < 10:
   print (n)
   n = n + 1

# while with break
while True:
    inStr = input("Enter something, or q to quit")
    if inStr == 'q':
        break #stops loop, goes to statement after loop
    print (inStr)

# while with continue 
n = 0
while n < 10:
    n = n + 1
    if n == 5:
        continue #skips 5, continue top of loop 
    print (n)

# while with else
n = 20
while n < 10:
    print (n)
    n = n + 1
else:
    print (n, " : n is not < 10")

Python Functions

Functions are defined (named) blocks of code that help organize sections of a program into specific tasks or functions. Python has many built-in functions. These are listed on Python Software Foundation's web site at Python Built-in Functions.

Additionally, you can create your own user-defined functions. To create a user-defined function, begin the block of code with the keyword def (for define), followed by a function name, then a pair parentheses and end with a ':'. Optionally, you can include parameters within the parentheses. At the end of the function's block of code, an optional return may be used, with or without a return expression or variable.

Example user-defined function:

# user function format
def myFunctionName(optional, parameters):
    code goes here
    more code
    return

# user function example    
def multiplyTwoNumbers(num1, num2):
    result = num1 * num2
    return result

returnVal = multiplyTwoNumbers(5, 10)
print(returnVal)  

lambda - Anonymous Function

Another type of function is the Lambda, or Anonymous Function. It is a Python function, but without a name or use of def. It is a shortcut for an small, immediate use function.

The format is: lambda parameters: expression

Following compares a named function with a lambda equivalent.

# defined (named) function 
def squareNum(x):
    return x*x

x = squareNum(4)
print (x)

# a lambda function 
squareNum = lambda x: x*x
print(squareNum(4))

Python Classes, Methods and Objects

Classes

A class contains variables and functions grouped together into a unit. The class definition serves as a template that must be copied through assignment to an instance called an object. It is this instance, including all the variables and functions from the class template that is used directly within the procedural flow of the program.

Methods

Within a Class, what appear to be procedures as defined with def are actually called methods. The differ from procedures in that they can access the data and variables contained with the class, and that they are always associated with the object that they were created from the Class.

Also note that methods with parameters have "self" as the first parameter. This is used internally by Python as a reference to the current instance (the object) of the class.

Objects

Python is an Object-Oriented programming language. This means that the programming model is organized primarily around objects rather than procedural actions. Almost everything in Python is an object. This includes all the Python data types, variables, functions, methods and instances.

Python.org states that "Objects are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects."

Example Class with Methods and creation of Instance:

# class definition with 2 methods 
class MySquareCubeClass:
  
  def squared(self, num1):
    squaredNum = num1 * num1
    return squaredNum
    
  def cubed(self, num1):
    cubedNum = num1 * num1 * num1
    return cubedNum
# end of class definition
    
# create instance of MySquareCubeClass    
myInstanceOfClass = MySquareCubeClass()

result = myInstanceOfClass.squared(4)
print (result)
# prints 16 

result = myInstanceOfClass.cubed(4)
print (result)
# prints 64


Python Errors and Exceptions

In real-world programming, things don't always go as planned. Errors occur. There are two main types of errors in Python - Syntax errors and Exceptions.

Syntax Errors

Syntax errors are caused by invalid format, sequence, indentation or other violation of rules of the language and the Python interpreter cannot understand the statement or structure. The Python parser will show the line of code in error with a ^ character pointing to the start of the syntax error.

Python Exceptions

An exception occurs during run time of a program. While the syntax may be correct, the execution of the program encountered an invalid condition. If not handled correctly, the program will abort and fail. A simple example might be the following. The syntax of all three statements is correct. However, when a is divided by b, which is zero, it will result in a division by zero exception.

a = 5
b = 0
c = a / b

Python has many standard, built-in exceptions as detailed at Python.org: Built-in Exceptions.

Many exceptions can be handled in a way to prevent program failure. This is called Exception Handling, and may be applied to portions of a program that are at risk of an exception.

Try and Except

The try and except statements are the primary tools for handling exceptions. Code that is to be tested for a potential exception is placed within the try statement. The except statement follows with likely exception error conditions and statements to handle or report the exception. The format for the try and except is as follows:

try:
    python code here
    more code
except:
    run this code if there is
    an exception from above

The except statement allows specific error conditions to be tested so the appropriate code can be used to handle that condition.

# While loop - enter integer number only
while True:
  try:
    n = int(input("Enter a number 0 - 9: "))    
  except ValueError: 
    print("Error: please enter a number")

The try statement also offers an else to allow conditional handling, and a finally clause that will always execute at the end of the try regardless of the except or else.

while True:
    try:
        n = int(input("Enter a number 0 - 9: "))
    except ValueError:
        print("Error: please enter a number")       
    else:
        print("Good job, you entered: ", n)
    finally:
        print("Will always execute this line")

Article closing text image