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

Lecture 4 - Controlling The Execution and Modularization of Python Programs

Controling the execution and modularisation

Uploaded by

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

Lecture 4 - Controlling The Execution and Modularization of Python Programs

Controling the execution and modularisation

Uploaded by

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

CS4051 FUNDAMENTALS OF

COMPUTING

• Topic 4: Controlling the execution


and modularization of Python
programs
CONTENT
1 Control Operations
– E.g., conditional operations: if-else
– E.g., looping operations: for, while
2 Modularizing Python programs
– In blocks
– In modules/functions
3 Creating and Executing Python Scripts
– Streamlined/sequential processing
CONTROL OPERATIONS

• Control operations allow to control the program


flow
• Therefore, specify more complex algorithms for
data processing.
– E.g. ordering/sorting: [5, 1, 2, 4, 3] ➔ [1, 2, 3, 4, 5]
MAIN OPERATIONS IN
PYTHON
• In Python there are 6 main operations
– Variable declaration: naming placeholders for individual data.
– Value assignment: assigning values to existing placeholders.
– Block operations: grouping the operations in a sequence.
– Function definition: naming sequences of operations.

– Conditional execution: alternating the operations based on conditions.


– Looping: enforcing repetition of the operations.
VARIABLES
• Python is a language with dynamic typing
– we do not need to specify data type of a variable
>>> payDay="twenty third" # a string
>>> payday=23 # an integer

• Python uses type conversion rules.


– If you do not meet the type conversion rules, Python
issues a type error
VARIABLE SCOPE
• The variable types: global and local variables
def f(): As soon as defined, the scope
print s of the variable cannot be
changed
# Global scope
s = “Hello world"
f()
– The scope of a variable determines its value automatically
def f():
s = "Me too."
print s # “Me too." is printed

# Global scope
s = “Hello world"
f()
ASSIGNMENTS (1/2)
Syntax: <variable> = <expr>
<variable> = eval (input (<prompt>))
Interpretation:
– The expression is evaluated to produce a data value, which is
then associated with the name:
>>> a = 5 * 2
– The prompt does not participate in the evaluation and eval
evaluates the input as expression
>>> height = eval(input("Your height please: ")) # try to type in expression: 5*2
• The assignment determines the data type
>>> pi=3.14 # pi is a number
>>> pi="three fourteen" # pi is a string
– Note: for a variable, assignments can happen multiple times,
therefore types can be changed as shown above.
ASSIGNMENTS (2/2)
• Python supports simultaneous assignment.
Example-1: a, b = X+Y, X-Y
Syntax: <var-1> , <var-2> … = <expr-1> , <expr-2>…
Interpretation: Each of the variables <var> in the list on LHS are
associated with the result of the evaluation of an expressions
<expr> in the same position on RHS

• Example-2:
>>> height, weight=eval(input("Your height and weight: "))
Your height and weight: 1, 2
>>> print("Your height=", height," and weight=",weight)
CONDITIONS

• Conditional execution of an operation allows to control


the execution flow depending on logical conditions
Syntax: if <condition> : <expression>

Example: Conditional execution of operations


>>> if x > y or x < y: print("x=", x)
x=5
>>>

• Operators used in <condition>:


<, <=, >, >=, ==, !=
BOOLEAN OPERATIONS FOR FORMING
COMPLEX CONDITIONS

Operation Example
if a>5 or a<-5:
x or y
print("Hello World")
if a>5 and a<-5:
print("Hello World")
x and y
else:
print("Sorry World")
If not(a>5):
not x
print("Hello World")
LOOPS - FOR
Syntax: for <var> in <sequence> :
<expression>
Interpretation: repeat the <expression>
with <var> is assigned by the values of
<sequence> each time
Example: ranging over listed sequence of values
DEFINITE LOOPS

Example: ranging over enumerated sequence


>>> for counter in range(4):
... print (counter)
...
>>>
Here range is a build-in Python function which
generates sequence of natural numbers:
[0, 1, 2, 3]
CONDITIONAL LOOPS
Syntax: while <condition> :
<expression>

Example: Filtering the input data until satisfactory


value within the range from 1 to 100 is entered
>>> min, max = 1,100
>>> val=int(input("Enter an integer:"))
...
>>> while val <= min or val >=max:
... print("Sorry, wrong value.")
... val=int(input("Enter another:"))
... else:
... print("Thanks, this will do.")
>>>
CONDITIONAL OPERATIONS: IF-ELSE
>>> if x>y:
... Print(“x is greater than y”)
... elif x<y:
... Print(“x is less than y”)
... else:
... Print(“x is equal to y”)
...
>>>
BLOCK OPERATIONS
• Grouping the operations in a sequence (e.g. inside “if i <
0”, is a block)
if i < 0:
unit_price, no_items = 17.5, 100
total_sum=unit_price*no_items
print("The subtotal for " + item_name + " is: " +
str(total_sum))
else:
print("i > 0")

• Use indentation (four spaces suggested), so that everything


which belongs to the same block is indented equally
• Use one more indentation on each line of a statement split
between several lines
• Loops would use Accumulator Variable to keep a running
total.
FUNCTIONS

• Functions are simply named block operations for


use within the program multiple times

>>> def hello():


... print("Hello, new user.")
... you=input("What is your name? ")
... print("Nice to meet you, " + you + "!")
...
>>> hello()
Hello, new user.
What is your name? Vassil
Nice to meet you, Vassil!
>>>
EXAMPLE: PSEUDORANDOM
NUMBER GENERATION
>>> def gen(x, n):
... print("Pseudorandom Numbers:")
... for i in range(n):
... x = 3.9 * x * (1 - x)
... print(x)
...
>>> gen(0.7,10)
Pseudorandom numbers:
0.8190000000000001
0.5781320999999998
Accumulator Variable?
0.9511919623034011
0.18106067129594453
0.5782830479626452
0.951099881166545
0.18138469912496308
0.5790887311884079
0.9506053931361303
0.1831236407388703
MODULARIZING PYTHON PROGRAMS
• Modularization: organize codes in a logical way; is
one of the main techniques for dealing with the
complexity of software development.
– Module: a collections of data and functions, stored a file.
– Package: The files of the modules are organized into a
directory with subdirectories.

• Use a module in a program, e.g. math


>>> import math
>>> print(math.pi)
3.141592653589793
>>> import pkgxxx
MODULARIZING PYTHON PROGRAMS

• Python comes with an extensive set of library modules,


which is one of the reason for its popularity amongst the
developers:
– Mathematical calculations
– Text processing
– Statistical data processing
– Machine Learning algorithms
– 2D and 3D graphical presentation
• We can devise our own libraries/modules as well. The
simplest way is to save your code to.py file, then to
import the file.
INVOKING PYTHON FOR EXECUTING SCRIPTS
• Python programs are called scripts; they are simply files
with an extension .py
• The invocation of Python for executing the scripts can be
done in one of the four ways:
o >>> myscript
o python myscript.py
The two methods above requires setting of the paths
o Load myscript.py to IDLE in Python, then F5
o Double click: myscript.py
This method requires configuring the operating system to
recognize file extension .py as executed by Python
INPUT FROM/OUTPUT TO A FILE

• Python reads the data from the file instead of the


keyboard:
>>> myscript.py < mydata.in
python myscript.py < mydata.in

Note: In such a case all input data needs to be in the input


data file and no reading from the keyboard will take place
• Output data to a file instead of screen
>>> myscript.py > mydata.out
python myscript.py > mydata.out
INPUT FROM A FILE WITHOUT SCRIPT

• Alternative way to read a file without a script to


run:
f = open("C:\\Users\\sryyu\\Desktop\\myData.txt", "r")
l= f.read()
print(l)
3. COMBINING FILE INPUT AND FILE OUTPUT (1/2)
• Input from a file and then output the results to another file
>>> myscript.py < mydata.in > mydata.out
python myscript.py < mydata.in >
mydata.out
Example: Reporting the number of Students in a module
❖ Python script myscript.py
code=input()
num=int(input())
print('Module '+ code +' has '+ str(num) + ' students')
❖ Content of the input data file mydata.in
CS4051
87
❖ Generated output file mydata.out
3. COMBINING FILE INPUT AND FILE OUTPUT (2/2)
STREAMLINED/SEQUENTIAL DATA PROCESSING
• Python scripts can be executed one after another, each one
• passing its output to the next script as input
• myscript.py | myreport.py
❖ myscript.py take data from mydata.in output to myreport.py
code=input() CS4051
num=int(input()) 87
print('Module '+ code +' has '+ str(num) + ' students')
❖ myreport.py take data from myscript.py output to mydata.out
msg=input()
print('Record:' + msg)
❖ Python streamed data processing with two scripts
myscript.py < mydata.in | myreport.py > mydata.out
❖ The output produced in file mydata.out in this case:
Record: Module CS4051 has 87 students

You might also like