2  Basics You Need to Know

Credit Fabien Maussion and xkcd.

What To Expect In This Chapter

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.

Why Is This Important To You?

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.

2.1 Some Python Basics

2.1.1 Functions

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.
  • Parentheses, ( ), 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.
  • The above is an example of what we call code. It is a set of instructions written using some programming language.
Remember
  • A function is ‘something’ that executes a specific task.
  • A function may or may not accept arguments.
  • We can define our own functions.

2.1.2 Python is interpreted

What we refer to as ‘Python’ is really the Python interpreter. 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.

2.1.3 Python is sensitive

Python is case-sensitive, so Print() is different from print().

This means,

print('Hello World')      # This WILL work
Print('Hello World')      # This will NOT work
Remember

Python is case-sensitive.

2.1.4 Comments

You will notice I wrote additional information (e.g. WILL work or will NOT work) in the above code by inserting a #. These are called comments.

  • Anything between the # and the end of the line constitutes the comment.
  • Python ignores all comments.

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.

print("Hello world" )     # Printing "Hello World."

Here are more examples of writing comments.

# This is a comment
print('One')              # This is a comment.
# print('Two')            # The interpreter ignores this line.
print('Three')            # This is
                          # also a way to
                          # write comments

You will develop a knack for writing good comments as you gain more experience. For the moment:

Remember

All programming languages offer the feature of inserting comments.

2.1.5 = 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).
name = 'Batman'   # Make name equal to 'Batman'
name == 'Batman'  # Tell me if name is equal to 'Batman'?
                  # Answer:  True or False

You will see these used in the followng section. For the moment:

Remember
  • = is not the same as ==.
  • = assigns a value and
  • == asks a question.

2.1.6 Use if to make decisions

We 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.

name = 'Batman'

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.

Remember

Use an if else block to make decisions.

2.1.7 Indentations (spaces) are sooo IMPORTANT!

This will work:

x = 10
print(x)

This will not work:

x = 10
 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") {
  print("Hello Hero | Batman!");
} else {
  print("Hello World!");
}
Remember

Indentations play a crucial role in Python.

Be careful!

Don’t mix spaces and tabs. Make it easy for yourself, and just use the tab key consistently.

2.1.8 ‘age’ is English, age is a variable.

Variables are ‘things’ that can hold information. You can give almost 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:

age = 10
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.

2.1.9 Escape sequences

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.

  1. 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.
  2. print('A\\B\\C')
    A\B\C
  3. print('A\nB\nC')
    A
    B
    C

    Notice the linebreaks!

  4. print('A\tB\tC')
    A   B   C

    Notice the tabs!

2.1.10 Brackets

Python uses all three types of brackets ( ), [ ] and { }. Let me show you some quick examples.

  1. Python uses ( ) in calls to function.

    print('Hello!')             # In functions
  2. Python uses ( ) for mathematics.

    (1 + 2) * 5                 # For math
  3. Python uses [ ] for lists of data.

    py_list = [1, 2, 3, 4, 5]   # A 1D list
    
    py_list_2 = [[1, "A"],      # A 2D list
                 [2, "B"],
                 [3, "C"],
                 [4, "D"],
                 [5, "E"]]
  4. 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

2.2 Giving Python Superpowers

2.2.1 Packages

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:

1×((23)+4)56

We can do this in Python by:

1 * ((2 - 3) + 4) ** 5 / 6
40.5

How about 4?

sqrt(4)     # Will NOT work because 
            # 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.

math.sqrt(4)
2.0

2.2.2 There Are Many Packages

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.

np.sqrt(4)
2.0

2.2.3 Why so many packages?

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:

np.sqrt([4, 9, 16])
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 once. Python will remember the functions until you restart the Python interpreter.

Remember
  • You can give Python ‘superpowers’ by importing packages.
  • You must import a package only once.
  • There are different ways to import packages (You don’t have to remember the syntax; just know there are several ways to get it done.).

2.2.4 The dot (.)

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.

math.sqrt (4)
np.sqrt (4)

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.

Remember

The dot indicates ownership, and what it can access depends on the context.

2.2.5 Packages for DAQ

Here are some packages that you will find useful for your DAQ work:

  1. PyDAQmx: This accesses the National Instruments (NI) Data Acquisition (DAQ) library. It allows you to interact with NI DAQ hardware.

  2. PyVISA: A Python library for controlling and interacting with measurement instruments and devices using various communication protocols like GPIB, USB, and LAN.

  3. 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.

  4. DAQFactory: A complete SCADA (Supervisory Control and Data Acquisition) package for data acquisition, process control, and more.

  5. pySerial: Useful for communicating with serial devices, often found in DAQ setups.


  1. The latest version of the Python interpreter is 3.11.5.↩︎

  2. Except the keywords used in the Python language like if, for, while, is ↩︎

  3. You do not have to teach Python the same thing twice!↩︎