Lec 03 Python Scripts and Statement
Lec 03 Python Scripts and Statement
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
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
12
Run Python Scripts
13
Run Python Scripts
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:
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
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
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