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 jump to controlling hardware via Python scripts, it will be useful to first have a strong foundation of the language. So, in this tutorial, we discuss the basics of Python programming and learn about a few best practices, including the style of writing code in Python.
Although this is a crash course, you’ll be able to run short Python scripts on Raspberry Pi (RPi). So, keep your Raspbian booted up and the IDLE opened. And, in case you note a blank screen on your monitor when powering on your RPi desktop, occasionally it fails to boot up a few days after installation.
A couple of reasons: a loose connection of the MicroSD card or the HDMI cable. If this occurs, re-plug in the MicroSD card and HDMI cable, and power up RPi on your desktop again. If this does not solve the problem, try re-installing Raspbian on the MicroSD card.
Python syntax
Python syntax is different from other programming languages. In most other programming languages, statements (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. So, adding an unintentional space at the start of a line (a physical line in the text editor) will block the code differently. This means indentations matter a lot in Python. This is sometimes off-putting or daunting for developers that are used to other languages.
In Python, each physical line of code is interpreted as a single logical line (a statement of code) unless it continues on. If a logical line is too long to fit in a single physical line, the first line can be terminated by a backslash (“\”). This indicates that the logical line continues on in the next physical line.
When a logical line continues to the next one, any indentation in the second line is irrelevant. But if the second line is not a continuation of the first (because there’s no backslash at its end), this marks the end of that logical line. When a logical line continues, it should not have any comment except in the last physical line.
Similar to other programming languages, however, a block of code in Python is indicated by braces (“{“) or “begin/end” delimiters. The first line of code should not be indented. But in Python, all adjacent lines indented by the same amount will be identified as a block of code (as if they’re between braces).
It’s recommended to use only spaces or tabs to indent code in Python, but avoid mixing them (Version 3 doesn’t allow for this to occur). The tabs may also be treated differently in different text editors, so it’s ideal to avoid them. It’s best to use four spaces (logical columns 5, 9, 13, etc.).
If there is an open delimiter — such as brace (“{“), bracket (“[“), or parenthesis (“(“) on a physical line, the next line is automatically continues until the closing delimiter of the same type occurs.
Comments
All of the comments in Python start from a hashtag (“#”). Everything right of the hashtag, until the end of a line, is treated as a comment by the Python interpreter. Comments are not processed as lines of codes. Rather, these are text strings that are inserted into the code to provide other programmers useful information.
It’s recommended to use comments liberally so that your code is readable. Such comments should state significant things about the code without iterating obvious ones.
For example, a comment in Python might look like this:
# This script controls interfacing of a character
# LCD with Raspberry Pi GPIO and manage displaying
# string messages on it.
Identifiers
Identifiers are names given to variables, constants, functions, classes, modules, and other objects in any programming language.
In Python, any identifier should start with a letter (ASCII-compatible) or underscore, which can be followed by more letters, digits, or underscores. Punctuation characters cannot be used as identifiers.
The identifiers in Python are case-sensitive. For instance, “GPIO_status” and “gpio_status” refer to different objects.
Here are a few 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
Keywords
Keywords are the reserved words and they also cannot be used as identifiers for other objects. Python V2 has 31 keywords.
They are:
and as assert break
class continue def del
elif else except exec
finally for from global
if import in is
lambda not or pass
print raise return try
while with yield
Python V3 has 33 keywords. They are:
and as assert break
class continue def del
elif else except false
finally for from global
if import in is
lambda none nonlocal not
or pass raise return
true try while with
yield
Statements
Statements are logical lines of code that perform a type of operation on the data.
In Python, statements can be simple or compound statements. Simple statements are single logical lines of code that are typically an assignment of values to variables or simple expressions. Compound statements contain more than one simple statement grouped as a block of code with the same amount of indentation.
Each simple statement within a compound statement is called a clause. A clause may 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 declarations in Python — only simple and compound statements.
Object-oriented programming
The code in any programming language is used to process data. The data can be constant values, ordered, and unordered group of constant values, or more complex data structures (such as classes and objects).
Essentially, each type of data has a type. The type of a datum 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 done on it.
A reference name accesses each datum in the code. This reference name can be an identifier — other than the keywords and the identifiers that are used in this scope. So, references for certain data should always be unique within the same scope.
The references that point to a datum where the content can be changed are called variables. Variables server as references that bind to memory locations where the content of that location can be changed in the code. The references that point to a datum where the content will never change in the code are called constants.
The value assigned to a reference defined as a constant cannot be changed once it is established.
The statements of a coding process are the content of the variables. These statements can be simple or compound. The compound statements can be used for decision making or changing the sequence of the execution of other statements. 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 can also be more complex data structures where the related data values and operations on them are grouped as a class. Typically, a class represents the type of a real object (like a class) that’s defined to represent people.
Any real object will have some properties that are defined as attributes in a class. These attributes are special variables that bind to a particular class and represent the properties of the object, which are also represented by the class.
There can be some operations on the content of the attributes. The functions (bind to the class) that process content of the class attributes are called methods.
Particular instances of a class are called objects (code objects). These objects have all of the attributes and methods defined for their class. The objects belong to built-in or user-defined classes. In object-oriented programming, data is always processed as the values associated with the variables and attributes of objects.
Python objects, classes, data types, and IDs
Python is also different from other languages in the ways that it handles data. For example, in Python, everything is an object. This includes the values assigned to variables or attributes that are the objects of built-in data type classes.
The data types are, technically, built-in Python classes. When a value is assigned to a variable or an attribute, the value becomes the object that belongs to a data type class. Another way we can say this: the value becomes an instance of a Python built-in, data type class.
What this means is that In Python, there’s no need to declare the data type of the references. Python implicitly assumes the data type of the reference. That is why keywords are unnecessary for declaring data types in Python.
Another interesting function of Python is the IDs. Depending on the implementation and platform, Python only stores unique 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, iterables, and iterators
Python objects can be mutable or immutable. When performing any operation (via the 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 the object.
When performing operations on mutable objects, the data type of the return value of the respective expression can be different from the data type of the object.
An object can be iterable, which means that the object is a collection of items (values or other objects) that can be accessed by indices. The object that serves as a provider of the indices 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. The literals can be integers, floating-point numbers, complex numbers, strings, or bytes. The literals are immutable Python objects and the return value of an expression for them has the same data type as of the literal.
Data types classes
Python supports all fundamental data types (numbers, strings, Boolean, etc.), as well as user-defined data types (user-defined classes). The data types are classes in Python. There are many data types available in Python including:
Integers – belong to the int or long class in Python. They can be decimal, binary, octal, or hexadecimal numbers.
- The decimal values start with any non-zero digit, followed by other digits.
- The binary values start with 0b, followed by a sequence of 0 and 1.
- The octal values start with 0o, followed by a sequence of octal digits (0 to 7). The 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 of the integers belong to the int class because there’s no distinction between the int 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 may contain a decimal point, exponent, or both. In Python, floating-point values generally have a 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-between, or a floating-point value on either side of “j” or “J.” The real and imaginary part of a complex object that’s defined by a variable named “x” can be accessed as “x.real” and “x.imag,” respectively.
Strings – these are a sequence of characters that represent text values. The strings belong to the str class in Python. The string objects can be byte or Unicode formatted. Python V2 has ASCII encoding and Python V3 has Unicode encoding by default.
It’s possible to enforce different encoding styles to the Python script by including a coding directive comment in the first line of the script. The encoding style only affects the characters that can be used in the strings and comments.
A coding directive looks like this:
# coding: utf-8
In Python, the strings can be single, double, or triple-quoted. It’s also possible to use a double in a single-quoted string and a single in a double-quoted string without an escape sequence. If a single has to be used in a single-quoted string and double has to be used in a double-quoted string, it must be “escaped” by a backslash as follows:
“He said\”get me a glass of water\””
‘I\’am going to office’
A string can also span over more than one physical line in code by using the backslash as follows:
“This is a very, very, very, \
very long text”
To include a new line in a string, the new line escape sequence (\n) should be used like this:
“This is one line. \n This is second line”
For multi-line strings, it’s best to use triple-quoted strings. In triple-quoted strings, the line breaks are treated as new-line characters. Here’s an example:
“””This is one line.
This is second line.
This is third line.”””
A single or double-quoted string cannot contain an unescaped quotes — the line either ends or it backslashes. A triple-quoted string cannot contain only an unescaped backslash. In a triple-quoted string, if a backslash is followed by a new line, the backslash and new line character will be ignored.
To include the backslash, quotes, line ends, tabs, or special characters in a string object, be sure to use the escape sequences.
Python allows these escape sequences in strings:
Escape sequence | String literal |
\<newline> | Backslash and Newline ignored |
\\ | Backslash (|) |
\’ | Single Quote (‘) |
\” | Double Quote (“) |
\a | ASCII Bell |
\b | ASCII Backspace |
\f | ASCII Formfeed |
\n | ASCII Linefeed |
\r | ASCII Carriage Return |
\t | ASCII Horizontal Tab |
\v | ASCII Vertical tab |
\ooo | Character with octal vale ooo |
\xhh | Character with hexadecimal value hh |
\uHHHH | Unicode character with hexadecimal value HHHH |
\uHHHHHHHH | 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 leading quote. In raw strings, escape sequences are not interpreted. If the escape sequences are included in a raw string, they become part of the string without interpretation.
Also, a raw string cannot end with an odd number of backslashes followed by an ending quote. If this occurs, the ending quote will be escaped and this would result in a syntax error. The raw strings are useful when a string value has many backslashes.
A few valid examples of raw strings are:
r”\\” (equivalent to \\)
R’Hello\n’ (equivalent to Hello\n)
Some invalid examples of raw strings are as follows:
r’\’
r’\\\’
R”Hello\n\”
In the next tutorial, we’ll continue this discussion on the basics of Python’s programming language.
You may also like:
Filed Under: Featured Contributions, Python, Tutorials
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.