print('Hello world!')
Hello world!
In this chapter, I will quickly take you through some basics of Python. We will not go into much detail, just enough to get started. By the end of this chapter, you will understand the absolute fundamentals of Python’s syntax. These include how Python uses indentations (spaces, tabs) to identify blocks of code, how to use the .
and how to extend Python’s abilities by importing packages.
You usually can use LabVIEW, C++ or Python for your DAQ work. If you opt for Python, you first need to understand the basics of how Python is set up before you can start using it in DAQ. This chapter will help you with that. Further, Python is a great scientific tool to know even if you do not use it for DAQ.
Let’s start our Pythonic journey by observing tradition and printing Hello World!. Try and run the following code. You should see the words Hello World!
as the output.
print('Hello world!')
Hello world!
Note:
print()
is called a function. You can think of a function as something that does a specific task. In this case, the print()
function accepts the “Hello world” argument and prints it to the screen.( )
, always follow a function. We use these parentheses to pass arguments to the function. Most functions expect arguments; the parentheses are left empty for those who don’t (e.g. close()
).print()
is a core, in-built function of Python. However, we can also define our own functions. This is an extremely powerful feature, which we will explore later.What we refer to as ‘Python’ is really the Python interpreter1. An interpreter works sequentially, one instruction at a time. So, for example, the following has two instructions.
print('Hello World')
print('Hello World again')
The interpreter stops and complains if there is an error in the command, it is currently executing. I will discuss more about the complaints later in ?sec-complaints.
Python is case-sensitive, so Print()
is different from print()
.
This means,
print('Hello World') # This WILL work
'Hello World') # This will NOT work Print(
Python is case-sensitive.
=
is not the same as ==
You will often see =
and ==
used in programming. These mean two very different things.
=
is used to set one thing equal to another.==
is used to check if something is equal to another (i.e. it is asking a question).= 'Batman' # Make name equal to 'Batman' name
== 'Batman' # Tell me if name is equal to 'Batman'?
name # Answer: True or False
You will see these used in the followng section. For the moment:
=
is not the same as ==
.=
assigns a value and==
asks a question.if
to make decisionsWe often have to make decisions to change the flow of our code. We accomplish this with the if
statement. Specifically, if
can be used to branch the flow of the programme. Here is an example.
= 'Batman'
name
if name == 'Batman':
print('Hello Hero | Batman!')
else:
print('Hello World!')
A typical if
statement asks a question (i.e. tests a condition) and has something to do if the answer is True
(printing Hello Hero | Batman!) and something else (printing Hello World! ) if it is not. Notice the use of :
and indentations (spaces or tabs) to define what to do if the answer is True
and what to do if the answer is False
.
Use an if else
block to make decisions.
This will work:
= 10
x print(x)
This will not work:
= 10
x print(x)
You can understand why there is an error by looking at the structure of the if
statement. Python uses an indentation to separate the True and False ‘blocks’. So, you cannot indiscriminately use indentations (spaces) with Python, as this will cause confusion.
One of the reasons that Python is so easy to read is its elegant use of indentation. Other languages, such as C++ or R, use brackets that can become clunky. For example, the previous statement in R or C++ looks like this:
if (name == 'Batman') {
print('Hello Hero | Batman!')
else {
} print('Hello World!')
}
if (name == "Batman") {
("Hello Hero | Batman!");
print} else {
("Hello World!");
print}
Indentations play a crucial role in Python.
Don’t mix spaces and tabs. Make it easy for yourself, and just use the tab
key consistently.
age
is a variable.Variables are ‘things’ that can hold information. You can give almost2 any name for a variable. However, it is best to provide a name that describes the data it is holding.
For example, we can store a student’s age using the variable a = 24
. However, it is better to write age = 24
. It is even better to write student_age = 24
.
Be careful about mixing up English with variables. For example, there is a difference between the following.
print(age) # Print the value of the variable age
print("age") # Print the English word 'age'
The former tries to print the value of the variable age. The latter will print the English word “age”.
I wrote ‘tries’ earlier because Python will complain if the variable age
has not yet been assigned a value. To get it to work, we need to do something like:
= 10
age print(age)
Note that you can use either matching pairs of ' '
or " "
for English words. However, it is always good to be consistent. You might be wondering why we need two ways of writing English. It is because, sometimes, you need to do things like:
print("You're twenty years old.")
You're twenty years old.
This is a good point to highlight escape sequences. Despite the funky name, it simply refers to special characters used when you type in English to convey certain formatting or actions, like creating a new line. While these characters are typically invisible, they serve important functions. Here are some useful escape sequences:
Escape Sequence | Meaning |
---|---|
\’ |
Single quote |
\\ |
Backslash |
\n |
Newline |
\t |
Horizontal Tab |
Here are some examples of how to use escape sequences.
Returning to the last example of the previous section, I can avoid using " "
by using the escaped version of '
.
print('You\'re twenty years old.')
You're twenty years old.
print('A\\B\\C')
A\B\C
print('A\nB\nC')
A
B
C
Notice the linebreaks!
print('A\tB\tC')
A B C
Notice the tabs!
Python uses all three types of brackets ( )
, [ ]
and { }
. Let me show you some quick examples.
Python uses ( )
in calls to function.
print('Hello!') # In functions
Python uses ( )
for mathematics.
1 + 2) * 5 # For math (
Python uses [ ]
for lists of data.
= [1, 2, 3, 4, 5] # A 1D list
py_list
= [[1, "A"], # A 2D list
py_list_2 2, "B"],
[3, "C"],
[4, "D"],
[5, "E"]] [
Python employs { } to store data using a key to identify a corresponding value. This method of data storage is known as adictionary.
= {
personal_info 'Names': 'Batman',
'Real Name': 'Bruce Wayne',
'Age': 55,
'Affiliation': 'Justice League',
'Universe': 'DC'
}
A dictionary is a neat way to store data because you can easily access information with a key; for example:
print(personal_info['Real Name'])
Bruce Wayne
I now like to talk about an essential feature of Python. For this, I will first use the examples below to highlight a potential limitation of pure Python.
Let’s say we want to calculate:
We can do this in Python by:
1 * ((2 - 3) + 4) ** 5 / 6
40.5
How about
4) # Will NOT work because
sqrt(# basic Python is limited
Error in py_call_impl(callable, dots$args, dots$keywords): NameError: name 'sqrt' is not defined
Oh, dear! Python cannot calculate square roots! But don’t worry, we can enhance Python’s capabilities by using packages. For instance, I can give Python more math skills by using (importing) the math
package.
import math # Adding(importing) the functions
# of the 'math' package
Now, we can use the sqrt()
function of the math
module.
4) math.sqrt(
2.0
math
is one of many modules that offer the sqrt()
functionality. So, let me also import the super useful Numpy
package so as to use its sqrt()
function.
import numpy as np # Importing Numpy and giving it
# an alias np because I am lazy
Now we can also use the sqrt()
function of the Numpy
module. Since I loaded it with an alias (np
) I can be lazy and use np
instead of the longer numpy
.
4) np.sqrt(
2.0
You might wonder why we need multiple sqrt()
functions. There are different versions because they have different capabilities and efficiencies. For example, the Numpy
version can handle a list of numbers:
4, 9, 16]) np.sqrt([
array([2., 3., 4.])
We will talk a lot more about Numpy
later. Before we move on, please note that you need to import packages only once3. Python will remember the functions until you restart the Python interpreter.
You often see a dot “.
” used in Python (and many other programming languages). This dot is used to indicate ownership! To see how this works, consider the code below.
4)
math.sqrt (4) np.sqrt (
In the first line, we use the sqrt()
function that belongs to the math module. In the second line, we use the sqrt()
function that belongs to Numpy
.
Everything in Python (e.g. numbers, letters) has hidden functions and attributes that belong to them. We can access these using the dot.
For example, the following will split the sentence into words.
"I am Batman".split()
['I', 'am', 'Batman']
However, the following will not work because a split()
function for numbers makes no obvious sense.
1234.split()
So, the things that can be accessed using the dot depend on what the dot is attached to. This will become more obvious very quickly as you use Python more. So don’t worry about the details for the moment.
The dot indicates ownership, and what it can access depends on the context.
Here are some packages that you will find useful for your DAQ work:
PyDAQmx: This accesses the National Instruments (NI) Data Acquisition (DAQ) library. It allows you to interact with NI DAQ hardware.
PyVISA: A Python library for controlling and interacting with measurement instruments and devices using various communication protocols like GPIB, USB, and LAN.
nidaqmx: Another package for National Instruments DAQ hardware, this one is a pure Python implementation. It provides a high-level interface for interacting with NI hardware.
DAQFactory: A complete SCADA (Supervisory Control and Data Acquisition) package for data acquisition, process control, and more.
pySerial: Useful for communicating with serial devices, often found in DAQ setups.
2.1.4 Comments
You will notice I wrote additional information (e.g.
WILL work
orwill NOT work
) in the above code by inserting a#
. These are called comments.#
and the end of the line constitutes the comment.Comments are for us humans to highlight aspects of the code that might not be obvious. Comments must be used intelligently. Unnecessary comments add clutter and make it difficult to read the code. For example, the following comment is redundant.
Here are more examples of writing comments.
You will develop a knack for writing good comments as you gain more experience. For the moment:
All programming languages offer the feature of inserting comments.