Chapter2
Last updated
Last updated
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.
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.
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.
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:
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:
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.
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
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 −
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:
We can access an individual list item by its index, for example:
Note that indexing starts from 0. We can also assign values to the list items via index. For example,
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[:].
Dictionary:
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:
You can also assign a new value to the given key, for example:
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,
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.
Tuple:
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:
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:
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:
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:
Now, express that in python, we write the following code:
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 above contruction is the well-known if-statement. The compelete statement is as following:
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:
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,
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,
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.
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:
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:
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,
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.
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:
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.