Python 1
Python 1
http://profs.info.uaic.ro/~grigoras/Geo
[email protected]
Why Python?
Teaching introductory GIS programming to geographers
using an open source Python approach (
Journal of Geography in Higher EducationVolume 40, 2016 -
Issue 1)
! Computer programming is not commonly taught to
geographers as a part of geographic information system (GIS)
courses, but the advent of NeoGeography, big data and open
GIS means that programming skills are becoming more
important.
! These laboratories use core spatial concepts that are relevant
for all areas of geographic study, and use an open source
Python approach that has wider logistical and pedagogical
benefits.
2
Why Python?
Python for ArcGIS (
http://resources.arcgis.com/en/communities/python/ )
3
Bibliography
https://www.python.org/
https://wiki.python.org/moin/BeginnersGuide
https://docs.python.org/2/tutorial/
https://www.python.org/downloads/
https://wiki.python.org/moin/IntroductoryBooks
http://it-ebooks.info/read/304/
https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/
index.html
https://docs.python.org/2/library/idle.html
https://www.tutorialspoint.com/python3/
4
Evaluare
50% Laborator
50% Test scris
5
Short History - Computers
Ancient era: Abacus
Abacus:
7
New calculating tools
John Napier's calculating tables from around 1680:
8
Mechanical calculators
Pascal's calculator. Pascal invented his machine in 1642.
He built twenty of these machines (called Pascal's Calculator
or Pascaline) in the following ten years.
9
Punched card data
processing
1801: Joseph-Marie Jacquard developed a loom in which the
pattern being woven was controlled by punched cards.
1880: the American Herman Hollerith invented data storage
on punched cards that could then be read by a machine
1911: Computing Tabulating Recording Company (CTR)
formed by the merger of the Tabulating Machine Company
and three other companies. In 1924 renamed International
Business Machines (IBM).
1920: electro-mechanical tabulating machines could add,
subtract and print accumulated totals.
1935: IBM punched card systems were used to process
records of 26 million workers.
10
First general-purpose
computing device
Charles Babbage, (26 December 1791 18 October 1871)
was an English polymath. He was a mathematician,
philosopher, inventor and mechanical engineer, who is best
remembered now for originating the concept of a
programmable computer.
1822: the difference engine, made to compute values of
polynomial functions.
11
First general-purpose
computing device
1843: Babbage worked to design a more complex machine
called the Analytical Engine
Ada Lovelace - the first computer programmer - is credited
with developing an algorithm for the Analytical Engine to
calculate a sequence of Bernoulli numbers.
12
Analog computers
1872: The first modern analog computer was a tide-
predicting machine, invented by Sir William Thomson, later
Lord Kelvin
1927: the differential analyzer built by H. L. Hazen and
Vannevar Bush at MIT
13
Electromechanical
computers
1939: German engineer Konrad Zuse created Z2 one of the
earliest examples of an electromechanical relay computer.
1941: Zuse followed his earlier machine up with the Z3, the
world's first working electromechanical programmable, fully
automatic digital computer.
14
Electronic data processing
1942: John Vincent Atanasoff and Clifford E. Berry of Iowa
State University developed and tested the AtanasoffBerry
Computer (ABC)
This design was also all-electronic, and used about 300
vacuum tubes, with capacitors fixed in a mechanically
rotating drum for memory
15
The electronic
programmable computer
Colossus was the world's first electronic digital computer
that was programmable. The Colossus computers were
developed for British codebreakers during World War II to
help in the cryptanalysis of the Lorenz cipher
Colossus Mark 1, was shown to be working in December
1943 and was operational at Bletchley Park by 5 February
1944. An improved Colossus Mark 2 that used shift registers
to quintuple the speed, first worked on 1 June 1944, just in
time for the Normandy Landings. Ten Colossi were in use by
the end of the war.
A functioning replica of a Colossus computer was completed
in 2007 and is on display at The National Museum of
Computing at Bletchley Park.
16
Colossus rebuild
17
The stored-program
computer
The theoretical basis for the stored-program computer had
been laid by Alan Turing in his 1936 paper. In 1945 Turing
joined the National Physical Laboratory and began work on
developing an electronic stored-program digital computer.
His 1945 report Proposed Electronic Calculator was the first
specification for such a device.
18
The stored-program
computer
the Manchester Mark 1 at the University of Manchester.
Work began in August 1948, and the first version was
operational by April 1949
the EDSAC (Electronic Delay Storage Automatic Calculator)
designed and constructed by Maurice Wilkes and his team at
the University of Cambridge Mathematical Laboratory in
1949.
ENIAC (Electronic Numerical Integrator And Computer)
inventors John Mauchly and J. Presper Eckert proposed the
EDVAC's (Electronic Discrete Variable Automatic Computer)
construction in August 1944, and design work for the
EDVAC commenced at the University of Pennsylvania's
Moore School of Electrical Engineering, before the ENIAC
was fully operational.
19
Commercial computers
The first commercial computer was the Ferranti Mark 1,
built by Ferranti and delivered to the University of
Manchester in February 1951
In June 1951, the UNIVAC I (Universal Automatic Computer)
was delivered to the U.S. Census Bureau. Remington Rand
sold 46 machines at more than US$1 million each
($9.09 million as of 2014)
IBM introduced a smaller, more affordable computer in 1954
that proved very popular. The IBM 650 weighed over
900 kg, the attached power supply weighed around 1350 kg
and both were held in separate cabinets of roughly 1.5
meters by 0.9 meters by 1.8 meters. It cost US$500,000
($4.39 million as of 2014)
20
In 1951, British scientist Maurice Wilkes developed the
concept of microprogramming
By 1954, magnetic core memory was rapidly displacing most
other forms of temporary storage
IBM introduced the first disk storage unit, the IBM 350
RAMAC (Random Access Method of Accounting and Control)
in 1956.
From 1955 onwards transistors replaced vacuum tubes in
computer designs
A second generation computer, the IBM 1401, captured
about one third of the world market. IBM installed more
than ten thousand 1401s between 1960 and 1964.
21
Post-1960: third generation
Integrated Circuit: Kilby (Texas Instruments) recorded his
initial ideas concerning the integrated circuit in July 1958,
successfully demonstrating the first working integrated
example on 12 September 1958
IBM System/360 in 1964. It was the first family of
computers designed to cover the complete range of
applications, from small to large, both commercial and
scientific.
April 1975 at the Hannover Fair, Olivetti presented the
P6060, the world's first personal computer with built-in
floppy disk
22
Minicomputers
23
PC
An early use of the term "personal computer" appeared in a
November 3, 1962, New York Times article reporting John W.
Mauchly's vision of future computing as detailed at a recent
meeting of the American Institute of Industrial Engineers.
Mauchly stated, "There is no reason to suppose the average boy
or girl cannot be master of a personal computer
Six years later a manufacturer took the risk of referring to their
product this way, when Hewlett-Packard advertised their
"Powerful Computing Genie" as "The New Hewlett-Packard 9100A
personal computer
Over the next seven years the phrase had gained enough
recognition that when Byte magazine published its first edition, it
referred to its readers as "[in] the personal computing field and
Creative Computing defined the personal computer as a "non-
(time)shared system containing sufficient processing power and
storage capabilities to satisfy the needs of an individual user.
24
PC - The beginnings
Simon was a project developed by Edmund Berkeley and
presented in a thirteen articles series issued in Radio-
Electronics magazine, from October 1950. The Simon
represented the first experience of building an automatic
simple digital computer, for educational purposes. In 1950,
it was sold for US$600
The IBM 610 was designed between 1948 and 1957 by John
Lentz at the Watson Lab at Columbia University as the
Personal Automatic Computer (PAC) and announced by IBM
as the 610 Auto-Point in 1957. With a price tag of $55,000,
only 180 units were produced.
25
PC - The beginnings
The Programma 101 was the first commercially produced
"desktop computer designed and produced by the Italian
company Olivetti and presented at the 1965 New York
World's Fair. Over 44,000 units were sold worldwide; in the
US its cost at launch was $3,200.
The Soviet MIR series of computers was developed from
1965 to 1969 in a group headed by Victor Glushkov.
The Kenbak-1 is considered by the Computer History
Museum to be the world's first personal computer. It was
designed and invented by John Blankenbaker of Kenbak
Corporation in 1970, and was first sold in early 1971. The
system first sold for US$750.
26
PC - The beginnings
The Xerox Alto, developed at Xerox PARC in 1973, was the
first computer to use a mouse, the desktop metaphor, and a
graphical user interface (GUI), concepts first introduced by
Douglas Engelbart while at International. It was the first
example of what would today be recognized as a complete
personal computer.
27
PC - The beginnings
Three machines, the Apple II, PET 2001 and TRS-80 were
all released in 1977, eventually selling millions of machines.
28
The IBM PC
IBM responded to the success of the Apple II with the IBM
PC, released in August, 1981.
29
Apple Lisa and Macintosh
In 1983 Apple Computer introduced the first mass-marketed
microcomputer with a graphical user interface, the Lisa.
Apple launched the Macintosh in 1984, the first successful
mass-market mouse-driven computer with a graphical user
interface or 'WIMP' (Windows, Icons, Menus, and Pointers).
30
PC clones
In 1985, the Atari ST, also based on the Motorola 68000
microprocessor, was introduced with the first color GUI in
the Atari TOS.
31
1990s and 2000s
In the early 1990s, the CD-ROM became an industry
standard, and by the mid-1990s one was built into almost
all desktop computers, and towards the end of the 1990s, in
laptops as well.
In 1994, Apple introduced the Power Macintosh series of
high-end professional desktop computers for desktop
publishing and graphic designers.
In the late 1990s CD-R and later, rewritable CD-RW drives
were included instead of standard CD ROM drives
Since the late 1990s, many more personal computers
started shipping that included USB (Universal Serial Bus)
ports for easy plug and play connectivity to devices
32
1990s and 2000s
In 2001, 125 million personal computers were shipped in
comparison to 48,000 in 1977
More than 500 million PCs were in use in 2002 and one
billion personal computers had been sold worldwide since
mid-1970s till this time
About 81.5 percent of PCs shipped had been desktop
computers, 16.4 percent laptops and 2.1 percent servers
United States had received 38.8 percent (394 million) of the
computers shipped, Europe 25 percent and 11.7 percent
had gone to Asia-Pacific region, the fastest-growing market
as of 2002
33
Programming Languages
Short History
Early history
1842-1843: Ada Lovelace translated the memoir of Italian
mathematician Luigi Menabrea about Charles Babbage's
newest proposed machine, the Analytical Engine.
36
First programming
languages
FLOW-MATIC, Grace Hopper in the US. It was developed for
the UNIVAC I at Remington Rand during the period from
1955 until 1959. Flow-Matic was a major influence in the
design of COBOL(1958)
The language Fortran was developed at IBM in the mid
1950s, and became the first widely used high-level general
purpose programming language.
LISP (1958), invented by John McCarthy
ALGOL 60 Report (the "ALGOrithmic Language"), ALGOL 68
1960 - Simula, the first language designed to support
object-oriented programming.
37
Fundamental paradigms
1960 - Simula, object-oriented programming.
1968 Logo
1969 - B (forerunner to C)
1970 Pascal
1970 Forth
1972 C, systems programming language
1972 Smalltalk, complete object-oriented language.
1972 Prolog - first logic programming language
1973 ML - functional programming language
1975 Scheme
1978 - SQL (a query language, later extended)
38
Modules, Performance
1980 - C++ (as C with classes, renamed in 1983)
1983 Ada
1984 - Common Lisp
1984 - MATLAB
1985 Eiffel
1986 - Objective-C
1986 Erlang
1987 Perl
1988 Tcl
1988 Mathematica
1989 - FL (Backus)
39
1990s: the Internet age
1990 Haskell
1991 Python
1991 - Visual Basic
1993 Ruby
1993 Lua
1994 - CLOS (part of ANSI Common Lisp)
1995 - Ada 95
1995 Java
1995 - Delphi (Object Pascal)
1995 JavaScript
1995 PHP
1996 WebDNA
1997 Rebol
1999 D
40
Current trends
Increasing support for functional programming
Constructs to support concurrent and distributed
programming
Component-oriented software development
Metaprogramming, reflection or access to the abstract
syntax tree
Integration with databases, including XML and relational
databases
XML for graphical interface (XUL, XAML)
Open source as a developmental philosophy for languages,
including the GNU compiler collection and recent languages
such as Python, Ruby, and Squeak.
AOP or Aspect Oriented Programming
41
Current trends
2000 ActionScript
2001 - C#
2001 - Visual Basic .NET
2002 - F#
2003 - Groovy
2003 - Scala
2007 Clojure
2009 Go
2011 Dar
2012 Rust
2014 Swift
http://en.wikipedia.org/wiki/
List_of_programming_languages
42
Python!
Created in 1991 by Guido van Rossum
! I chose Python as a working title for the project, being in a
slightly irreverent mood (and a big fan of
Monty Python's Flying Circus).
https://gvanrossum.github.io
! I am the author of the Python programming language.
! In January 2013 I joined Dropbox. I work on various Dropbox
products and have 50% for my Python work, no strings
attached. Previously, I have worked for Google, Elemental
Security, Zope Corporation, BeOpen.com, CNRI, CWI, and
SARA.
43
Python!
Useful as a scripting language
! script: A small program meant for one-time use
! Targeted towards small to medium sized projects
Used by:
! Google, Yahoo!, Youtube
! Many Linux distributions
! Games and apps (e.g. Eve Online)
44
Python!
Python is a multi-paradigm programming language:
! object-oriented programming and structured programming are
fully supported
! there are a number of language features which support
functional programming and aspect-oriented programming
(including by metaprogramming and by magic methods).
! many other paradigms are supported using extensions,
including design by contract and logic programming.
Python uses dynamic typing
An important feature of Python is dynamic name resolution
(late binding), which binds method and variable names
during program execution.
45
Python!
46
Installing Python
https://www.python.org/downloads/
Windows: Mac OS X:
Download Python from http:// Python is already installed.
www.python.org Open a terminal and run python
Install Python. or run Idle from Finder.
Run Idle from the Start Menu.
Linux:
Chances are you already have
Python installed. To check, run
python from the terminal.
If not, install from your
distribution's package system.
47
Interpreted Languages
interpreted
! Not compiled like Java
! Code is written and then directly executed by an interpreter
! Type commands into interpreter and see immediate results
Java: Runtime
Code Compiler Computer
Environment
48
The Python Interpreter
Allows you to type commands one-at-a-time and see results
A great way to explore Python's syntax
! Repeat previous command: Alt+P
! https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/
index.html 49
Our First Python Program
hello.py
1 print("Hello, world!")
50
Python Identifiers
51
Naming conventions
Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.
as finally or
54
An error
if True:!
print ("Answer")!
print ("True")!
else:!
print "(Answer")!
print ("False")
55
Multi-Line Statements
Statements in Python typically end with a new line. Python
does, however, allow the use of the line continuation
character (\) to denote that the line should continue. For
example:
total = item_one + \!
item_two + \!
item_three!
Statements contained within the [], {}, or () brackets do not
need to use the line continuation character. For example:
word = 'word!
sentence = "This is a sentence.!
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
57
Comments in Python
A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the end of
the physical line are part of the comment and the Python
interpreter ignores them.
# First comment!
print ("Hello, Python!") # second comment!
name = "Madisetti" # This is again comment
58
Waiting for the User
The following line of the program displays the prompt, the
statement saying Press the enter key to exit, and waits for
the user to take action
a = b = c = 1!
a, b, c = 1, 2, "john!
Variables can change (they are variable!)
x = 1.343 !
X = 2 !
x = 10 + 4!
x = -3!
61
Standard Data Types
The data stored in memory can be of many types. For
example, a person's age is stored as a numeric value and
his or her address is stored as alphanumeric characters.
62
Python Numbers
Number data types store numeric values. Number objects
are created when you assign a value to them. For example:
var1 = 1!
var2 = 10!
You can also delete the reference to a number object by
using the del statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]!
del var!
del var_a, var_b
63
Python Numbers
Python supports four different numerical types:
! int (signed integers)
! float (floating point real values)
! complex (complex numbers)
64
Python Strings
Strings in Python are identified as a contiguous set of
characters represented in the quotation marks. Python
allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ]
and [:] ) with indexes starting at 0 in the beginning of the
string
65
Python Lists
The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.
66
Python Lists
67
Python Tuples
A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated.
68
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )!
tinytuple = (123, 'john')!
print (tuple) # Prints complete tuple!
print (tuple[0]) # Prints first element of
the tuple!
print (tuple[1:3]) # Prints elements starting
from 2nd till 3rd: (786, 2.23) !
print (tuple[2:]) # Prints elements starting
from 3rd element!
print (tinytuple * 2) # Prints tuple two
times!
print (tuple + tinytuple) # Prints
concatenated tuple
69
>>> tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )!
>>> list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]!
>>> list[2] = 1000!
>>> list!
['abcd', 786, 1000, 'john', 70.2]!
>>> tuple[2] = 1000!
Traceback (most recent call last):!
File "<pyshell#13>", line 1, in <module>!
tuple[2] = 1000!
TypeError: 'tuple' object does not support item
assignment!
70
Python Dictionary
Python's dictionaries consist of key-value pairs. A dictionary
key can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary
Python object.
71
Python Dictionary
dict = {}!
dict['one'] = "This is one!
dict[2] = "This is two!
tinydict = {'name': 'john','code':6734, 'dept:'sales'}!
print (dict['one']) # Prints value for 'one' key!
print (dict[2]) # Prints value for 2 key!
print (tinydict) # Prints complete dictionary!
print (tinydict.keys()) # Prints all the keys!
print (tinydict.values()) # Prints all the values!
This is one!
This is two!
{'dept': 'sales', 'code': 6734, 'name': 'john'}!
['dept', 'code', 'name']!
['sales', 6734, 'john']
72
Data Type Conversion
To convert between types, you simply use the type name as
a function.
Function Description
int(x [,base]) Converts x to an 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.
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.
73
Data Type Conversion
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
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.
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.
74
Types of Operator
Python language supports the following types of operators:
! Arithmetic Operators
! Comparison (Relational) Operators
! Assignment Operators
! Logical Operators
! Bitwise Operators
! Membership Operators
! Identity Operators
75
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 21:
76
Python Comparison Operators
These operators compare the values on either sides of them
and decide the relation among them. They are also called
Relational operators.
77
Python Assignment Operators
78
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
>>> a = 60
>>> b = 13
>>> bin(a)
'0b111100'
>>> bin(b)
'0b1101
! a = 0011 1100 b = 0000 1101
79
Python Logical Operators
>>> a = True
>>> b = False
>>> a and b
False
>>> a or b
True
>>> not a
False
80
Python Membership Operators
Pythons membership operators test for membership in a
sequence, such as strings, lists, or tuples. There are two
membership operators:
! in Evaluates to true if it finds a variable in the specified
sequence and false otherwise.
! not in Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.
81
Python Identity Operators
Identity operators compare the memory locations of two
objects. There are two Identity operators:
! is Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise.
! is not Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.
>>> a = 20 >>> c = 30
>>> b = 20 >>> id(c)
>>> id(a) 4297624864
4297624544 >>> a is b
>>> id(b) True
4297624544 >>> a is c
False
82
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= Assignment operators
-= += *= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
83
Using Python as a Calculator
>>> 2+2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
84
Using Python as a Calculator
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the
division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
85
Using Python as a Calculator
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
>>> 55**55
524744532468751923546122657597368049278513737089035
272057324643668607677682302892208099365234375
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
86
Using Python as a Calculator
In interactive mode, the last printed expression is assigned to the
variable _.
>> 5+75
80
>>> _
80
87
Strings
Besides numbers, Python can also manipulate strings, which can be
expressed in several ways. They can be enclosed in single quotes ('...')
or double quotes ("...") with the same result
88
Strings
If you want to concatenate variables or a variable and a
literal, use +:
Strings can be indexed (subscripted), with the first character
having index 0.
89
Strings
>>> word[-1] # last character
'n
>>> word[-2] # second-last character
'o
>>> word[-6]
'P
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho
>>> word[:2] + word[2:]
'Python
>>> word[:4] + word[4:]
'Python'
90
Lists
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
91
List concatenation
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
92
append
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
93
Nested lists
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
94
Decision Making
Decision structures evaluate multiple expressions which
produce TRUE or FALSE as outcome. You need to determine
which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Python programming language assumes any non-zero and
non-null values as TRUE, and if it is either zero or null,
then it is assumed as FALSE value.
Python programming language provides following types of
decision making statements:
! if statement
! if else statement
! nested if statements
95
IF Statement
The if statement contains a logical expression using which
data is compared and a decision is made based on the
result of the comparison:
if expression: !
statement(s)
96
IF Statement
var1 = 100!
if var1:!
print ("1 - Got a true expression value")!
print (var1)!
var2 = 0!
if var2:!
print ("2 - Got a true expression value")!
print (var2)print ("Good bye!")!
97
IFELSE Statement
An else statement can be combined with an if statement.
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
if expression:!
statement(s)!
else:!
statement(s)
98
IFELSE Statement
amount=int(input("Enter amount: "))!
if amount<1000:!
discount=amount*0.05!
print ("Discount",discount)!
else:!
discount=amount*0.10!
print ("Discount",discount)!
print ("Net payable:",amount-discount)!
99
The elif Statement
The elif statement allows you to check multiple expressions
for TRUE and execute a block of code as soon as one of the
conditions evaluates to TRUE.
if expression1:!
statement(s)!
elif expression2:!
statement(s)!
elif expression3:!
statement(s)!
else: statement(s)
100
The elif Statement
amount=int(input("Enter amount: "))!
if amount<1000:!
discount=amount*0.05!
print ("Discount",discount)!
elif amount<5000:!
discount=amount*0.10!
print ("Discount",discount)!
else:!
discount=amount*0.15!
print ("Discount",discount) !
print ("Net payable:",amount-discount)
101
The elif Statement
Enter amount: 600!
Discount 30.0!
Net payable: 570.0!
102
Loops
In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the
second, and so on. There may be a situation when you need
to execute a block of code several number of times.
A loop statement allows us to execute a statement or group
of statements multiple times.
Python programming language provides following types of
loops:
! while loop
! for loop
! nested loops
103
while Loop Statement
A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
while expression:!
statement(s)
104
while Loop Statement
count = 0!
while (count < 5):!
print ('The count is:', count)!
count = count + 1!
print ("Good bye!")!
105
for Loop Statement
The for statement in Python has the ability to iterate over
the items of any sequence, such as a list or a string.
106
for Loop Statement
for letter in 'Python':!
# traversal of a string sequence!
print ('Current Letter :', letter)!
print()!
fruits = ['banana', 'apple', 'mango']!
for fruit in fruits:!
# traversal of List sequence!
print ('Current fruit :', fruit)!
print ("Good bye!")
107
for Loop Statement
The built-in function range() is the right function to iterate over a sequence of
numbers. It generates an iterator of arithmetic progressions.
>>> range(5)!
range(0, 5)!
>>> list(range(5))!
[0, 1, 2, 3, 4]!
>>> for var in list(range(5)):print(var)!
0!
1!
2!
3!
4!
>>> for var in (range(5)):print(var)!
0!
1!
2!
3!
4!
108
fruits = ['banana', 'apple', 'mango']!
for index in range(len(fruits)):!
print ('Current fruit :', fruits[index])!
print ("Good bye!")!
109
Nested loops
Python programming language allows to use one loop inside
another loop.
while expression:!
while expression:!
statement(s)!
statement(s)
110
for i in range(1,11):!
for j in range(1,11):!
k=i*j!
print (k, end=' ')!
print()!
1 2 3 4 5 6 7 8 9 10 !
2 4 6 8 10 12 14 16 18 20!
3 6 9 12 15 18 21 24 27 30 !
4 8 12 16 20 24 28 32 36 40 !
5 10 15 20 25 30 35 40 45 50 !
6 12 18 24 30 36 42 48 54 60 !
7 14 21 28 35 42 49 56 63 70 !
8 16 24 32 40 48 56 64 72 80 !
9 18 27 36 45 54 63 72 81 90 !
10 20 30 40 50 60 70 80 90 100
111
Loop Control Statements
Loop control statements change execution from its normal
sequence.
112
break statement
The break statement is used for premature termination of current
loop. After abandoning the loop, execution at the next statement
is resumed:
for letter in 'Python': # First Example!
if letter == 'h':!
break!
print ('Current Letter :', letter)!
113
Using else Statement with Loops
Python supports to have an else statement associated with
a loop statement
If the else statement is used with a for loop, the else block
is executed only if for loops terminates normally (and not
by encountering break statement).
114
Examples
no=int(input('any number: '))!
numbers=[11,33,55,39,55,75,37,21,23,41,13]!
for num in numbers:!
if num==no:!
print ('number found in list')!
break!
else:!
print ('number not found in list')!
115
Examples
numbers=[11,33,55,39,55,75,37,21,23,41,13]!
for num in numbers:!
if num%2==0:!
print ('the list contains an even number')!
break!
else:!
print ('the list does not contain even number')!
116
continue statement
The continue statement in Python returns the control to the beginning of current
loop.
When encountered, the loop starts next iteration without executing remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
117
pass Statement
The pass statement is a null operation; nothing happens
when it executes.
It is used when a statement is required syntactically but you
do not want any command or code to execute.
118