RPi Python Programming 06: Python Basics

In the previous tutorial , we discussed the Python language, its applications, implementations (including CPython, Jython, IronPython, and PyPy), and IDEs. We also learned how to write Python scripts and modules, and how to run Python scripts through an integrated development environment (or IDLE) and a Bash shell.

Before we move on to controlling hardware through Python scripts, it will be helpful to first have a solid foundation in the language. So, in this tutorial, we discuss the basics of Python programming and learn some best practices, including the style of writing code in Python.

Although this is an intensive course, you will be able to run short Python scripts on the Raspberry Pi (RPi). So keep your Raspbian booted and IDLE open. And if you notice a blank screen on your monitor when you turn on your RPi desktop, it occasionally fails to boot a few days after installation.

Some reasons: loose MicroSD card or HDMI cable connection. If this occurs, reconnect the MicroSD card and HDMI cable and plug the RPi into your desktop again. If this doesn't solve the problem, try reinstalling Raspbian on the MicroSD card.

Python Syntax
Python's syntax is different from other programming languages. In most other programming languages, instructions (the logical lines of code) are terminated by a delimiter, such as a semicolon (“;”).

However, Python uses spaces and indentation to maintain the block structure of a script. Therefore, adding an unintended space at the beginning of a line (a physical line in the text editor) will block the code differently. This means that indentations are very important in Python. This is sometimes discouraging or scary for developers accustomed to other languages.

In Python, each physical line of code is interpreted as a single logical line (a statement of code) unless continued. If a logical line is too long to fit on a single physical line, the first line may be terminated with a backslash (“\”). This indicates that the logical line continues into the next physical line.

When one logical line continues to the next, any indentation on the second line is irrelevant. But if the second line is not a continuation of the first (because there is no backslash at the end), that marks the end of that logical line. When a logical line continues, there should be no comments except on the last physical line.

Similar to other programming languages, however, a block of code in Python is indicated by square brackets (“{“) or “start/end” delimiters. The first line of code must not be indented. But in Python, all adjacent lines indented by the same value will be identified as a block of code (as if they were enclosed in square brackets).

It is recommended to use only spaces or tabs to indent code in Python, but avoid mixing them (version 3 does not allow this to happen). Tabs can also be treated differently in different text editors, so it's ideal to avoid them. It is best to use four spaces (logical columns 5, 9, 13, etc.).

If there is an open delimiter – such as brace (“{“), square bracket (“(“) or parentheses (“(“) on a physical line, the next line automatically continues until the closing delimiter of the same type occurs.

Comments
All comments in Python start with a hashtag (“#”). Everything to the right of the hashtag, up until the end of the line, is treated as a comment by the Python interpreter. Comments are not processed as lines of code. Instead, they are strings of text inserted into code to provide useful information to other programmers.

It is recommended to use comments generously so that your code is readable. These comments should indicate meaningful things about the code without iterating over obvious things.

For example, a Python comment might look like this:

# This script controls a character's interface
# LCD with Raspberry Pi GPIO and display management
# message string in it.

Identifiers
Identifiers are names given to variables, constants, functions, classes, modules and other objects in any programming language.

In Python, any identifier must begin with a letter (ASCII compliant) or underscore, which may be followed by more letters, digits, or underscores. Punctuation characters cannot be used as identifiers.

Identifiers in Python are case sensitive. For example, “GPIO_status” and “gpio_status” refer to different objects.

Here are some valid identifiers in Python:

LCD_message _display_status LED01
_LED_ON LED_OFF sleep

These are examples of invalid identifiers in Python:

01LED LCD@status 123

Key words
Keywords are reserved words and cannot be used as identifiers for other objects. Python V2 has 31 keywords.

They are:

and how to claim to break
class continues def
elif else exec
finally stop global
if the import is
lambda no or pass
print enlarge return try
while with income

Python V3 has 33 keywords. They are:

and how to claim to break
class continues def
elif otherwise false
finally stop global
if the import is
lambda none no local no
or pass, increase, return
true try while you have
harvest

Declarations
Instructions are logical lines of code that perform a type of operation on data.

In Python, statements can be simple or compound. Simple statements are single logical lines of code that are typically an assignment of values ​​to simple variables or expressions. Compound statements contain more than one simple statement grouped together as a block of code with the same amount of indentation.

Each simple statement within a compound statement is called a clause. A clause can have a header that can begin with a keyword and end with a colon (“:”). The header containing a clause is followed by other statements (or clauses) in the block and these are called the body of the block.

Unlike other programming languages, there are no statements in Python – just simple, compound statements.

Object-oriented programming
Code in any programming language is used to process data. Data can be constant values, ordered and unordered groups of constant values, or more complex data structures (such as classes and objects).

Essentially, each data type has a type. The data type determines how it should be treated in the code, what properties it can have and what operations (in the form of operators, functions and methods) can be performed on it.

A reference name accesses each piece of data in the code. This reference name can be an identifier — different from the keywords and identifiers used in this scope. Therefore, references to certain data must always be unique within the same scope.

References that point to data where the content can be changed are called variables. Server variables as references that bind to memory locations where the contents of that location can be changed in code. References that point to data where the content will never change in the code are called constants.

The value assigned to a reference defined as constant cannot be changed once established.

The declarations of an encoding process are the contents of the variables. These statements can be simple or compound. Compound instructions can be used to make decisions or change the execution sequence of other instructions. More than one simple and/or compound statement may need to be organized into reusable (callable) blocks, which are called functions.

Additionally, there can be ordered and unordered groups of constant values ​​assigned to a variable. There may also be more complex data structures where related data values ​​and operations on them are grouped together as a class. Typically, a class represents the actual type of object (like a class) defined to represent people.

Any real object will have some properties defined as attributes in a class. These attributes are special variables that bind to a specific class and represent the object's properties, which are also represented by the class.

There may be some operations on the content of attributes. The functions (linked to the class) that process the contents of the class's attributes are called methods.

Specific instances of a class are called objects (code objects). These objects have all the attributes and methods defined for their class. Objects belong to internal or user-defined classes. In object-oriented programming, data is always processed as values ​​associated with variables and attributes of objects.

Python Objects, Classes, Data Types, and IDs
Python is also different from other languages ​​in the way it handles data. For example, in Python, everything is an object. This includes the values ​​assigned to variables or attributes that are objects of built-in data type classes.

Data types are technically built-in Python classes. When a value is assigned to a variable or attribute, the value becomes the object that belongs to a data type class. Another way to say this: the value becomes an instance of a built-in Python data type class.

What this means is that in Python there is no need to declare the data type of references. Python implicitly assumes the data type of the reference. This is why keywords are unnecessary for declaring data types in Python.

Another interesting Python function is IDs. Depending on the implementation and platform, Python only stores single values ​​in memory locations. If two references point to the same value, they will have the same ID and point to the same memory location. Python does not duplicate the same (literal) values, even if they are linked to different references.

Mutable, immutable, iterable, and iterators
Python objects can be mutable or immutable. When performing any operation (through operators, functions or methods) on an immutable object, the data type of the return value of the respective expression will always remain the same as that of the object.

When performing operations on mutable objects, the data type of the respective expression's return value may be different from the object's data type.

An object can be iterable, which means that the object is a collection of items (values ​​or other objects) that can be accessed by indexes. The object that serves as the provider of indexes to iterate an iterable is called an iterator.

Interestingly, every iterator is an iterable, but every iterable may not be an iterator.

Literals
The notations for constant values ​​of built-in data types are called literals. Literals can be integers, floating point numbers, complex numbers, strings, or bytes. Literals are immutable Python objects and the return value of an expression for them has the same data type as the literal.

Data types Classes
Python supports all fundamental data types (numbers, strings, booleans, etc.) as well as user-defined data types (user-defined classes). Data types are classes in Python. There are many data types available in Python, including:

Integers – belongs to the builtin or long class in Python. They can be decimal, binary, octal or hexadecimal numbers.

  • Decimal values ​​start with any non-zero digit, followed by other digits.
  • Binary values ​​start with 0b, followed by a sequence of 0 and 1.
  • Octal values ​​start with 0o, followed by a sequence of octal digits (0 to 7). Hexadecimal values ​​start with 0x, followed by a sequence of hexadecimal characters (0 to 9, A, B, C, D, E, and F).

In Python V3, all integers belong to the inner class because there is no distinction between inner and long . From Python 3.6 onwards, integers can include underscores (“_”) between digits and characters for visual assistance, such as “0b_0111_1111” is equivalent to “0b01111111”.

Floating point numbers – these values ​​belong to the float class. These are decimal numbers that can contain a decimal point, an exponent, or both. In Python, floating point values ​​generally have 53-bit precision.

Complex numbers – these values ​​belong to the complex class. A complex number can have two floating point values ​​with a “j” or “J” in the middle, or a floating point value on either side of the “j” or “J”. The real and imaginary part of a complex object that is defined by a variable called “ x” can be accessed as “x.real” and “x.imag”, respectively.

Strings – these are a sequence of characters that represent text values. Strings belong to the str class in Python. String objects can be formatted in byte or Unicode. Python V2 has ASCII encoding and Python V3 has Unicode encoding by default.

You can impose different coding styles on your Python script by adding a coding directive comment to the first line of the script. The encoding style only affects characters that can be used in strings and comments.

An encoding directive looks like this:

# encoding: utf-8

In Python, strings can have single, double, or triple quotes. You can also use a double in a single-quoted string and a single in a double-quoted string without an escape sequence. If a single is to be used in a single-quoted string and double is to be used in a double-quoted string, it must be “escaped” by a backslash as follows:

“He said “bring me a glass of water””
'I'm going to the office'

A string can also span more than one physical line in code using the backslash as follows:

“This is a very, very, very,\
very long text”

To include a newline in a string, the newline escape sequence (\n) must be used like this:

“This is a line. \nThis is the second line”

For multi-line strings, it is best to use triple-quoted strings. In triple-quoted strings, line breaks are treated as newline characters. Here is an example:

“””This is one line.
This is the second line.
This is the third line.”””

A string enclosed in single or double quotes cannot contain unescaped quotes – the line ends or has backslashes. A triple-quoted string cannot contain just one unescaped backslash. In a triple-quoted string, if a backslash is followed by a newline, the backslash and newline character are ignored.

To include backslashes, quotation marks, line endings, tabs, or special characters in a string object, be sure to use escape sequences.

Python allows these escape sequences in strings:

Escape sequence String literal
\ Backslash and newline ignored
\\ Backslash ( )
\' Single quote (')
\” Double quote (“)
\The ASCII Buzzer
\B ASCII Backtracking
\f ASCII form
\n ASCII line feed
\r ASCII transport return
\t ASCII Horizontal Guide
\v ASCII Vertical Guide
\ooo Character with octal valley ooo
\xhhh Character with hexadecimal value hh
\uHHH Unicode character with hexadecimal value HHHH
\uHHHHHHH Unicode character with hexadecimal value HHHHHHHH
\N{name} Unicode character with standard Unicode name

Raw Strings – These are quoted or triple-quoted strings preceded by “r” or “R” before the initial quote. In raw strings, escape sequences are not interpreted. If escape sequences are included in a raw string, they become part of the string without interpretation.

Additionally, a raw string cannot end with an odd number of backslashes followed by a final quote. If this occurs, the final quote will be escaped and this will result in a syntax error. Raw strings are useful when a string value has many backslashes.

Some valid examples of raw strings are:

r”\\” (equivalent to \\)
R'Olá\n' (equivalent to Hello\n)

Some examples of invalid raw strings are as follows:

r'\'
r'\\\'
R”Hello\n\”

In the next tutorial we will continue this discussion on the fundamentals of the Python programming language.

Back to the blog

Leave a comment

Comments need to be approved before publication.