The slides created by Muhammad Aboelfotoh for Tutorial A can be downloaded here.

Thanks to Dr. Alan McLeod for the content of this lab.

These exercises can be done in the lab, where you can easily get help, or on your own. This particular set of exercises is pretty self-explanatory, so you can work on them even if they seem ahead of what we have done in lecture. You will need a working installation of Python, version 3, to do these exercises. If you have not already done so, and you wish to work on these exercises on your own machine, use the Python Software Resources page to learn how to download and install Python.

Expressions are at the root of any programming language. Here are a few Python expressions:


result = number * 2

if result > 1000 :

salary = int(input('Enter your salary: '))

for counter in range(5) :

Expressions are made up using literal values, punctuation, operators, variables, keywords and function calls. Of course the interpreter needs to understand your expression so that it can translate it into the machine code that runs on the processor of your computer. This means that you have to adhere to the syntax rules of the language you are using. And, you must make sure that your expression does what you want it to do, after it has been found to be syntactically correct.

These exercises explore the various parts of an expression, starting with literal values. For now, all you will need is a Python prompt: >>>. From the Python 3.0 or Python 3.1 program group, select "Python (command line)", or better yet, start up IDLE and use its command prompt.

Exercise 1

Here are some examples of literal values:


4

5.2

100097

-72

0.000676

3.3E-10

"CISC101"

'Single Quotes Work Too!'

'''Or Even Triple Quotes'''

1.2e45

True

False

OK, that looks pretty straight forward. But here are some more examples that might be a little puzzling:


0o77

0x101

0xA22

0b11101

4 + 5J

8 - 2j

Any guesses as to what these are? How about the collection examples shown below:


(4, 5.2, "hello")

[True, 6, 3]

{1, 3, 5, 7}

{'name': 'Alan', 'age': 21}

Maybe we should slow down before things get out of hand!

Python has a function, more specifically a "Built-In Function" or "BIF" called type() that will allow you to find out more about these literal values. A function is a piece of code stored somewhere else that we can invoke by "calling" it. Take one of the literal values shown above, give it to the type() function and display the results. Here's an example, where the code finds out what type True is:


>>> type(True)

<class 'bool'>

>>>

The example invokes the type() function when you type in type(True) and press the Enter key. The command line interpreter responds by displaying the return value of the function, which is <class 'bool'> in this case, and then it provides another command line prompt, ready (and eager!) for your next command.

So, the literal value True is a bool type. You might suspect that bool is short for "boolean", and you would be correct!

Exercise 2

In the examples above, you found that the literal numbers 4, 0o77 and 0x101 were all of the int type. So what happens when you preface a number with a 0o (zero-oh) or a 0x? (And why would you want to?)

You also found that the interpreter dumps the result of an expression to the screen after you type in the expression and press Enter. Yes, you have already used an expression!! In a sense, the interpreter is just acting like a fancy calculator.

To find out what the 0b, 0o and 0x prefaces are doing, type the following numbers at the prompt and press Enter after each:

The default base or "radix" of the number displayed by the interpreter is base 10. So what is the base of each of the numbers listed above?

Base 2 or binary just uses zeros and ones. Base 8, or octal, uses the digits 0 to 7. Base 10, or decimal, uses 0 to 9, and base 16, or hexadecimal ("hex") uses 0 to 9 along with A, B, C, D, E and F.

Exercise 3

Exercise 4

Literal values are not too interesting by themselves, so let's do something with them. Using arithmetic operators you can carry out calculations. Here is a list of these operators and what they do:

You can discover a few of the fine points of using these operators by trying out some simple expressions. In each case, predict what the output will be. If your prediction is wrong, make sure you understand why it came out the way it did.


4 + 2

4 + -2

2 * 4 * 8

2 + 4 * 8

2 * 4 + 8

10 / 5

10 / 3

1 / 2

1 // 2

10.0 / 3

20.0 / 3

20 / 3

20.0 // 3

20 % 3

10 % 2

10 ** 6

The rules of operator precedence determine which operations are carried out first in an expression that has multiple operators. If the operators all have the same precedence calculations are made from left to right. Round brackets can be used to control precedence. Guess and then use the interpreter to evaluate each of the following expressions:


5 * 4 - 2

5 * (4 - 2)

4 + 2 // 3

(4 + 2) // 3

4 * 1 // 3

4 * (1 // 3)

5 * 4 - 2 + 6 // 4 * 7

((2 - 3) * 7) + 20 // 3

10 % 3 + 2

10 % 3 * 2

10 % (3 * 2)

By now you should have noticed that even if you have an integer on both sides of a division operator, then the result is a float, not an integer! Note that the result of floor division is truncated, not rounded!

Exercise 5

If you have a string literal on either side of a + operator, then the operation carried out is not addition, but concatenation instead. This just means that a string is created by jamming two strings together into one. See what you get when you type in:


"one" + "two" + "three"

You can make a string out of a number by using the str() BIF. Try:

str(1) + "two" + str(3)

Try this expression as 1 + "two" + 3 instead to see that this will not work.

Likewise you can convert a string back to a number using such BIFs as int() and float(). Try:


int("4") + 7

These exercises keep pulling BIFs out of thin air, which is not very satisfying to a curious programmer, like you! To find a list of these functions, begin by opening up "Python Manuals" from the Python 3.1 group. Display section 2, "Built-in Functions" from the "The Python Standard Library" chapter. You can scan through this page now, but it will be confusing until we get to use these functions more often. You can always get help on specific BIFs by using the index tab at the left and then typing in the function name.

Exercise 6

Variables are used to store values in memory. A variable name must start with a letter and cannot contain spaces. You store a value in a variable using the = assignment operator. Sounds complicated? Not really! Enter the following lines, one after another and observe the results that are sent to the screen:


a = 5

b = 10

a + b

c = b / a

c

You should have noticed that the use of the assignment operator does not result in any output to the screen. The only lines that generated output were:


a + b

c

These were pretty simple and not terribly descriptive variable names. But, a, b and c will contain values until you exit the interpreter! You can certainly use better names, like "numStudents", "temperature", and "automobileVelocity", for example.

Exercise 7

In this course you will get to write lots of Python programs or scripts. One thing you can't do in a program is dump output like we have been doing with the interpreter. You will not be able to put something like a + b on a line in a program and have it work the way you want. Instead you will have to use the print() BIF to display output to the screen. You can try this function now by typing:


print(a + b)

(Of course, this assumes that you did not close the Python prompt after exercise 6! If you did, you lost the values stored in the a and b variables.)

In the interpreter, this gives the same output as if you just typed a + b followed by Enter. However, the print() function does not always give the same output as an interpreter dump. For example, type in the following lines of code, by pressing Enter after each line:


m = '''line1

line2

line3'''

m

print(m)

You should have seen that dumping the variable m creates quite a different output than printing it with the print function!

We will use this BIF often. To get a quick summary of the syntax of the print() function type help() at the Python prompt, then print at the "help>" prompt. Typing quit at the help> prompt will exit the help system and put you back to the Python prompt.

Exercise 8

You have looked at literal values, variables, some operators and punctuation, and a few functions. What's left? Keywords! You might mistake a keyword for a function, but a keyword never uses the round brackets. If you check back, all of the functions you have used so far: type(), str(), int(), float() and print() all must have a set of round brackets after the name of the function. Keywords do not use the round brackets. Also, functions often return a value (print() doesn't!), in contrast a keyword does something.

Here is some code you can run at the Python prompt that uses both keywords and BIFs, that hints at the power of a programming language. Type the following at the prompt and press Enter:


for x in range(10) :

Because this line ends with a colon (the :) you notice that the cursor does not go back to the >>> but is indented and is in fact waiting for more code. Type:


print(x)

and press Enter and then Enter again. You should see the numbers 0 to 9 displayed on the screen, one number per line. The for and in are keywords (no brackets) and the range(10) and print(x) are functions. x is a variable, and 10 is a integer literal. The colon and the tab character providing the indentation are punctuation.

Of course, there are many other keywords in Python and you will use most of them in your programs to construct conditionals, loops (like the "for" loop above) and many other powerful expressions that will control the flow of your program. To get a list of keywords, you can use the Python help documentation, but you can also get a list through the interpreter itself. To do this, type help() at the prompt, then keywords at the help> prompt. You can type quit or just press enter at the help> prompt to get out.

Exercise 9

Before you go, remember the list of expression examples shown at the top of this page?:


result = number * 2

if result > 1000 :

salary = int(input('Enter your salary: '))

for counter in range(5) :

Can you identify the various parts of these expressions? Here is how you might sort out all the pieces if you were to take these expressions apart:

Literal Values Variables Operators Punctuation Functions Keywords
2 result = : input() if
1000 number * : range() for
'Enter your salary: ' salary > (spaces) int() in
5 counter =      

Had enough? Time for one more function!

Type quit() at the python prompt to close the prompt and its window. Ahhh...

You will have noticed that we called or "invoked" this function without putting anything in the round brackets. But, quit() is still a function!