Building Robots with Python and Raspberry Pi
  • Introduction
  • Chapter1
  • Chapter2
  • Chapter3
  • Chapter4
  • Chapter5
  • Chapter6
  • Chapter7
  • Chapter8
  • Chapter9
  • Chapter10
Powered by GitBook
On this page
  • 2.1 Interactive Mode
  • 2.2 Script Mode
  • 2.3 python syntax
  • 2.3.1 Comments
  • 2.3.2 Variables
  • 2.3.3 Standard Data Types
  • 2.3.4 Input and Output
  • 2.3.5 Conditionals and Control Flow
  • 2.3.6 Loops
  • 2.3.7 Functions
  • 2.3.8 Modules
  • Exercise 2.3

Chapter2

PreviousChapter1NextChapter3

Last updated 7 years ago

Python is a general-purpose, interpreted, interactive, object-oriented, and high-level programming language. It can be used under interactive mode or script mode. It's a very powerful language and is used widely in various fields. It takes a lot to describe the entire language specification and it's not practical to cover them all here. Nor is it necessary to describe the entire language since we don't need to use all aspect of the language. So, here, we will only show the basics to get you going in learning a language and use it to program the robots. For detailed description, please refer to the (make sure you are on the right version). You can always consult the documentation for more advanced topics once you master the basics.

2.1 Interactive Mode

Under interactive mode, python can be used as an advanced calculator. To start interactive mode, we need a command window. For Linux OS, we can use the console/terminal window. For Microsoft Windows, we need to launch a command window by typing “cmd” in the windows start menu. Once we have a command window, we can type “python” to enter interactive mode. Now try it out: 1. add two numbers together: type “2 + 4” into the command line. 2. multiply two numbers: 24 3. Power a number: 4*2 4. Divide two numbers: 5/2 5. Enter “print(‘Hello world’)”

Interactive mode is fun and easy to use. But, it's not very useful as a program. Whatever you type will be executed and lost. In addition, it's not suitable for more complicated decision making as you will see when you learn. It would be nice if we can save the statements and reuse them. The script mode of python comes to the rescue for this case. Under script mode, the code is saved in a script file. So, it will be a lot easier to read/understand and debug. But, remember, whatever saved in a script file can be executed in the interactive mode. As a matter of fact, if you are not sure of something when you are writing python script, you can always check it out under interactive mode. Now, we will focus on the script mode.

2.2 Script Mode

So far, we have executed individual lines of code in the python shell. When writing longer programs, it is more convenient to use python scripts. A script is just a series of programming commands in a text file. All you need to do is put all the statements in a file. So, you need a text editor for that purpose. On Microsoft Windows, you can use notepad. Now, try to do the following: 1. Start nodepad. 2. Type print('Hello World') and save it to a file called test.py. 3. Go to the cmd window and change to the directory where the file test.py was saved at. 4. Type “python test.py”. You will see that "Hello World" is displayed. Whatever scripts you write in text editors can also be executed via python directly. The difference is that writing scripts in text editors makes it much easier to write, understand, and debug. But, the output is the same regardless.

When we write python code, the code has to conform to certain syntax. Just like any native language. The following section will describe the syntax of python code.

2.3 python syntax

2.3.1 Comments

Anything after the '#' character will be treated as a comment. Python will ignore anything after the '#' character. So, comments are there to help us understand the code. For example:

 # This is a comment line.

2.3.2 Variables

We use variables to remember certain values. Variables are reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The python interpreter allocates memory based on the data type of a variable and decides what can be stored in the reserved memory. Therefore, you can store integers, decimals, strings, lists, etc. in these variables. Variables make the code more readable. Without variables, the python code will be just all numbers or strings and some operators. It would be hard to understand the intent of the code. You can use any name (with certain limitations) as a variable. The equal sign (=) is used to assign values to variables. For example:

  name = 'John'           # name is the variable and it is used to represent 'John'  
  print('hello ' + name)  # This will print out "hello John", '+' is the concatenation operator for strings.
  x = 5                   # x is the variable here and it's used to store an integer value of 5.
  y = 6                   # y is the variable here and it's used to store an integer value of 6.
  print(x+y)              # This will print out "11"
  z = x + y               # a new variable z is created to store the result of x + y.
  print(z)                # This will print out "11"

So, it's that simple. You can use almost any name you want as a variable. I said "almost any name" because there are certain limitations on the names you can use. Variable names are Python Identifiers. A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

There are naming conventions for Python identifiers, but we won't get into details here.

Reserved Words The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. Here is the list:

and assert break, class contnue 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.

2.3.3 Standard Data Types

The data stored in memory can be of many types. Python has five standard data types − 1. Numbers:

1, 100, 8.7, etc. Operators used to manipulate numbers are called Arithmetic Operatros. The following is a table of Python Arithmetic Operators (Assume variable a holds 10 and variable b holds 20):

Operator

Description

Example

+

Add values on either side of the operator

a + b = 30

-

Subtract rgith hand operand from left hand operand

b - a = 10

*

Multiplies values on either side of the operator

a * b = 200

/

Divides left hand operand by right hand operand

b / 2 = 2

%

Divides left hand operand by right hand operand and returns remainder

b % a = 0

**

Performs exponential (power) calculation on operators

a**b = 10 to the 20th power

//

Floor Division - The division of operands where the result is rounded down

11//4 = 2

  1. String "This is a string", 'This is also a string', "string needs to be quoted with single or double quotation marks" Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Subsets of strings can be taken using the slice operator ([ ] and [:] ). Index starts at 0 in the beginning of the string and working their way from -1 at the end.

    The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −

    str = 'Hello World!'
    print(str)          # Prints complete string: "Hello World!"
    print(str[0])       # Prints first character of the string: "H"
    print(str[2:5])     # Prints characters starting from 3rd to 5th(not including 5th): "llo"
    print(str[2:])      # Prints string starting from 3rd character: "llo World!"
    print(str * 2)      # Prints string two times: "Hello World!Hello World!"
    print(str + "TEST") # Prints concatenated string: "Hello World!TEST"
  2. List:

     my_list = ["John", "Chris", "Fred", "Emma"]   # create a list with 4 entries and assign to my_list.

    A list is the fundamental data structure. It organizes information as an ordered sequence. It's enclosed in square brackets. List is important in Python because the for loop(that we will talk about later) is based on iteration through elements in an iterable, such as a list, diectionary, etc. You can create lists as follows:

    my_list = ["item1", "item2"]         # create a list with two items and assign to the variable my_list
    empty_list = []                      # create an empty list and assign it to the variable empty_list

    We can access an individual list item by its index, for example:

    print(my_list[0])                    # This will print out "item1"

    Note that indexing starts from 0. We can also assign values to the list items via index. For example,

    students = [‘Max’, ‘Emma’, ‘John’]   # create a list with 3 items and assign to the variable students.
    students[1] = ‘Chris’                # This replaces 'Emma' with 'Chris'
    print(students)                      # try this out in python.

    The list data type has quite a few methods. Here are all of the methods of list objects: list.append(x) Add an item to the end of the list. Equivalent to a[len(a):] = [x]. Example, students.append("Frank") will add "Frank" to the end of the students list. list.extend(L) Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L. list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x). list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item. list.pop([i]) Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.) list.clear() Remove all items from the list. Equivalent to del a[:]. list.index(x) Return the index in the list of the first item whose value is x. It is an error if there is no such item. list.count(x) Return the number of times x appears in the list. list.sort(key=None, reverse=False) Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation). list.reverse() Reverse the elements of the list in place. list.copy() Return a shallow copy of the list. Equivalent to a[:].

  3. Dictionary:

    my_dict = {"name": "John", "address": "123 Wall st", "salary": "$1 million"}

    A dictionary contains key/value pairs and is enclosed with curly braces. In the above example, "name", "address", "salary" are all keys and "John", "123 Wall st", "$1 million" are the corresponding values for the three keys. The values are accessed with the keys. For example:

    print(my_dict["name"])       # This will print out "John".

    You can also assign a new value to the given key, for example:

    my_dict["name"] = "Fred"     # This replaces "John" with "Fred"

    Dictionary keys have to be unique. If you store some value using a key that already exists, the old value associated with that key is forgotten and the value will be associated with that key. If you try to use the dictionary with an invalid (non-existent) key, it will error out. So, we need to make sure the key exists before we access it. To do that, use the "in" keyword. For example,

    "name" in my_dict            # This will evaluate to true because "name" is a key in my_dict.
    "abc" in my_dict             # This will evaluate to false.

    The above test is frequently used in the if-statement (will be discussed shortly). We won't use it much in this Robotics class and we will not get deeper. It's here just for the sake of compeleteness.

  4. Tuple:

    my_tup = ("John", "Chris", "Fred", "Emma")    # create a tuple with 4 entries and assign to my_tup

    Tuples are like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists, and tuples use parentheses, whereas lists use square brackets.

There is a len() function that will tell the # of characters for string, # of items for lists, dictionaries, or tuples. For the examples given above, the len() operation will give you the following value:

len(str)       # This will evaluate to 12 (there are 12 characters in "Hello World!").
len(students)  # This will evaluate to 3 (there are three items in the list)
len(my_dict)   # This will evaluate to 3 (there are 3 key/value pairs in the dictionary)
len(my_tup)    # This will evaluate to 4.

2.3.4 Input and Output

So far, we have only dealt with output from python (through the print statement). In real life, we probably want to input data/information to python scripts so that it can make decisions based on input. The simpliest input method in python is called, as you might have guessed it, input (in versions earlier than 3.2, it is called raw_input). The following is an example:

  str = input("What's your name?")    # the string inside the function is called the prompt.
                                      # the prompt is optional. It prints out the prompt and
                                      # will wait for your input.
  print("Hello" + str)                # If you replied with "John", this will print out "Hello John"

Sometimes, we want to read data/information from a file or write to a file. First, we need to open the file and then we can read or write to it. Example:

    fr = open("test.py", "r")         # tells python to open the file "test.py" for "read".
                                      # the 1st parameter is the file name
                                      # the 2nd parameter is the mode, "r" for read, "w" for write.
                                      # make sure the file exists.
    data = fr.read()                  # This reads in the entire file and assign to data.
    line = fr.readline()              # This reads in one line from the file and assign to line.
    fr.close()                        # When we are done, we close the file.  It's an error to call
                                      # fr.read() after this statement.
    fw = open("test.bak", "w")        # open file "test.bak" for "write". 
    fw.write(data)                    # writes data into the file.
    fw.close()

2.3.5 Conditionals and Control Flow

So far, all the examples I've given are just simple python statements. They are executed in the order entered. However, in real life, we make decisions everyday. For example, if I get a gold medal in Olympics, I get to go to University of Choice. So, the control flows goes as following:

  "Win Gold Medal" ? --yes--> "I get to go to University of Choice"
                    |
                     --no---> "I get to go nowhere"

Now, express that in python, we write the following code:

win_gold_medal = True             # True is called a Boolean.  The opposite of True is False.
if win_gold_medal:                # notice the ":", it's required.
    print("I get to go to University of Choice")  # notice the indentation.  It's required.
else:                             # notice the ":", it's required.
    print("I get to go nowhere")  # This has indentation as well. It's required.

Since win_gold_medal is set to True, the result will be "I get to go to University of Choice"

Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −

# The following is okay.
if True:
    print "True"
else:
  print "False"

# However, the following block generates an error −
if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"

The above contruction is the well-known if-statement. The compelete statement is as following:

if x < 0:                        # The "<" is the logical comparison operator.
    x = 0
    print('Negative changed to zero')
elif x == 0:                     # This "==" is the logical comparison operator.
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’.

The if-statement uses logical operations, the following are the logical comparison operators:

Operator

Description

Example

==

If the values of two operands are equal, then the condition becomes true.

('a'=='b') is False

!=

If values of two operands are not equal, then condition becomes true.

('a' != 'b') is True

<>

If values of two operands are not equal, then condition becomes true.

similar to !=

>

If the value of left operand is greater than the value of right operand, then condition becomes true.

('a' > 'b') is False

<

If the value of left operand is less than the value of right operand, then condition becomes true.

('a' < 'b') is True

>=

If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.

('a' >= 'b') is False

<=

If the value of left operand is less than or equal to the value of right operand, then condition becomes true.

('a' <= 'b') is True

The following are the logical operators:

Operator

Description

Example

and (Logical AND)

If both the operands are true then condition becomes true

('a' and 'b') is true

or (Logical OR)

If any of the two operands are non-zero then condition becomes true

(a or b) is true

not (Logical NOT)

Used to reverse the logical state of its operand

Not(a and b) is false

For example:

a = 10
b = 20
x = 1
y = 2
if a < b and x < y:
    print("%d < %d and %d < %d" % (a, b, x, y))  # prints "10 < 20 and 1 < 2". The % is used for formatted printing.

2.3.6 Loops

Loops are one of the most powerful programming concepts. A loop carries out the same sequence of instructions multiples times. The instructions only need to be defined once. There are two basic loop constructions: 1. while loop Repeats a statement or group of statements while a given condition is True. It tests the condition before executing the loop body. For example,

  # The following will print 0, 1, 2, ..., 99
  x = 0
  while x < 100:        # The while loop will repeat if x is less than 100. The ":" is required.
      print(x)
      x += 1            # This is the same as x = x + 1, it increments x and assign it back to x.
  1. for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. The for loop can loop through lists, dictionaries, strings and other suitable data types. Data structures you can apply loops to are called iterables. For example,

    students = ['Max', 'Emma', 'John']     # create a list and assign it to students.
    # The following loops through the "students" list with the for loop. It prints all entries in the list.
    # "name" is a temporary variable that will hold the entry when for loop iterates through the list.
    for name in students:                  # for loop construct. ":" is required.   
       print(name)                        # indented code block. Indentation is required.
    
    my_dict = {"name": "John", "address": "123 Wall st", "salary": "$1 million"}
    # The following will print out all the key/value pairs in my_dict.
    # The temporary variable k is used to hold the key of the dictionary during the iteration.
    for k in my_dict:               # use for loop to iterate through the keys.
       print(k, my_dict[k])        # print the key (k) and the value of that key (my_dict[k])

    Exercise 2.3.6: 1. Write a program to print out all names other than "John" in the students list. 2. Write a program to replace "John" with "Martin" in the studens list and print out the list.

   # Example code for Exercise 1
   students = ["Max", "Emma", "John"]
   for name in students:
       if name != "John":
           print(name)

   # Example code for Exercise 2.
   students = ["Max", "John", "Emma", "John"]
   count = len(students)
   index = 0
   while index < count:
       if students[index] == "John":
           students[index] = "Martin"
       index += 1

   print(students)

2.3.7 Functions

It is often the case that you want to perform the same task just with different values. A function is a reusable section of code written to perform a specific task in a program so that we don't need to write the same code again and again. For example:

def mul(x, y):       # notice the "def" keyword. "mul" is the function name. ":" is required.
  return x*y         # notice the "return" keyword.  This function returns the value x*y

The x and y inside the parenthesis are called parameters or arguments. A function can have no argument, 1 argument, 2 arguments or more. It depends on what the function does. In the above example, the function needs two parameters (numbers) because the multiplication needs two numbers. Once a function is defined, it can be called as following:

z = mul(3, 5) + mul(4, 6)   # The result will be z = 39

2.3.8 Modules

A module is a concept that python uses to organize code. For example, if you define a range of mathematical functions, you can organize them in a module. When we need certain functions from a module, we first need to import the module and then call the functions from that module. For example,

import math                 # math is a module that contains mathematical functions.
print(math.sqrt(81))        # sqrt() is a function defined inside the math module.

There are all sorts of modules available in python to carry out specific tasks. It's rare that there is no module available that would suit your needs. When you are dealing with robots, the "sys" module will be used frequently. So, I suggest that you earch the "python sys module" from your favorite web browser and you can read the description of the sys module. It will list all the functions that can be called, as well as flags you can set.

Exercise 2.3

Now that we have learnt the basics of python, we can use it to simplify our everyday tasks. Try to do the following: 1. Write a function replace_name(name_list, old_name, new_name). It will replace the old_name in the name_list by the new_name. For example, if I have a list my_list = ["Mary", "John", "Peter"] and if I call replace_name(my_list, "John", "Eric"), it will return a new list with ["Mary", "Eric", "Peter"]. 2. Save the above code in a file called my_module.py and then call the function from another python script file to replace "Peter" with "Matt". Print out the original list and the new_list. 3. Write a program that does the following:

  a) Ask a person's name.
  b) When a person enter's a name, print "Hello name", where name is the person's name.
  c) Ask about what class the person is taking.
  d) Print "class is very fun, isn't it?"
  e) Ask about "which country are you from?"
     If from US, then, ask about "Which state are you from"?
         If from California, then print("You are local").
         Else print("California is nice, isn't it?")
     Else print("country is far. Wish you had a nice trip")
  f) Print "Do you want to play again? (yes/no)"
  g) If input is "no", then, we exit, otherwise, we go back to ask the 1st question.
# example code for exercise 1. Save it in a file called my_module.py
def replace_name(name_list, old_name, new_name):
    new_list = []
    for name in name_list:
        if name == old_name:
            new_list.append(new_name)   # the append() function appends new_name to the new_list.
        else:
            new_list.append(name)
    return new_list

# example code for exercise 2. To use the function, save it into a file test2.py
# then type "python test2.py" from the cmd window (type without the quotation marks)
import my_module

my_list = ["Mary", "John", "Peter"]
new_list = my_module.replace_name(my_list, "Peter", "Matt")
print("Original list: ", my_list)
print("After replacing John with Eric, new list is: ", new_list)

# example code for exercise 3
while True:
    answer = input("What's your name? ")
    print("Hello " + answer)
    answer = input("What class are you taking? ")
    print(answer + " is fun, isn't it?")
    country = input("Which country are you from? ")
    answer = country.lower()    # change to lower case for easy comparison
    if answer == "us" or answer == "united states" or answer == "u.s":
        state = input("Which state are you from? ")
        t = state.lower()    # change to lower case and assign to variable t.
        if t == "ca" or t == "california":
            print("You are local")
        else:
            print("California is very different from " + state + ", isn't it")
    else:
        print(country + " is far. Wish you had a nice trip.")
    answer = input("Do you want to play again?(yes/no) ") 
    if answer.lower() == "no": 
        break

In the above exercise, we created our own module (my_module.py) and used it in another piece of code. Once the module is created, using it is really simple. We just need to import it and start calling the functions in the module. The last exercise is a glimpse of artificial intelligence(AI). If we create a large enough dictionary/database with more complicated logic, the computer will behave like a human being and will be able to carry out a conversation with a real human.

python document