Programming Series - Part 1 - Python
In the modern world, where almost every device has smart functionality, being a programmer is an important tool in an engineer’s skillset. Python is a popular programming language for both beginning and advanced programmers due to its simplicity, readability, and versatility. In this module, we will explore the fundamental concepts of programming and introduce you to Python's basic syntax and structures.
Test Your Knowledge
2. Objectives
Upon completion of this learning module, you will be able to:
- Explain basic programming logic
- Understand the concepts of object-oriented programming (OOP)
- Recognize Python syntax
- Create a basic Python program
3. Basic Concepts
What’s the history of Python?
Python was created by Guido van Rossum in the late 1980s, while he was working at the National Research Institute for Mathematics and Computer Science in the Netherlands. The language was named after Monty Python, the British comedy group. Initially, Python was developed as a hobby, but gained popularity over time. Python was released to the public in 1991, quickly gaining a following because of its easy-to-learn syntax, rich library support, and community-driven development model.
Today, Python is widely used around the world for a variety of applications. It is popular in data science, machine learning, and artificial intelligence, due to its extensive libraries for numerical and scientific computing. Python is also used in web development, game development, automation and various other applications. Many popular websites, including Instagram, Pinterest, and Dropbox are built using Python. Additionally, Python is a popular language for embedded systems, where it is used to program devices such as microcontrollers, single-board computers (SBCs), and other devices.
What is Python exactly?
Python is an interpreted programming language, meaning that the programs are executed directly from the source code, without the need for a compilation step. In other words, an interpreter reads and executes the code line-by-line at runtime, converting it to machine code as it goes. This is in contrast to a compiled language, such as C++, where the source code is translated to machine code by a compiler before execution.
Python is also dynamically typed. A dynamically typed language is a programming language where the data type of a variable is determined at runtime, rather than at compile time. In a dynamically typed language, you don't need to declare the data type of a variable before using it, because the type is inferred based on the value assigned to the variable. This simplifies programming and makes the code more concise, but can also make programs more difficult to debug.
Python is an object-oriented programming language (OOP) and uses the concept of objects to represent and manipulate data. Objects have both properties (data) and methods (behavior), and the focus is on the interactions between objects rather than the procedures or functions of a program. We’ll dive into OOP in a future learning module.
4. Getting Started with Python
To get started with learning how to code in Python, you'll need a few basic things:
- A computer: Python can run on a variety of operating systems, including Windows, macOS, and Linux. It can also run on single-board computers (SBCs), such as the Raspberry Pi.
- Python interpreter: The interpreter is the program that reads and executes the code. You can download the latest version of the Python interpreter from the official Python website.
- Text editor or Integrated Development Environment (IDE): You'll need a text editor or an IDE to write your Python code. There are many options available, including popular text editors like Visual Studio Code, Sublime Text, and Notepad++. IDEs like PyCharm and Spyder offer more advanced features and integrated debugging tools.
After finishing this tutorial, you’ll probably want to seek out further learning resources. There are many free online resources available, including the official Python documentation, YouTube tutorials, and interactive coding websites such as Codecademy and DataCamp.
Hello World!
Creating a simple “Hello World!” application will introduce you to creating a Python program.
- Download and install the latest version of Python from the official Python website.
- Open a simple text editor such as Notepad (on Windows), TextEdit (on macOS), or Gedit (on Linux) to create your Python program.
- Type the following code into your text editor:
print("Hello World!")
- Save the file with the name "helloworld.py". The ".py" extension signifies that it is a Python file.
- Open a terminal or command prompt on your computer.
- Use the "cd" command to navigate to the folder where you saved the file. If you saved the file on your Desktop, you can navigate to it using the command:
cd ~/Desktop
- Type the following command to run the program:
python helloworld.py
The program will output “Hello World!”
Tabs or spaces
In Python, tabs or spaces are used to mark blocks of code that are grouped together, such as the body of a loop or function. Python uses indentation as a way of grouping statements, rather than using characters such as curly brackets or parentheses.
Proper indentation is essential in Python, as it affects how the code is interpreted and executed. If the indentation is incorrect, the code will result in a syntax error. Python code conventionally uses four spaces for indentation, but it is possible to use tabs, or a combination of tabs and spaces, as long as it is consistent throughout the program.
For example, in the following code, the indented lines are grouped as part of the if statement:
if i == 0:
result = i + 10
print(i)
The following code would result in a syntax error because the indentation is incorrect:
if i == 0:
result = i + 10
print(i)
Proper indentation also makes code more readable, an important quality when dealing with complex logic or nested structures.
Commenting in Python
A comment is a piece of text that is ignored by the interpreter and used to provide information or context about the code. Comments can help explain the purpose of the code, how it works, or provide other important details. To write a comment in Python, start it with the # symbol. Anything that follows the # symbol on a line is treated as a comment and is ignored by the interpreter. For example:
# This is a comment in Python
print("Hello, World!")
5. Learning Python Syntax
Variable types
A variable is a named reference to a value stored in the computer's memory. Variables can hold various types of data, including numbers, strings, lists, dictionaries, and more. To assign a value to a variable in Python, the assignment operator = is used. For example, the following code assigns the value 10 to a variable named x, which you can use later in the code:
x = 10
print(x) # This will print “10”
The value of a variable can be reassigned to a new value.
x = 20
print(x) # Now this will print “20”
Because Python is a dynamically typed language, the data types of variables do not have to be explicitly declared. The type of a variable is determined automatically based on the value assigned to it. Some of the built-in data types in Python include:
- Integer: represents a whole number (e.g. 5, -3, 0)
- Float: represents a floating-point number (e.g. 3.14, -2.5, 0.0)
- String: represents a sequence of characters (e.g. "hello", "cat", "42")
- Boolean: represents a logical value (True or False)
- List: represents a mutable sequence of elements (e.g. [1, 2, 3], ["car", "boat", "airplane"])
- Dictionary: represents a collection of key-value pairs (e.g. {"name": "Mike", "age": 30})
if statements
An if statement is a control structure that lets you execute code based on conditions. Certain code can be executed if a condition is True, with different code running if the condition is False.
In Python, an if statement is followed by a colon (:). The code to be executed if the condition is True is indented below the if statement.
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5 is True, because the value of x is 10, which is greater than 5. The code inside the if statement will be executed, outputting the text, "x is greater than 5". If x is set to 3, the print statement would not be executed and the program would move on to the next line of code.
An else statement specifies the code to be executed if the condition is False.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
In this example, the condition x > 5 is false, so the code inside the if statement will not be executed; instead, the code inside the else statement runs, outputting the text "x is less than or equal to 5".
Strings can also be compared with if statements. Like numbers, checking if strings are equal use the == comparator, while checking if they are not equal uses the != comparator. Python's built-in string methods can be used to compare strings in more complex ways. For example, the startswith() method can be used to test if a string starts with a certain substring, while the endswith() method can be used to test if a string ends with a certain substring. The in operator can be used to test if a string contains a certain substring. For example, "hello" in "hello world" would evaluate to True, while "hi" in "hello world" would evaluate to False.
Note that Python is case-sensitive. To ignore case sensitivity, strings can be converted to lowercase or uppercase using the lower() or upper() functions before comparison.
Working with Lists
Data elements are often grouped together into a collection. In many languages, this is done using a datatype called an array, which are collections of elements of a similar data type.
Python does not have a built-in array, but instead has a built-in data type known as a list that can be used in a similar fashion. Lists, however, can contain elements of differing data types. This example shows how to create a list in Python that includes numbers and a string.
my_list = [1, 2, 3, "four", 5.0] #A list uses square brackets []
The individual elements in a list can be accessed by their index. The index starts at 0. To access the first element of my_list:
print(my_list[0]) #This outputs a 1
Elements in a list can be modified by assigning new values to their index. To change the second element of my_list to 10:
my_list[1] = 10 #my_list is now [1, 10, 3, “four”, 5.0]
New elements can be added to a list using the append() method. To add the number 6 to the end of my_list:
my_list.append(6) #my_list is now [1, 10, 3, “four”, 5.0, 6]
What is a Dictionary?
Another way to group data is with a dictionary. A dictionary is a collection of key-value pairs. This example shows how to create a dictionary in Python:
my_dict = {"car": 1, "train": 2, "plane": 3} #A dictionary uses curly brackets {}
In this example, my_dict is a dictionary with three key-value pairs. The keys are "car", "train", and "plane", and their respective values are 1, 2, and 3. The individual values in a dictionary can be accessed by their key.
print(my_dict["car"]) #This outputs 1
The value associated with a key can be modified.
my_dict["train"] = 10 #my_dict is now {"car": 1, "train": 10, "plane": 3}
New key-value pairs can be added to a dictionary by assigning a value to a new key.
my_dict["boat"] = 4 #my_dict is now {"car": 1, "train": 10, "plane": 3, “boat”: 4}
Looping through data: for and while loops
One of the most useful capabilities of programming is being able to quickly loop through large collections of data, repeating a set of instructions with each iteration. In Python, there are two types of loops, the for loop and the while loop.
The for loop is used when iterating over a sequence of elements.
vehicles = ["car", "train", "plane"]
for vehicle in vehicles:
print(v)
The for loop iterates over the vehicles list, assigning each element to the variable vehicle. The print statement then prints vehicle to the console. The output of this code would be:
car
train
plane
The while loop is used when you want to repeat a block of code as long as a certain condition is true.
i = 0
while i < 5:
print(i)
i += 1
The while loop repeats the code block as long as i is less than 5. The code block first prints the value of i, and then increments i by 1. The output of this code would be:
0
1
2
3
4
What is a function and why should I use them?
A function is a block of code performing a specific task that can be called from other parts of a program. Functions are an essential part of writing clean, reusable, and modular code. The advantages of using functions include:
Reusability: Functions can be used in different parts of a program without having to rewrite the same code over and over.
Modularity: Functions allow you to break up a program into smaller, more manageable pieces.
Abstraction: Functions can be used to hide implementation details and provide a high-level interface for other parts of a program.
Maintainability: Functions make code more organized, easier to read and understand, and easier to maintain over time.
Testing: Functions can be tested in isolation from the rest of a program, making it easier to find and fix bugs.
In Python, functions are defined with the def keyword, followed by the function name, and the parameters in parentheses. The following function takes in two numbers as arguments, adds them together, and returns the result:
def add_numbers(x, y):
result = x + y
return result
Once you have defined a function, you can call it from other parts of your program. This example calls our add_numbers function, passing 3 and 5 as arguments.
sum = add_numbers(3, 5)
print(sum) #This code outputs 8
Inputting data
The input() function is a built-in function in Python that requests input from a user. When called, the program waits for the user to enter a value through the console.
name = input("What is your first name? ")
# format the name with the first letter capitalized and the rest in lowercase
formatted_name = name.capitalize()
# print the welcome message with the formatted name
print("Hello " + formatted_name + "! Welcome to the element14 Community!")
When you run the program, it will prompt the user to enter their first name:
What is your first name?
If the user enters "Mary" and hits enter, the program will output:
Hello Mary! Welcome to the element14 Community!
If the user enters "mARY" instead, the program will still output:
Hello Mary! Welcome to the element14 Community!
The capitalize() function formats the name with the first letter capitalized and the rest in lowercase, regardless of how the user entered the name.
6. Creating Hello World! On the Raspberry Pi
Hardware and Software Requirements
To follow this tutorial, you will need the following:
- Raspberry Pi (any model)
- MicroSD card with Raspbian installed
- Keyboard and mouse
- Monitor with an HDMI cable or a remote desktop app
- Internet connection (if you want to access your Pi remotely)
Step 1: Set up the Raspberry Pi
Before we start coding, we need to set up our Raspberry Pi.
- Insert the microSD card with Raspbian installed into the Raspberry Pi.
- Connect a keyboard, mouse, and monitor to the Raspberry Pi.
- Power on the Raspberry Pi and wait for Raspbian to boot up.
Instead of using a monitor, you also can connect to the Raspberry Pi remotely via SSH or VNC.
Step 2: Open a terminal
We will be using the terminal to write our code. To open the terminal, click on the terminal icon on the desktop.
Step 3: Create a Python file
In the terminal, type the following command:
nano hello.py
This creates a new file called hello.py and opens it in the Nano text editor.
Step 4: Write the code
Type the following code in Nano:
print("Hello World!")
Step 5: Save the file
Press Ctrl+X (close and exit), then Y (Yes, to save), then Enter.
Step 6: Run the script
To run the script, type the following command in the terminal:
python3 hello.py
This will execute the Python script and print "Hello World!" to the console.
7. Python Examples
Find the first even number in a list
numbers = [3, 5, 7, 4, 9, 11, 8, 2]
i = 0
while i < len(numbers) and numbers[i] % 2 != 0:
i += 1
if i < len(numbers):
print("The first even number is:", numbers[i])
else:
print("There are no even numbers in the array.")
First, we initialize a list called numbers. Then we create the variable i and set it to 0. i will store the index of the element containing the first even number. Our while loop checks two conditions: that i is less than the length of the numbers array (to avoid an index out of bounds error), and that the current number in the array at index i is not even. If both conditions are true, we increment i and continue the loop. Checking if the number is even is done with mod (%), which returns the remainder of a division operation. If the number divided by 2 gives a remainder of 0, that number is even and the loop stops.
After exiting the while loop, we use an if statement to check whether we found an even number in the array. If i is less than the length of the array, we print out the number at the index i (the index where the loop was stopped). Otherwise, we print a message saying that that no even numbers are present in the array.
The output of the code should be:
The first even number is: 4
Find the average of a list of numbers
numbers = [10, 20, 30, 40, 50]
sum = 0
count = 0
for num in numbers:
sum += num
count += 1
average = sum / count
print("The average is ", average)
The initial list of integers is called numbers. We initialize two variables, sum and count, and set them to 0. We use a for loop to iterate over each element in numbers. During each iteration, we add the current element to sum, and increment count by 1. After the loop, the average can be calculated by dividing sum by count.
The output of the code should be:
The average is 30.0
Read/write to a text file
# open a text file for writing. The ‘with’ statement automatically closes the file after reading (or writing) is complete
with open('example.txt', 'w') as f:
# write some text to the file
f.write('Hello, world!\n') #The ‘\n’ character is used to create a new line in the file.
f.write('This is an example text file.\n')
# open the same text file for reading
with open('example.txt', 'r') as f:
# read the contents of the file
contents = f.read()
# print the contents of the file
print(contents)
Programs often need to read and write to text files. Examples include reading from a configuration or JSON file, or writing to a log file. In this example, we open a text file (example.txt) that we want to write to, using the open function and the w mode (write). We then write some text to the file using the write method.
Next, we open the same text file using the open function and the r mode (read). We then read the contents of the file into a variable called contents using the read method.
Finally, we print the contents of the file to the console using the print function. When you run this code, you should see the following output:
Hello, world!
This is an example text file.
Read/Update a JSON file
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, the built-in json module allows us to work with JSON data. This example reads in a JSON file, updates one of its fields, and writes the modified data back to a new JSON file. First, let’s assume we have a JSON file named data.json with the following contents:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
The file can be read using the json.load() method:
import json
with open('data.json', 'r') as f:
data = json.load(f)
print(data)
This outputs the contents of the JSON file:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
If we need to update this user’s age to 31, we simply assign a new value to the corresponding key in the data dictionary:
data['age'] = 31
print(data)
This will output the updated dictionary:
{'name': 'Alice', 'age': 31, 'city': 'New York'}
Now we write the modified data back to a new JSON file using the json.dump() method:
with open('new_data.json', 'w') as f
json.dump(data, f)
This creates a new JSON file (new_data.json) with the following contents:
{
"name": "Alice",
"age": 31,
"city": "New York"
}
Connecting to a MySQL database with Python
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(user='user', password='password', host='host',
database='database') #user, password, host, and database are the credentials of the MySQL database that is being connected to
# Execute a query
cursor = conn.cursor() #A cursor is a data access object that can iterate over or update the set of rows in a table
query = "SELECT * FROM my_table" #This SQL command retrieves all the rows from a table called my_table
cursor.execute(query)
# Fetch the results
for row in cursor.fetchall():
print(row)
# Close the connection
cursor.close()
conn.close()
This example connects to a MySQL database and executes a SELECT query on a table called my_table. The results are fetched and printed to the console.
To connect to a MySQL database, the mysql-connector-python library is required. The library can be installed using pip:
pip install mysql-connector-python
Reading a temperature sensor with embedded Python
import machine
import time
# set up temperature sensor
sensor = machine.ADC(0)
# set up fan control
fan_pin = machine.Pin(2, machine.Pin.OUT)
# read temperature and control fan
while True:
temp = sensor.read()
if temp > 100:
fan_pin.on()
else:
fan_pin.off()
time.sleep(0.1)
The code imports the machine module, which provides access to the hardware on the microcontroller. It sets up an analog-to-digital converter (ADC) to read from a temperature sensor connected to the microcontroller's pin 0, and a digital output pin to control the fan connected to the microcontroller's pin 2.
The code then enters a while loop where it reads the temperature sensor and turns the fan on or off based on the reading. If the temperature reading is above 100, it turns the fan on by setting the fan pin to ON. Otherwise, it turns the fan off by setting the fan pin to OFF. The code then waits for 0.1 seconds before reading the temperature sensor again. The while True: line tells the loop to repeat indefinitely.
8. Other forms of Python
Several different types of Python have been created, each with its own strengths. While the syntax is similar, many of the implementations have been designed for use in specific use cases.
- CPython: This is the default implementation of Python, written in C. CPython is the most widely used and is the reference implementation for Python.
- Jython: Jython compiles Python code to Java bytecode, allowing Python code to run on the Java Virtual Machine (JVM).
- IronPython: IronPython runs on the .NET framework. It is designed to integrate seamlessly with the .NET environment and allow Python and .NET code to interoperate.
- PyPy: PyPy is a high-performance implementation of Python, with a just-in-time (JIT) compiler that can provide speed improvements over CPython in many cases.
- MicroPython: MicroPython is a version of Python that is designed to run on microcontrollers and other embedded systems. It includes a reduced subset of the Python standard library, and is optimized for low memory and limited computing resources.
- CircuitPython: CircuitPython is a variant of MicroPython that is optimized for use with microcontrollers in circuitry and robotics. It provides a number of built-in libraries and tools, making it easier to integrate with electronics and sensors.
9. Glossary
- Abstraction: a fundamental concept in programming that involves breaking down complex systems into simpler, more manageable parts. Abstraction allows programmers to create general, reusable solutions to common problems.
- Comment: In terms of programming, a comment is a piece of text that is added to code for the purpose of providing explanations, notes, or reminders to the programmer or other readers of the code. Comments are ignored by the interpreter or compiler and do not affect the behavior of the program.
- Compiled language: a programming language where the source code must be first compiled into machine code that can be directly executed by a computer's processor
- Data type: a classification of data based on the type of value it represents; examples include integers, floating-point numbers, and strings. Data types determine how the program will store, manipulate and interpret the data.
- Dynamically typed language: a programming language where the data type of a variable is determined at runtime, and do not have to be declared explicitly in the code
- Function: a self-contained block of reusable code performing a specific task that can be called from other parts of a program. It can accept input parameters and return output values, making it a powerful tool for the abstraction and organization of code.
- Integrated Development Environment (IDE): a software application that provides a comprehensive environment for developers to write, test and debug software. An IDE typically includes a code editor, compiler/interpreter, debugger, and other tools that assist with development, making it easier to write and maintain code.
- Interpreted language: a programming language where the source code is directly executed by an interpreter, without being compiled first
- Machine code or bytecode: a low-level programming language consisting of binary instructions that can be executed directly by a computer's CPU
- Object-oriented programming (OOP): a programming paradigm based on the concept of "objects", which can contain data, in the form of attributes, and code, in the form of methods. OOP focuses on creating reusable code by organizing data and behavior into classes and objects.
- Python interpreter: a program that reads and executes Python code. It translates Python code into machine code that can be understood and executed by the computer's CPU.
- Reusability: the ability to reuse existing code to perform a specific task, rather than rewriting the same code again from scratch. This saves time and effort and makes the code more efficient and organized.
- Statically typed language: a programming language where the data type of a variable is determined at compile time
- Syntax error: a type of error that occurs when the code violates the grammar rules of the programming language. The code cannot be executed until the syntax error is corrected.
- Variable: a named storage location in a computer's memory that holds a value or data, which can be changed during program execution
*Trademark. element14 is a trademark of AVNET. Other logos, product and/or company names may be trademarks of their respective owners.
Test Your Knowledge
Programming 1
Score 100% on our Programming I Quiz, then rate the document and leave your feedback as a comment to earn this badge.
Are you ready to demonstrate your Python essentials knowledge? Then take a quick 10-question multiple choice quiz to see how much you've learned from this module.
To earn the Essentials Programming 1 Badge, read through the learning module, attain 100% in the quiz at the bottom, and leave us some feedback in the comments section below.