L3 - Python Scripts,
Statements
By
Dr. Mubarak Sufyan
1
Table of content References
File Objects
The with statement
Python Script
Plotting in Python
Condition Statement
If statement
If else
If else if
Iteration
For loop
Fibonacci Numbers
Nested For Loops
While
Break Statement
2
References
3
Reference
Assignment manipulates references
x = y does not make a copy of the object y references
x = y makes x reference the object y references
Very useful; but beware!
Example:
>>> a = [1, 2, 3] # a now references the list [1, 2, 3]
>>> b = a # b now references what a references
>>> a.append(4) # this changes the list a references
>>> print b # if we print what b references,
[1, 2, 3, 4] # SURPRISE! It has changed…
4
Reference
There is a lot going on when we type:
x=3
First, an integer 3 is created and
stored in memory
A name x is created
An reference to the memory location
storing the 3 is then assigned to the
name x
So: When we say that the value of x is For example, we could increment x:
3
>>> x = 3
we mean that x now refers to the
integer 3 >>> x = x + 1
>>> print x
4
5
Reference – Example1
References
Every object name is a reference to this object!
An assignment to a new name creates an additional
reference to this object.
Reference – Example2
Hint: copy a list
s2 = s1[:] oder s2 = list(s1)
Operator is compares two references (identity),
Operator == compares the contents of two objects
Assignment:
different behavior depending on object type
Strings, numbers (simple data types): create a new object
with new value
Lists, dictionaries, ...: the original object will be changed
6
File Objects
7
File Objects
f = open(filename[, mode[, buffersize])
mode can be "r", "w", "a" (like C stdio); default "r" file1 = open (" spam ", "r")
file2 = open ("/ tmp/ eggs ", "wb")
append "b" for text translation mode
• Read mode: r
append "+" for read/write open
• Write mode (new file): w
buffersize: 0=unbuffered; 1=line-buffered; • Write mode, appending to the end: a
buffered • Handling binary files: e.g. rb
methods: • Read and write (update): r+
read([nbytes]), readline(), readlines()
write(string), writelines(list)
seek(pos[, how]), tell()
flush(), close()
fileno()
8
Files
File objects are built for interacting with files on
the system.
Same object used for any file type.
User has to interpret file content and maintain
integrity.
Operations on Files
Read: f.read([size])
Read a line: f.readline()
Read multiple lines: f.readlines([sizehint])
Write: f.write(str)
Write multiple lines: f.writelines(sequence)
Close file: f.close()
The with statement
File handling (open/close) can be done by the context manager with .
(⇒section Errors and Exceptions on slide 64).
After finishing the with block the file object is closed, even if an
exception occurred inside the block.
10
Python Scripts
11
Python Scripts
When you call a python program from the command line the interpreter
evaluates each expression in the file
From the Python Shell you select Run → Run Module or hit F5 in order to
run or execute the Python Script
Run Python Scripts from the Command Prompt in Windows
12
Run Python Scripts
13
Run Python Scripts
Running Python Scripts from Console window on macOS 14
Plotting in Python
15
Plotting in Python Plotting functions that
you will use a lot:
Typically you need to create some plots or charts. plot()
In order to make plots or charts in Python you will title()
need an external library.
xlabel()
The most used library is Matplotlib.
ylabel()
Matplotlib is a Python 2D plotting library
axis()
Here you find an overview of the Matplotlib library:
grid()
https://matplotlib.org
import the whole library like this: subplot()
legend()
show()
4 basic plotting function in the Matplotlib library:
1. plot()
2. xlabel()
• In order to make plots or charts in Python you will need
an external library
3. ylabel()
• The most used library is Matplotlib.
4. show() • Matplotlib is a Python 2D plotting library Here you find an
16
overview of the Matplotlib library: https://matplotlib.org
Plotting in Python
17
Subplots
The subplot command enables you to display multiple plots in the same
window.
Example will be the Quiz
18
Condition Statements
19
Conditions : If / Else
Syntax
If, elif, and else statements are used to implement
conditional program behavior
Syntax: if condition:
elif Boolean_value: statements
…some other code [elif condition:
elif Boolean_value: statements] ...
…some other code else:
else: statements
…more code
elif and else are not required
used to chain together multiple conditional
statements or provide a default case.
20
• <condition> has a value True or False
• evaluate expressions in that block if
<condition> is True
21
Example
22
Example
23
INDENTATION
matters in Python
how you denote blocks of code
24
INDENTATION
25
if statements
26
Iteration
for var in sequence:
statements
while condition:
statements
Do … while condition:
break
continue
27
For loops
iterate through numbers in a sequence
A For loop is used for iterating over a sequence.
All programs will use one or more For loops.
28
For loops
29
Range(start,stop,step)
Default values are start = 0 and step = 1 and optional
Loop until value is stop – 1
30
Fibonacci numbers
Fibonacci numbers are used in the analysis of financial markets, in strategies
such as Fibonacci retracement, and are used in computer algorithms such as
the Fibonacci search technique and the Fibonacci heap data structure.
In mathematics, Fibonacci numbers are the numbers in the following sequence:
0, 1, 1, 2 ,3, 5, 8, 13, 21, 34, 55, 89, 144, . . .
By definition, the first two Fibonacci numbers are 0 and 1, and each
subsequent number is the sum of the previous two.
In mathematical terms, the sequence n of Fibonacci numbers is defined by the
recurrence relation
Assignment:
write a Python script that calculates the N first Fibonacci numbers
31
Nested For Loops
use one loop inside another loop
32
While Loops
<condition> evaluates to a Boolean
If <condition> is True, do all the steps inside the
while code block
check <condition> again
repeat until <condition> is False
Note: break and continue work for while loops, too.
33
for VS while LOOPS
For While
know number of iterations unbounded number of iterations
can end early via break can end early via break
uses a counter can use a counter but must initialize
before loop and increment it inside
loop
can rewrite a for loop using a while may not be able to rewrite a while
loop loop using a for loop
34
Break STATEMENT
• immediately exits
whatever loop it is in
• skips remaining
expressions in code block
• exits only innermost loop!
35
Exercise:
1) Programming Challenge: Hollow Square
Write a program that prints the pattern to the right using functions
36
References:
For more information, you can read from “Python
for Everybody” book
Chapter 3 Conditional execution
Chapter 5 Iteration
Chapter 7 Files
37
End
38