0% found this document useful (0 votes)
3 views

Python basics final

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python basics final

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Table of Contents

1 Automating GIS Tasks ........................................................................................................................... 3

1.1 Why do we need to learn Python? ............................................................................................... 4

2 Python Basics ........................................................................................................................................ 5

2.1 Basic Syntaxes ............................................................................................................................... 6

2.1.1 First program - Interactive Mode .......................................................................................... 6

2.1.2 PYTHON IDENTIFIERS ............................................................................................................ 8

2.1.3 RESERVED WORDS ................................................................................................................ 8

2.1.4 LINES AND INDENTATION ..................................................................................................... 9

2.1.5 MULTILINE STATEMENTS .................................................................................................... 11

2.1.6 QUOTATIONS ...................................................................................................................... 12

2.1.7 COMMENTS IN PYTHON...................................................................................................... 13

2.2 VARIABLES ................................................................................................................................... 14

2.2.1 Assigning Values to Variables.............................................................................................. 14

2.2.2 Multiple Assignments ......................................................................................................... 15

2.2.3 Standard Data Types ........................................................................................................... 16

2.3 Python Basic Operators............................................................................................................... 19

2.3.1 Arithmetic Operators .......................................................................................................... 19

2.3.2 Comparison Operators ........................................................................................................ 20

2.3.3 Assignment Operators ........................................................................................................ 21

2.3.4 Logical Operators ................................................................................................................ 22

2.4 Loops ........................................................................................................................................... 23

2.5 IF, ELSE, ELIF STATEMENTS ......................................................................................................... 26

3 Basic Python Exercise and Quizzes ..................................................................................................... 29


1
3.1 Section 2.1 Basic Syntaxes Questions ......................................................................................... 29

3.2 Section 2.2 Variables Questions.................................................................................................. 31

3.3 Section 2.3 Python Basic Operators ............................................................................................ 33

3.4 Section 2.4 Loops Questions ....................................................................................................... 35

3.5 Section 2.5 IF, ELSE, ELIF STATEMENTS Questions ..................................................................... 36

4 Advance Python .................................................................................................................................. 37

4.1 Lists and Tuples ........................................................................................................................... 37

4.2 Dictionary .................................................................................................................................... 39

4.3 Functions ..................................................................................................................................... 40

4.4 Data Type Conversion ................................................................................................................. 43

4.5 Global Vs Local Variable .............................................................................................................. 46

4.6 Modules ...................................................................................................................................... 47

4.6.1 Import Statements .............................................................................................................. 47

4.6.2 from import Statements...................................................................................................... 48

4.6.3 Locating Modules ................................................................................................................ 48

4.6.4 Some examples of existing modules (built-in modules) ..................................................... 48

5 Basic Python Exercise and Quizzes ..................................................................................................... 52

5.1 Section 4.1 List and Tuples Questions......................................................................................... 52

5.2 Section 4.2 Dictionary Questios .................................................................................................. 53

5.3 Section 4.3 Functions Questions ................................................................................................. 53

2
1 Automating GIS Tasks
A GIS is designed to manipulate and analyze spatial datasets with the intent of providing
solution to geographic problems. For instance, if you are a GIS analyst, your main task could
involve executing certain operations on spatial data so that the data can be used to solve a
specific problem. Some of these operations can include clipping, re-projecting, buffering,
merging, extracting subsets of the data, raster-to-vector conversions and many more other
operations. The use of these operations is referred to as geoprocessing which is achieved
using tools termed as 'geoprocessing tools' in the ArcGIS software. Choosing the right tools to
operate on your data determines the success of your GIS analysis in solving a specific problem.
In general, GIS software use ‘toolboxes’ to organize its set of tools (geoprocessing tools). As a
GIS Analyst, you choose the appropriate tools you require and execute them in the proper order
to create your final product.

Executing the tools manually (selecting and clicking) for smaller study areas (one district or
province) is perhaps suitable. However if you are to deal with much bigger areas like several
more districts and provinces, then it is such a hassle to manually perform the same order of
operations by executing the same order of tools for each new area. This is where 'automation' is
required so that you do not have to redo the whole manual processing over again each time you
have a new area to work on, assuming the problem you are to solve is the same for all. Once a
data processing chain is automated, you as the GIS Analyst do not need to remember which tools
to use and the order in which they should be executed and so it makes your work easier.
Automation makes your work faster as well because you do not need to continuously point and
click. When a processing task is done manually, you run the risk of errors depending on the
complexity of your analysis procedures. Automation additionally makes your work more
accurate as the computer is instructed automatically to perform the same order of processing
steps every time.

3
1.1 Why do we need to learn Python?

For most of the advanced GIS software packages, there are three main approaches of automating
tasks including a) a visual kind of editor to design workflows, also called model builder, b)
writing scripts and c) using “hardcore” programming, i.e. using a programming language as C++
or Java.

Python is a programming language that can be used to automate computing tasks using a set of
programs called scripts. Python is an interpreted, interactive and object oriented programming
language. It is open-source and it can run on Windows, Linux, and Unix operating systems. Your
learning of the Python programming language will make your work as a GIS analyst much more
effective. Having Python programming skills can also be advantageous even outside the field of
GIS. In ArcGIS, you can use Python to easily run geoprocessing tools such as the Buffer tool.
Using Python, you can call the Buffer tool from a Python script using just one line of code.

In this introductory course, we will not be writing scripts to automate GIS tasks. However basic
Python programming concepts including syntaxes will be given. Python syntaxes refer to how
Python codes are structured generically. Your understanding of Python syntaxes is vital when
writing a script for automating GIS tasks, which will be covered later on in the actual course.

4
2 Python Basics
In the GIS component of the Master course, ESRI's ArcGIS desktop software will be used and
Python is included in the ArcGIS installation. In other words, with ArcGIS installed on your
computer, you should already have Python running on your computer as well.

However Python can also be installed as a standalone program. In this introductory course,
perhaps in order for you to try out some of the basic Python syntax examples that will be given
here, you can go to the Python website at www.python.org, download and install versions either
2.6 or 2.7 that is suitable for your platform. The Python basic examples given in this document is
based on Python 2.7. Once you have Python successfully installed, you can use the Python
default editor called IDLE (which comes with the Python installation) to write codes and run
them (interactive mode). IDLE is Python's own Interactive Development Environment written
entirely in Python and the tkinter Graphical User Interface (GUI) Toolkit. IDLE works on both
Windows and Linux, contains multi window text editor with syntax highlighting, smart indent
and auto-completion to name a few.

Once you are comfortable and confident with your codes, you can open a new window from the
IDLE interface, write your code and then save it with a .py file extension for later use (scripting
mode). Alternatively, you can use text editors like Notepad or Text pad to write Python codes
and also save it as a .py file.

5
2.1 Basic Syntaxes

2.1.1 First program - Interactive Mode

If you open the Python IDLE assuming you are using Python 2.7.x, you will see the following
window below.

Now type the following text into the editor and press the Enter key:

>>> print "Hello, Python!";

This should generate the following output: Hello, Python! as can be seen in the figure below

In the interactive mode, you can write a line of code, then press Enter key to see what the result
will be like, as you go on. This means, the line of Python code will be directly interpreted by
IDLE, and the statement will be executed. Here the statement is the text inside the double quotes
6
and this should be printed on the screen (by the Python command print). The interactive mode is
useful for trial and error purposes to enrich your learning of Python.

First program - Script Mode

From the IDLE, go to File, then New Window. You should see a new window as shown below.

Now type in: print "Hello, Python!"; and save (File<Save As) the untitled window as 'mypy.py'
file as shown in the figure below.

Then go to Run on the IDLE and click 'Run Module'. Alternatively, press the F5 key on your
keyboard to run the code. This will produce Hello, Python! as can be seen in the figure below.

Basically in the scripting mode, you can write a complete set of code, line by line and then run it
once you are done. You can then save it for later use, as mentioned before.

7
2.1.2 PYTHON IDENTIFIERS

With Python, an identifier refers to any name used to identify a variable, function, class, module,
or other object. It can start 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). See examples below:

num = 500 # so num, x, x_y and y are all identifiers (valid identifiers)
x = 10
y = 25
x_y = 67

-xy = 6 # so -xy, b@ and name.1 are invalid identifiers


b@ = 58
name.1 = 'Me'

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is
case sensitive which means that Instruction and instruction are two different identifiers.

2.1.3 RESERVED WORDS

The reserved words in Python may not be used as constant or variable or any other identifier
names. All the Python keywords contain lowercase letters only as shown in the table below.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

8
As example, see the screenshot below. When we use Python reserved words like 'del' and 'def' as
variable name, we get the following syntax error: invalid syntax. However when we use 'mynum'
as our variable name, we do not get any error and it returns the value 20 which was assigned to
it. This is what we mean when reserved words cannot be used as constant or variable or any
other identifier name.

2.1.4 LINES AND INDENTATION

In Python, blocks of code are denoted by line indentation. The number of spaces in the
indentation can vary, but all statements within the block must be indented the same amount. For
example:

Running the above code, we get the following error as shown below, as well as indicated by the
word 'print' being highlighted on the screenshot above. The error says 'expected an indented
block'.

9
This error occurs because of unequal indentation of statement within the block. In this example,
the statement within blocks refers to the print statements - print x, "is greater than or equal to
10". This statement should be directly below x, between x and the greater > sign, similar to the
other print statements.

As shown below is how the indentation should be: here it is clear that all print statements are
indented by the same amount.

By running this code, we get the expected result, which means that indentation is correct:

10
2.1.5 MULTILINE STATEMENTS

Statements in Python typically end with a new line. Python allows the use of the line
continuation character (\) to denote that the line should continue.

For example:

When you run the above example script, you will get the results below. Notice how the statement
lines continue. In the above example, we have three statement lines: 1 - 'I should ', 2 - 'learn ', 3 -
'python!!! '. What the backslash (\) does is that it causes one statement line to continue into
another during concatenation to form one statement line as seen in the output below. Notice in
the code above how there is a space between the last word in the statement and the second single
quote. This brings about the space between each statement line in the final output. Without this
space, the final output would read 'I shouldlearnpython!!!'

Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example:

Result:

11
2.1.6 QUOTATIONS

In Python, single ('), double (") and triple (''' or """) quotes are allowed to indicate strings.
However the same type of quote should start and end the string.

The triple quotes can be used to span the string across multiple lines. For example, all the
following are legal:

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

See below for additional examples of the use of single and double quotes:

What happens when we want to indicate strings that have apostrophes, for instance, you want to
print the statement: Hey, it's me! OR Hello, how's it going? Let us now look at the following
examples:

Notice how we get the error above. Usually, as you may have realized that the moment you
indicate strings with single, double or triple quotes, the text color changes to green. Notice also
in the above example that after the apostrophe, the s and me are black instead of green. What is
happening here is that the Python interpreter reads the apostrophe as the closing single quote for
this string, instead of the actual closing quote at the end of the string. So it only reads 'Hey, it' as
the only strings, disregarding the s and me. To rectify this error, whenever we want to have
12
strings with apostrophe, we use the backslash (\) before the apostrophe to avoid it being read as a
quote by the Python interpreter. See the correction below:

2.1.7 COMMENTS IN PYTHON

A hash sign (#) begins a comment, and all characters after the # and up to the end of the line are
part of the comment. Comments are ignored by the Python Interpreter.

# Write your first comment


print "Hello, Python!";

This will produce following result:

Hello, Python!

You may also write comments on the same line after a statement or expression:

name = "Madisetti" # Name of the person

Each line of comment must start with a # as shown in example below.

# This is the formula for calculating roughness index


#of roads.

It is a good habit to always add comments so that other people will be able to understand your
code.

13
2.2 VARIABLES
Variables are reserved memory locations to store values of some sort. This means that when you
create a variable you reserve some space in memory for a value.

Depending on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals, or characters in these variables. Refer to sub-section 3.2.3 for
further description of the different number types.

2.2.1 Assigning Values to Variables

The equal sign (=) is used to assign values to variables. The left of the = operator is the name of
the variable, and the right of the = operator is the value stored in the variable. For example:

Here Tracy, 30 and 160.5 are the values assigned to myName, myAge and myHeight variables,
respectively. Running this program will produce the following results:

14
2.2.2 Multiple Assignments

You can assign a single value to several variables simultaneously. For example:
a=b=c=1

In the above example, all three variables are assigned to the same memory location. See below:

When we run this code, we get the following result:

You can also assign multiple objects to multiple variables. For example:

a, b, c = 1, 2, "john"

Here two integer objects with values 1 and 2 are assigned to variables a and b, and one string
object with the value "john" is assigned to the variable c.

Look at the example below:

Running the above code, we get the following result:

15
2.2.3 Standard Data Types

Python has various standard types that are used to define the operations possible on them and the
storage method for each of them.

Python has five standard data types:

 Numbers

 String

 List

 Tuple

 Dictionary

We will only discuss numbers and strings in this section. List, tuple and dictionary will be treated
at the later part of this paper.

Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example:

var1 = 1
var2 = 10

Python allows different number types like: int, long, float. Examples of each are listed in the
table below.

int long float


10 51924361L 0.0
100 -0x19323L 15.20
-786 0122L -21.9
080 0xDEFABCECBDAECBFBAEl 32.3+e18
-0490 535633629843L -90.

16
-0x260 -052318172735L -32.54e100
0x69 -4721885298529L 70.2-E12

In version 2.x of Python there are two types of integer variables called int and long as you can
see in the above table. Variables of type int are restricted to numbers in the range ±2 31 while
variables of type long can store numbers of arbitrary size. Additionally, Integers have 32 bits of
precision while long have unlimited precision. Precision is the number of digits in a number. For
example, the number 123.45 has a precision of 5.
Float and decimal can be referred to as similar however the difference is related to their
precision. Float has 7 digits (32 bits) and decimal can have 28-29 significant digits (128 bits). In
simple terms, integer is a whole number while a float is a decimal number.

You can also check data types using type()- see the example below:

Strings

Strings in Python are identified as an adjoining set of characters in between quotation marks.
Python allows for either pairs of single, double or triple quotes as we have seen before. The plus
(+) sign is the string concatenation operator, and the asterisk (*) is the repetition operator. For
example:

17
Result: Hello World!

Further examples for string concatenation is given below:

OR

Both of the above codes produce the same result as shown below:

Now we will look at examples for the string repetition with the use of the asterisk (*) sign.

Notice below how the output is repeated three times:

18
2.3 Python Basic Operators
What do we mean by operators? Let's take the expression 3 + 7 is equal to 10. Here 3 and 7 are
called operands and + is called operator. In Python language, the following type of operators are
supported.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators

2.3.1 Arithmetic Operators

Assume variable a = 10 and variable b = 20 then:

Operators Description Example


+ Addition – Adds values on either side of the a + b will give 30
operator
- Subtraction – Subtracts right hand operand from a - b will give -10
left hand operand
* Multiplication – Multiplies value on either side a * b will give 200
of the operator
/ Division- Divides left hand operand by right b / a will give 2
hand operand
% Modulus – Divides left hand operand by right b % a will give 0
hand operand and returns remainder
** Exponent –Performs exponential (power) a ** b will give 10 the power
calculation on operators 20
// Floor Division – The division of operands 9//2 is equal to 4 and 9.0//2.0
where the result is the quotient in which the is equal to 4.0
digits after the decimal point are removed.

Source: http://www.tutorialspoint.co

19
2.3.2 Comparison Operators

Assume variable a = 10 and variable b = 20 then:

Operators Description Example


== Checks if the values of two operands are equal (a == b) is not true.
or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal (a!= b) is true.
or not, if values are not equal then condition
becomes true.
<> Checks if the values of two operands are equal (a <> b)is true. This is
or not, if values are not equal then condition similar to != operator.
becomes true.
> Checks if the value of left operand is greater (a > b) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than (a < b) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater (a>= b) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less than (a<= b) is true.
or equal to the value of right operand, if yes
then condition becomes true.
Source: http://www.tutorialspoint.com

20
2.3.3 Assignment Operators

Assume variable a = 10 and variable b = 20 then:

Operators Description Example


= Simple assignment operator, Assigns values c =a + b will assign value of
from right side operands to left side operand a+b into c
+= Add AND assignment operator, It adds right c += a is equivalent to c = c +
operand to the left operands and assign the result a
to left operand
-= Subtract AND assignment operator, It subtracts c -= a is equivalent to c = c - a
right operand from the left operands and assign
the result to left operand
*= Multiply AND assignment operator, It c *= a is equivalent to c = c *
multiplies right operand with left operand and a
assign the result to left operand
/= Divide AND assignment operator, It divides left c /= a is equivalent to c = c / a
operand with right operand and assign the result
to left operand
%= Modulus And assignment operator, It takes c %= a is equivalent to c = c
modulus using two operands and assign the %a
result to left operand
**= Exponent AND assignment operator, performs c **= a is equivalent to c = c
exponential (power) calculation on operators and ** a
assign value to the left operand
//= Floor Dividion and assigns a value, performs c // = a is equal to c = c // a
floor division on operators and assign value to
the left operand
Source: http://www.tutorialspoint.com

21
2.3.4 Logical Operators

These are the following logical operators supported by Python language. Assume variable a = 10
and variable b = 20 then:

Operators Description Example


and Called Logical AND operator. If both the (a and b) is true.
operands are true then then condition becomes
true.
or Called Logical OR operator. If any of the two (a or b) is true.
operands are none zero then condition becomes
true.
not Called Logical NOT Operator. Use to reverses Not (a and b) is false.
the logical state of its operand. If a condition is
true then Logical NOT operator will make false.
Source: http://www.tutorialspoint.com

22
2.4 Loops
Sometimes you will come across situations whereby you need to execute a block of code several
numbers of times. Generally, statements are executed sequentially: the first statement in a
function is executed first, followed by the second, and so on. A loop statement allows us to
execute a statement or group of statements multiple times. The following loop exists in Python:
Loop Type Description
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 loop Executes a sequence of statement multiple times and abbreviates the
code that manages the loop variable.
Nested loops You can use one or more loop inside any another while, for or
do…while loop.

Basic Python syntax for the while loop:


while condition :
indentedBlock

Let us look at the following example for while loop. Notice the use of raw_input - in Python
versions 2.6 and 2.7, this returns whatever the user typed - up to hitting the ENTER key - as a

string. Here we are prompting the user for an input, which is a string. For instance:

name = raw_input ('prompt the user for their name: ')

After running the code, the user will then be prompted to enter their name and on hitting Enter,
their name, which is a string is returned or displayed.

23
So when you run the above program shown in the screenshot and then just pressing the Enter
Key, you will notice that it will result in the question reappearing again as shown below:

The reason being that the name is still an empty string which evaluates to false. However if you
enter in a name, this results in:

The for loop can be used to repeat a block of code while any condition is true. For the for loop,
let's look at the following example:

Running the above results in:

24
Here the program loops through the sequence '1', '2', '3' and when x = 1, print the statement
'Welcome 1 times'. When x = 2, print the statement 'Welcome 2 times'. When x = 3, print the
statement 'Welcome 3 times'. Hence the output as shown above.

Since looping is common in Python, Python has a built in function that makes ranges for you.
Ranges include the first limit which is zero (0) and not the least, (in this example given in the
screenshot below), it is 5. If you type in <<<range (5) and press Enter, the output will be the
same as <<<range (0,5). This case is assumed when you supply one limit for e.g. 5.

Let's look at another example:

The above program will simply write out numbers from 1 to 10

25
2.5 IF, ELSE, ELIF STATEMENTS

The if statement is used to check a condition and if the condition is true, we run a block of
statements (called the if-block), else we process another block of statements (called the else-
block). An else statement contains the block of code that executes if the conditional expression in
the if statement resolves to 0 or a false value. Basic Python syntax for if-else statements:

if condition:
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition

Let us look at the following example:

Shown below is the result when running the above code:

So in our code, we have assigned the value of 5 to the variable x. So let us take a look at our
conditions that we have set in our code:

26
 Condition 1 - if x is less than 4, print 'x is less than 4'. However this condition was not
met because the value of 5 is greater than 4.
 Condition 2 - if x is less than 6, 'print x is less than 6'. This condition held true because 5
is less than 6.
 Condition 3 - if x is less than 8, print 'x is less than 8'. This condition also held true
because 5 is less than 8.
 Condition 4 - if x is less than 10, print 'x is less than 10'. This condition also held true
because 5 is less than 10.
 Finally, we have the else statement, whereby, if any of our if conditions do not hold true,
then the else block will be executed and printed. For instance, if x = 10 or 11.

As you can see in our results above, only the conditions that are met, are printed to the screen.
Python interpreter goes through one condition, if it holds true, it prints it out, then goes through
the next condition and so on.

The elif statement allows you to check multiple expressions for truth value and execute a block
of code as soon as one of the conditions evaluates to true. Python syntax for the if-elif-else:

if condition1 :
indentedStatementBlockForTrueCondition1
elif condition2 :
indentedStatementBlockForFirstTrueCondition2
elif condition3 :
indentedStatementBlockForFirstTrueCondition3
elif condition4 :
indentedStatementBlockForFirstTrueCondition4
else:
indentedStatementBlockForEachConditionFalse

27
Let's take the following example:

Running the above code gives us the result below:

What happened here is that, as soon as a condition is evaluated to true, Python interpreter
executes the block of code within that particular elif block. So the first condition that is true is
executed and printed while others are not. If we put x = 9 for instance, the output will be:

Think about the difference between this example on if-elif-else, and the first example on if-else

28
3 Basic Python Exercise and Quizzes

Please find below some simple exercises for the sections 3.1 to 3.5. Try to solve them in
interactive mode first, when you are comfortable, then you can start on the script mode where
necessary. For these exercises, please refer back to the readings and examples provided to help
you throughout!

3.1 Section 2.1 Basic Syntaxes Questions

Question 1

a) Try out some identifiers for instance, try the use of characters like $, %, @,
big and small caps identifiers and see the results.

I) Try the following in the interactive mode, what happens when you hit
Enter? State whether they are valid or invalid identifiers.

No. Identifiers

1. name% = 'Tracy'

2. var@ = 256

3. money$ = 'US Dollars'

4. -x=25

5. x_z = 5

6. name 1 = 'zara'

29
II) Try these also:
Type in: name = 'Tracy', then hit Enter. To confirm, type in Name on the
next line, what do you see? If you get an error, what do you think is
cause? Hint: Python is case sensitive
b) Use these reserved words (break, global, print and return)
as variable names or identifiers and see the results. Refer to the
example given in the reading. Example, break = 50 or return = 'GIS' or print =
'name' hit Enter and see the result.

c) In the script mode, type in the following script, exactly as it is shown in the
screenshot. If you get an error when running the program, what do you think is
the cause? Check the indentation, ensure you make the correction and re-run the
program to see the output.

d) How would you write multiline statements and then print them out in just one
line of statement? Write a program to print out the statement 'I am going to
Germany'. First of all, break this statement into 2 or 3 different lines. Then the
print statement should be in such a way that the 2 or 3 different lines are printed
as one statement line, horizontally.

e) How would you write a program that prints out this statement: "I'm happy to
know what's happening". Refer to readings on the use of quotes considering
apostrophe.

30
3.2 Section 2.2 Variables Questions

Question 2

a) What is your understanding of variables?

b) How would you assign values to variables? Use different types of values,
values can be different data types like integers, float and strings, and assign
them to variables.

For instance:
How would you assign the value of 50 to the variable x and print x?

How would you assign the value of 27.56 to the variable y and print y?

How would you assign the value of 'Paula' to the variable name and print name?

c) You now know that we can assign single value to multiple variables
simultaneously. By simultaneously we mean that the assigning of variable
happens on the same line of code. Now, how would you assign the value of
50 to the variables x, y and z simultaneously and then print x, y and z?

Note: It is also possible to assign multiple values to a single variable. For


example, you want to assign the values 10, 'Zara' and 5 to the variable x, this is
how to do it:

>>> x = ('zara', 10, 5)

>>> (a,b,c) = x

31
>>> a

'zara'

>>> b

10

>>> c
5
So x is a tuple of three elements, and (a,b,c) is a tuple of three variables.
Assigning one to the other assigns each of the values of x to each of the
variables, in order.

d) It is also possible to assign multiple values to multiple variables simultaneously


- same line of code. How would you write a code that assigns 25 to the variable
age, Paulina to the variable name, and 73.5 to the variable weight, then print all
the said variables?

e) Python allows three different types of numbers. List the three and explain
briefly the differences between them. List 2 examples of each type. In Python,
how would you find out if a number is of type integer, float or long?

f) Write a program that concatenates a string - your name, comma, and the text 'I
enjoy GIS!’

g) Write a program that prints 'I enjoy GIS' three times

32
3.3 Section 2.3 Python Basic Operators

Question 3

a) List the four different basic operators used in Python. List 2 examples of each.

b) Assuming x = 5 and y = 10, how would you write a simple Python program
that adds x and y, subtracts x from y, multiplies x by y, divides x by y,
computes the modulus of x and y and computes the exponential of x to y?
Write the simple codes in the interactive mode and run them to see the results.
You should obtain the following results: addition – 15, subtraction - -5,
multiplication – 50, division – 0.5, modulus – 0 and exponential - 9765625

Note: for division, you will notice that the result will be 0 instead of 0.5. In
Python, if you divide integer by integer, you get an integer answer, hence 0 in this
case. So you have to figure out how you would write the numbers so that you get
the actual answer which will be in float or decimal.

Try in the interactive mode:

2*5
2+3*4

If you expected the last answer to be 20, think again: Python uses the
normal precedence of arithmetic operations: Multiplications and divisions are
done before addition and subtraction, unless there are parentheses. Try
(2+3)*4
2 * (4 - 1)
Now try the following in the Interactive mode, exactly as written followed by
Enter, with no closing parenthesis:
5 * (2 + 3
33
Look carefully. There is no answer given at the left margin of the next line and no
prompt > > > to start a new expression. If you are using Idle, the cursor has gone
to the next line and has only indented slightly. Python is waiting for you to finish
your expression. It is smart enough to know that opening parentheses are always
followed by the same number of closing parentheses. The cursor is on
a continuation line. Type just the matching close-parenthesis and Enter,
)
and you should finally see the expression evaluated. (In some versions of the
Python interpreter, the interpreter puts '...' at the beginning of a continuation line,
rather than just indenting.)
Negation also works. Try in the:
-(2 + 3)

c) What operators are used in the following instances:

I) you want to compare if the value of x is equal to the value of y,


such that if they are equal, the condition becomes true

II) you want to compare if the value of x is equal to the value of y,


such that if they are not equal, the condition becomes true.

d) In Python, given x = 5 and y = 10, what does the following mean: x+=y,
x*=y, x%=y? What will be the new values of x?

e) Explain the three logical operators used in Python.

34
3.4 Section 2.4 Loops Questions

Question 4

a) Why do we require loops in programming? Briefly explain what the 'for'


and 'while' loops do in Python.

b) Write a for loop program for the following situation: each time y is
assigned 4, 5, and 6; print the string 'I am' and then the value of y at the
end of each. Output: I am 4
I am 5
I am 6
c) Write a for loop program that loops through a range of 10 - 15 and then
print all the numbers within this range.

d) Write a simple while loop program that assigns b a value of 1, and


while b is less than or equal to 10, print b, incrementing b by 1 till the
value 10 is reached. You should have values 1 to 10 printed vertically as
your output.

e) Write another while loop program that assigns a value of 100 to the
variable temperature. While temperature is greater than 90, print the
temperature, decrementing the temperature by a value of 1. You should
have values of 91 to 100 (100 to 91 literally) printed vertically as your
output

35
3.5 Section 2.5 IF, ELSE, ELIF STATEMENTS Questions

Question 5

a) Explain the concepts of If, Else and Elif statements.

b) Write an if-else program for your daily dressing. If temperature is greater than
a certain value, you should wear shorts, otherwise, wear long pants. First of
all, you need to define your variable - or - in other words, assign a value to the
variable (temperature). Then add in the if-else statements.

c) Say you work for an airline company. Write a program whereby if a


passenger's luggage exceeds the allowed weight of 20kg, they have to pay 20
Euros. Otherwise, they don't pay for excess baggage. Thank them for
choosing your airline.

d) Write a program for this situation: assign x any value you wish, if that value
is less than 10, print out the statement that the value is less than 0. If the value
is less than 20, print out the statement that it is less than 20. If the values are
less than 30, print out the statement that the value is less than 30. Otherwise,
print out the statement that value is greater than or equals to 30. Write your
program in such a way that execution takes place as soon as condition is
found to be true and only the print statement for that condition should be
printed.

36
4 Advance Python
4.1 Lists and Tuples
A data structure refers to a collection of elements like numbers or characters that are structured
in some way. In Python, the most basic data structure is called a sequence. Each element of a
sequence is assigned a number which is basically its position or index in the sequence. So the
first index when starting from left to right is 0, the second is one, third is two and so on. You can
also start counting from right to left. In this instance, the position or index starting from right to
left will be -1, the second last will be -2, the third last will be -3 and so on. In Python two of the
most common sequences are Lists and Tuples. The main difference between a list and tuple is
that a list can be changed while a tuple cannot be changed.

A list contains items separated by commas and enclosed within square brackets ([]). The values
stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0
for the first element in the list, and working their way to end -1. The plus ( + ) sign is the list
concatenation operator, and the asterisk ( * ) is the repetition operator as mentioned before with
the strings. For example:

This will produce following result:

37
A tuple consists of a number of values separated by commas. Again, the main differences
between lists and tuples are: Lists are enclosed in square brackets ( [ ] ), and their elements and
size can be changed. Tuples on the other hand are enclosed in parentheses ( ( ) ) and cannot be
updated/changed. We can refer to tuples as read-only lists. For example:

This will produce following result:

Following is invalid with tuple, because we attempted to update a tuple, which is not allowed.

38
When running this program, the following error occurs:

4.2 Dictionary
Dictionaries consist of {key:value} pairs. A dictionary keys can be almost any Python type, but
are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ( { } ). For example:

This will produce following result:

39
4.3 Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
As you may have realized by now, Python gives you many built-in functions like range() etc.
However you can create your own functions as well - user-defined functions. Functions are
needed to avoid having to write programs by ourselves and also it allows us to share pieces of
code with others.

You can define functions to provide the required functionality. Here are simple rules to follow
when defining a function in Python:
 Function blocks follow this format: def function name ( ).

 Any input parameters or arguments should be placed within these parentheses ().
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.

 The code block within every function starts with a colon (:) and is indented.

 The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.

Here is the simplest form of a Python function. This function takes a string as input parameter
and prints it on standard screen.

This results in:

40
Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function, and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme ()
function:

Running the above program results in:

Below are examples and explanation of Functions - without return value and with return values:

41
Source: CIV 2012 Lecture Notes

Source: CIV 2012 Lecture Notes

42
4.4 Data Type Conversion
In some instances, you may require to perform conversions between the data types. To convert
between data types you simply use the type name as a function. There are several built-in
functions to perform conversion from one data type to another. These functions return a new
object representing the converted value.

Function Description

int(x [,base]) Converts x to an integer. base specifies the


base if x is a string.

long(x [,base] ) Converts x to a long integer. base specifies the


base if x is a string.

float(x) Converts x to a floating-point number.

complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) Converts s to a tuple

list(s) Converts s to a list.

set(s) Converts s to a set.

dict(d) Creates a dictionary. d must be a sequence of


(key,value) tuples.

frozenset(s) Converts s to a frozen set.

43
chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

As an example, we want to write a program that allows the user to enter in their name and age
then print out their name and age in one line of sentence.

When we run this, we get the following error:

This error can be explained as follows: Notice the name variable is a string, while the age
variable is an integer number. Therefore we cannot concatenate a string and a number as they are
different data types. So one way to fix this error is to convert the age to a string. This can be
done as follows:

Now this results in no errors:

44
45
4.5 Global Vs Local Variable
Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared whereas global variables can be accessed throughout the program body by all functions.
When you call a function, the variables declared inside it are brought into action. Following is a
simple example:

Running the above program results in:

46
4.6 Modules

A module allows the logical organization of your code. Grouping related code into a module
makes the code easier to understand and use. Simply, a module is a file consisting of Python
code. A module can define functions, classes, and variables. A module can also include run-able
code.

4.6.1 Import Statements

You can use any Python source file as a module by executing an import statement in some other
Python source file. The import has the following syntax:

import module1[, module2[,... moduleN]

When there is an import statement, it imports the module if the module is present in the search
path. A search path is a list of directories that Python searches before importing a module. For
example, to import the module hello.py, you need to put the following command at the top of the
script:

When the above code is executed, it produces following result:

Hello : Zara

A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening over and over again if multiple imports occur.
47
4.6.2 from import Statements

It is also possible to import all names from a module into the current namespace by using the
following import statement:

from modulename import *

This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used carefully.

4.6.3 Locating Modules

When you import a module, Python searches for the module in the following sequences:
 The current directory,
 The directory in the shell variable PYTHONPATH,
 If all else fails, Python checks the default path.

The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation-dependent default.

4.6.4 Some examples of existing modules (built-in modules)

1. datetime - for basic date and time types.

This code shows an example of the use of the datetime module. Here we want to
print out the today's date and time. Objects of the datetime type represent a date
and a time in some time-zone. Unless otherwise specified, datetime objects use
the time zone used by the application.

48
Output:

2. math - provide access to mathematical constants and functions

Below is an example of the use of the math module.

Running the above code, we get the following results:

49
3. random - generating pseudo random numbers

If we wanted a random integer, we can use the randint function which is


contained in the random module. So without importing random module, we
cannot access the randint function - this is what we mean here.

The output is either 1, 2, 3, 4 or 5. Randint accepts exactly two parameters: a


lowest and a highest number. As you can see, it includes the highest number
but goes from 1 above the lowest number.

If you want a random floating point number, you can use


the random function like this:

The output will be any floating point number like:

4. os - allows one to interface with the underlying operating system whereby


Python is running on. It allows you to manipulate and find the properties of files
and folders on the system.

50
Let us look at this example where we want to check if a particular directory exist
or not - here we want to use the path sub-module: focus on how we import sub
modules.

These are some of the common built in modules in Python that one comes across as a beginner.
There are hell of a lot more modules that you will discover as you advance into Python.

51
5 Basic Python Exercise and Quizzes
Please find below the exercises for section 3.6 to 3.8.

5.1 Section 4.1 List and Tuples Questions

Question 6

a) Create a shopping list consisting of 6 items.


- How would you access or print out only the third item (not
element) in your list?
- How would you access or print out items 3 - 6? Take note of the
use of 'item', not element.
- How would you replace item 5 in your list with another item?
- How would you print your list twice?
- Create another list, and concatenate the two list.

b) Create a tuple consisting of 6 items: a mixture of strings and numbers:


- How would you access or print only the third item in the tuple?
- How would you access or print out items 3 - 6.
- In your attempts to prove that a tuple can be updated or not,
how would you do this in Python?
- How would you print your tuple twice?
- Create another tuple and concatenate the two together.

52
5.2 Section 4.2 Dictionary Questios

Question 7

a) Create a dictionary of the bibliography of a novel that you have read:


for instance, author, title, year of publication and place of publication
- print your dictionary
- print only the keys of your dictionary
- print only the values of your dictionary

5.3 Section 4.3 Functions Questions

Question 8

a) What are functions in Python, and why do we need them?

b) When you want to create your own function - user defined functions, what is
the Python syntax for this? What are the simple rules to follow when defining
a function?

c) Create a function called 'hello' that returns 'Hello' and the value of the
parameter or variable inside the function. Print it out. Your function should be
flexible in a way that you can plug-in any variable type (data type - strings or
numbers etc). Hint:

53
d) Create a math function called ‘timesfive’ that takes any variable or parameter
and multiplies it by 5. Print it out. Your function should be flexible in a way
that you can plug-in any number (integer or float).

e) How would you call this math function 'timesfive' directly from the
Python Interpreter/prompt?

References

1. CIV 2012 Lecture Notes


2. http://www.tutorialspoint.com

54

You might also like