3

Python Programming Essentials

In the previous chapter, we got acquainted with Python’s history and implementations. We also learned how to use an online editor by the Micro:bit Foundation for programming a Micro:bit device (also referred to as a board). We installed the Thonny and Mu IDEs for MicroPython programming and explored their useful features for programming Micro:bit with MicroPython. I hope that you have had an opportunity to write a basic program for Micro:bit.

In this chapter, we will get started with hands-on programming with MicroPython. We will get comfortable with the Python programming syntax before getting into creating projects with MicroPython and Micro:bit. If you are new to Python programming, this chapter will help you to gain the essentials. We will explore the following list of topics together:

  • Getting started with Python programming
  • Conditional statements
  • Loops
  • Computing prime numbers, factorials, and Fibonacci series

Let’s get started with the basics of programming.

Technical requirements

We do not need anything else besides a computer, a Micro:bit device, and a micro USB cable for the demonstrations in this chapter.

Getting started with Python programming

A program is a set of instructions. A computer runs those instructions in the given sequence and produces an output (also known as a result). In this section, we will take the first steps toward writing our own small programs with the Python syntax. If you recollect, I have mentioned in the previous chapter that the MicroPython implementation is largely compatible with Python 3. In this chapter, we will explore the common syntax for Python 3 and MicroPython. To keep it simple, we won’t be exploring any features of Micro:bit and specialized MicroPython syntax.

In the previous chapter, we ran simple statements on REPL with the online Python editor, Thonny, and Mu. I prefer using the Thonny editor and will continue using it for the rest of the book, but you can use the IDE of your choice. Open any of these editors, and then open the REPL interface. I hope that you are already comfortable working with this simple interface. Let’s use it to further enhance our knowledge of Python programming. We can write simple instructions in REPL (also known as the Python shell) to execute them immediately. In the terminology of programming languages, these instructions are known as statements. The following code snippet is a simple statement executed in the Python shell:

>>> 2 + 2
4

Try it now. Try other mathematical operators such as -, *, /, and %. The following are examples of these:

>>> 2 - 2
0
>>> 2 / 2
1.0
>>> 2 % 2
0
>>>

The numbers we are using are operands. I have only used one number with the operands, however, we can (and should) try other numbers too. And why limit ourselves to integers when we can also use numbers with a decimal point? Such numbers are known as floating-point numbers or floats. The following are examples of floating-point arithmetic:

>>> 22/7
3.142857
>>> 1.71828 + 1
2.71828
>>> 10.807 - 1
9.807

Well, that brought back memories of my school science lessons. We have already written the customary Hello, World program in the previous chapter. So, let’s try something else now:

>>> print(2)
2
>>> print(2+2)
4

Let’s print a string:

>>> print("This is a test string)
Traceback (most recent call last):
  File "<stdin>", line 1
SyntaxError: invalid syntax

Aghrrrr! I did it deliberately. The invalid syntax error is generated because we missed closing the string with a double quote. Python interpreters classify this as a syntax error. Let’s rectify and run it again:

>>> print("This is a test string")
This is a test string

We can also use single quotes to specify a string as follows:

>>> print('This is a test string')
This is a test string

Let’s understand the concept of Boolean values. We can have a special variable that stores the truth value in programming terminology. These values are known as Boolean values (a tribute to George Boole), and such a variable is a Boolean variable (or Boolean data type). There are only two Boolean values, True and False:

>>> True
True
>>> False
False

We can perform logical operations as follows:

>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> True or True
True
>>> not True
False
>>> not False
True
>>>

These are logical operations. True and False are keywords and are case sensitive. If you make a mistake, the interpreter returns the syntax error as follows:

>>> not true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' isn't defined

In the next section, we will understand and experiment with the concept of variables in detail.

Variables

We have directly handled strings, numbers, and Boolean values. We can store them in the main memory of the computer (RAM), where programs are executed. We can also assign them names to refer to them again when needed. These named storage areas in RAM are known as variables. We can only refer to them from the program in which they are created. Once the program stops running, they cannot be accessed. Also, they are limited to the program that created them even when the program is running, and outside programs cannot access them directly.

If you have worked with C, C++, Java, and other programming languages, you will know that you have to declare the data type of the variable in advance, as follows (the sample C code snippet won’t be executed by the Python interpreter):

int a = 2;
float pi = 3.14;

In these languages, after creating a variable with a particular data type, we cannot change its data type. Python is very flexible in that regard. We do not have to declare data types, and we can change the data type of any variable on the fly by assigning it a value of that particular data type as follows:

>>> a = 1
>>> a
1
>>> a = 3.14
>>> a
3.14
>>> a = 'c'
>>> a
'c'
>>> a = 'Hello, World!'
>>> a
'Hello, World!'

Try that one. And also, try changing the value of a again.

Now, let’s run a few statements:

>>> a = 1
>>> b = 2.14
>>> print(a + b)
3.14
>>> print("My first script!!")
My first script!!

Now, let’s collect all four statements and copy and paste them into the editor. Save the file in a directory and name the file prog00.py. Thonny automatically assigns it a py extension. I prefer to maintain chapter-wise directories. I recommend you do the same. Refer to the code bundle of this book for more information. After saving the program, click on the Run (green triangle) button in the menu, as shown in the following screenshot:

Figure 3.1 – Executing a Python script

Figure 3.1 – Executing a Python script

You can also press the shortcut F5 on the keyboard to run the program in the current editor window. We can also execute the program by selecting the options Run | Run current script from the main menu as shown in the following screenshot:

Figure 3.2 – Executing a Python script using the Run menu

Figure 3.2 – Executing a Python script using the Run menu

The Thonny IDE executes the current program in the editor window and displays the result in the REPL (shell) window as shown in the following screenshot:

Figure 3.3 – Output of a script execution

Figure 3.3 – Output of a script execution

Congratulations! This is the very first program we wrote and executed from scratch. Note that the program is saved on the local computer, but it is running in the main memory of the BBC Micro:bit device connected to the computer. If we reboot the Micro:bit by disconnecting it and reconnecting it or by pressing Ctrl + D using the REPL, the program will not be there in the Micro:bit. We can also store the program with any name in the Micro:bit. And if we want the Micro:bit to run the program every time we power it up or reboot, then we can save the program in the Micro:bit with the name main.py. While practicing programming, I usually save the files on the local computer and run them on Micro:bit from the Thonny IDE. While deploying projects (such as a robot), I create a main.py file in the Micro:bit and save the code there.

Code comments

We can add comments to the code. Code comments are the parts of the program that are not executed. However, they provide additional information about the program. Comments can be thought of as basic documentation of the program. We can write a single-line comment by using # as follows:

# Sample program
# Author : Ashwin Pajankar
a = 1
b = 2.14
print(a + b)
print("My first script!!")

If you run the program, then the output will be the same as earlier. This is because the interpreter ignores the text in the comments. We can also have multiline comments as follows:

# Sample program
# Author : Ashwin Pajankar
'''Multiline comment line 1
line 2
'''
"""Another way of writing
multiline comments"""
a = 1
b = 2.14
print(a + b)
print("My first script!!")

You must have noticed that the Thonny IDE highlights the different components of the program in different colors. This is one of the advantages of using IDEs for programming.

Let’s practice a few more programs now.

Arithmetic, string, and logical operations

The following are examples of arithmetic, string, and logical operations:

a = 10
b = 2
c = 4
d = a + b / c
print(d)
str1 = "Test"
str2 = 'string'
str3 = str1 + ' ' + str2
print(str3)
b_val1 = True
b_val2 = False
print(b_val1 and b_val2)
print(b_val1 or b_val2)
print(not b_val1)

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
10.5
Test string
False
True
False

Data type conversion

In Python, we can change the data type of variables. This is known as Data Type Conversion. Consider the following program:

str1 = "The value of Pi is "
pi = 22/7
print(str1 + pi)

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: can't convert 'float' object to str implicitly

This is because the variables str1 and pi are not of the same data type. Our goal is to print a string. So, it is logical to convert the variable pi into a string. The built-in str() method does the same. Let’s rectify the program as follows:

str1 = "The value of Pi is "
pi = 22/7
print(str1 + str(pi))

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
The value of Pi is 3.142857

Following is another example:

str1 = "3.14"
str2 = "1234"
pi = float(str1)
num = int(str2)
comp = complex(2, 3)
print(pi)
print(num)
print(comp)

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
3.14
1234
(2+3j)

Handling user input

We can accept user input using the built-in method input(). The following is the sample code:

name = input("Enter your name :")
print("Welcome " + name)

The output will prompt you for input. After entering an input, it shows the following output:

>>> %Run -c $EDITOR_CONTENT
Enter your name: Ashwin
Welcome Ashwin

We will soon use this concept to learn other important concepts in programming. Next, we will learn about and experiment with conditional statements in Python.

Conditional statements

We can write conditional statements in Python. The conditional flow can be achieved with the if keyword. It is used in combination with a Boolean expression. If the expression returns True, then the block listed under if is executed. In Python, code blocks are denoted with indentation. In fact, indentation is the only way to create a code block (unlike { and } in C, C++, and Java). Following is an example of the usage of the if statement:

num = int(input("Enter a number :"))
if num > 10 :
    print("The entered number is greater than 10.")

Run the program and see the output. We can enhance our logic with the else clause as follows:

num = int(input("Enter a number :"))
if num > 10 :
    print("The entered number is greater than 10.")
else:
    print("The entered number is less than or equal to 10.")

We can also create an elif ladder as follows:

num = int(input("Enter a number :"))
if num > 10 :
    print("The entered number is greater than 10.")
elif num == 10:
    print("The entered number is equal to 10.")
else:
    print("The entered number is less than 10.")

This is how we can use an elif construct in Python.

Loops

Looping means repeating something. It is a very common programming construct. We can use it to perform repetitive actions in our programs. Let’s start with the while construct. This construct evaluates a Boolean expression in every loop, and as long as the expression returns True, the code block under while is run repeatedly. When the Boolean expression returns False, the loop terminates. Following is a simple example:

i = 0
while i < 10:
    print(i)
    i = i + 1

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
0
1
2
3
4
5
6
7
8
9

Sometimes, we may wish to run the loop forever. In such cases, we can use 1 or True in place of the Boolean expression in the while construct as follows:

#while 1
while True:
    print("Processing...")

In order to exit the loop, press Ctrl + C in the shell. Following is the output:

Processing...
Processing...
Processing...
Processing...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt:

Such loops are known as infinite loops and can only be interrupted by manually interrupting the program under execution. If we make a mistake in the Boolean expression so that it never returns False, then our loop turns into an infinite loop. So, we have to be a bit careful while writing loops.

We can also have for loops. In this section, we will learn how to create for loops with the keywords for and in and the built-in method range(). The method range() creates a range from the given arguments. Following are a few possible cases of usage. You can figure out the functionality of the method range() from the arguments passed:

for i in range(5):
    print(i)
print('------------')
for i in range(5, 10):
    print(i)
print('------------')
for i in range(0, 10, 2):
    print(i)
print('------------')

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
0
1
2
3
4
------------
5
6
7
8
9
------------
0
2
4
6
8
------------

In the first case, we are iterating from 0 to 4. In the second case, we are iterating from 5 to 9. The second argument passed to the call of range() is non-inclusive. In both cases, the size of the step is 1. In the final case, we are iterating from 0 to 9 in increments of 2.

To have a better understanding of the mechanism, change the values of the arguments passed to the call of the method range(). As an exercise, print all the odd numbers between 1 to the number accepted as user input with the method input().

In the next section, we will see the applications of the concepts we just learned. We will use the programming constructs we learned to compute prime numbers, Fibonacci series, and factorials.

Computing prime numbers, factorials, and Fibonacci series

We can find out if a number is prime by checking its divisibility with all the numbers less than it. If a number is only divisible by 1 and itself, then it’s a prime number. We can compute prime numbers in a given range using the for loop twice as follows:

lower = 2
upper = 100
for num in range (lower, upper+1):
    for i in range(2, num):
        if(num % i) == 0:
            break
    else:
        print(num)

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
2
3
5
7
…
97

We can also compute the factorial of a number. The factorial of 0 and 1 is 1. For the rest of the integers, the multiplication of all the integers from 1 to that integer is factorial. Let’s write a simple program that computes the factorial of a given number as follows:

num = int(input("Please enter an integer: "))
fact = 1
if num == 0:
    print("Factorial of 0 is 1.")
else:
    for i in range (1, num+1):
        fact = fact * i
    print("The factorial of {0} is {1}.".format(num, fact))

In the preceding program, we are already familiar with all the code except the method format(). It formats the specified values and replaces them with the string’s placeholder. Following is the output of a few sample runs:

>>> %Run -c $EDITOR_CONTENT
Please enter an integer: 0
Factorial of 0 is 1.
>>> %Run -c $EDITOR_CONTENT
Please enter an integer: 1
The factorial of 1 is 1.
>>> %Run -c $EDITOR_CONTENT
Please enter an integer: 5
The factorial of 5 is 120.
>>> %Run -c $EDITOR_CONTENT
Please enter an integer: 10
The factorial of 10 is 3628800.
>>> %Run -c $EDITOR_CONTENT
Please enter an integer: 20
The factorial of 20 is 2432902008176640000.

Each number is the sum of the two preceding ones in the Fibonacci sequence. It begins with 0 and 1. The third number is 0 + 1 = 2. The fourth number is 1 + 2 = 3. The fifth number is 2 + 3 = 5. And so on, we can calculate as many numbers in this series as we desire. The following program demonstrates 20 numbers in this sequence. We are already familiar with all the syntax used in the code:

a = 0
b = 1
i = 0
while i < 20:
    print(a)
    c = a + b
    a = b
    b = c
    i = i + 1

The output is as follows:

>>> %Run -c $EDITOR_CONTENT
0
1
1
2
3
5
…
610
987
1597
2584
4181

So, this is how we can use loops to compute a list of prime numbers, Fibonacci series, and factorials. Practicing with these examples has now got us acquainted with the syntax of MicroPython and the Thonny IDE.

Summary

In this chapter, we learned the basics of Python syntax. The advantage of this chapter is that if we wish to use this knowledge elsewhere for Python programming, we can do so. As an exercise for this chapter, run all these programs using the reference Python 3 interpreter, CPython, provided by Python Software Foundation (www.python.org). All the knowledge we gained in this chapter will be employed when we start tinkering with the hardware of Micro:bit down the line.

In the next chapter, we will continue our journey and explore the advanced functionalities offered by Python.

Further reading

MicroPython’s home page has a lot of documentation hosted at https://docs.micropython.org/en/latest/. It is worth exploring it. Also, if you are interested, you can visit the documentation of Python 3 hosted at https://docs.python.org/3/. The MicroPython port specific to Micro:bit is documented at https://microbit-micropython.readthedocs.io/en/v2-docs/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.35.77