Python Programming - III. Controlling the Flow

89
PYTHON PROGRAMMING III. Controlling the Flow Engr. Ranel O. Padon

description

Feel free to download the material for offline viewing later, better images' resolutions, and crispier fonts.

Transcript of Python Programming - III. Controlling the Flow

Page 1: Python Programming - III. Controlling the Flow

PYTHON PROGRAMMINGIII. Controlling the Flow Engr. Ranel O. Padon

Page 2: Python Programming - III. Controlling the Flow

PYTHON PROGRAMMING TOPICS

I • Introduction to Python Programming

II • Python Basics

III • Controlling the Program Flow

IV • Program Components: Functions, Classes, Modules, and Packages

V • Sequences (List and Tuples), and Dictionaries

VI • Object-Based Programming: Classes and Objects

VII • Customizing Classes and Operator Overloading

VIII • Object-Oriented Programming: Inheritance and Polymorphism

IX • Randomization Algorithms

X • Exception Handling and Assertions

XI • String Manipulation and Regular Expressions

XII • File Handling and Processing

XIII • GUI Programming Using Tkinter

Page 3: Python Programming - III. Controlling the Flow

CONTROLLING THE FLOW

Page 4: Python Programming - III. Controlling the Flow

CONTROLLING THE FLOW

Page 5: Python Programming - III. Controlling the Flow

CONTROLLING THE FLOW

Page 6: Python Programming - III. Controlling the Flow

CONTROLLING THE FLOW: STRUCTURES

Page 7: Python Programming - III. Controlling the Flow

DECISION-MAKING

our lives are filled with choices:

1. Saan ako kakain?

2. Gi-gimmick ba ako sa Friday?

3. Gusto niya rin kaya ako?

Page 8: Python Programming - III. Controlling the Flow

DECISION-MAKING

many choices you make depend on other circumstances

1. Saan ako kakain?

May budget pa ba akong malupit? (Yes|No)

2. Gi-gimmick ba ako sa Friday?

Wala ba ako kelangang tapusin? (Yes|No)

3. Gusto niya rin kaya ako?

Lagi ba syang nagpaparamdam sa akin? (Yes|No)

Page 9: Python Programming - III. Controlling the Flow

ALGORITHMS

Before writing a program to solve a particular problem,

it is essential to have a thorough understanding of the

problem and a carefully planned approach to solving the

problem.

The Elevator-Mirror Problem

Page 10: Python Programming - III. Controlling the Flow

ALGORITHMS

Any computing problem can be solved by executing a series of

actions in a specified order.

An algorithm is a procedure for solving a problem in terms of

1. actions to be executed

2. the order of execution

Page 11: Python Programming - III. Controlling the Flow

ALGORITHMS

“rise-and-shine” algorithm for getting out of bed and

going to work:

(1) get out of bed

(2) take off pajamas

(3) take a shower,

(4) get dressed

(5) eat breakfast

(6) carpool to work.

Page 12: Python Programming - III. Controlling the Flow

ALGORITHMS

Suppose that the same steps are performed in a

slightly different order:

(1) get out of bed

(2) take off pajamas

(3) get dressed

(4) take a shower

(5) eat breakfast

(6) carpool to work

Page 13: Python Programming - III. Controlling the Flow

PSEUDOCODE

Pseudocode is an artificial and informal language that

helps programmers develop algorithms.

Characteristics

similar to everyday English

convenient and user-friendly

not an actual computer programming language

Page 14: Python Programming - III. Controlling the Flow

PSEUDOCODE

Pseudocode helps the programmer “plan” a program

before attempting to write it in a programming language

A carefully prepared pseudocode program can be converted easily

to a corresponding Python program

Page 15: Python Programming - III. Controlling the Flow

PROGRAM CONTROL

Program Control

specifying the order in which statements are to be executed

in a computer program

Page 16: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

By default, program execution is sequential.

You could break this behavior using transfer of control.

Transfer of Control makes use of Control Structures.

Page 17: Python Programming - III. Controlling the Flow

STRUCTURED PROGRAMMING

In the 1960’s, indiscriminate use of transfer of controls,

especially goto statements, resulted to spaghetti code.

Structured programming is synonymous to goto elimination or

goto-less programming.

Page 18: Python Programming - III. Controlling the Flow

STRUCTURED PROGRAMMING

Structured programs are clearer, easier to debug and modify and

more likely to be bug-free in the first place.

Page 19: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

Structured programs could be written in terms of

three control structures:

I. Sequence

II. Selection

III. Repetition

Page 20: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

I. Sequence Control Structure

- the default flow of program

Page 21: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

II. Selection Control Structures

a. if (single selection)

b. if/else (double selection)

c. if/elif/else (multiple selection)

Page 22: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

III. Repetition Control Structures

a. while (single selection)

b. for (double selection)

Page 23: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

In Summary:

I. Sequence

II. Selection (if, if/else, if/elif/else)

III. Repetition (while, for)

Page 24: Python Programming - III. Controlling the Flow

CONTROL STRUCTURES

Any Python program can be constructed from 6 different types of

control structures (sequence, if, if/else, if/elif/else, while and for)

combined in 2 ways (control-structure stacking and control-structure

nesting)

Page 25: Python Programming - III. Controlling the Flow

CONDITIONAL STATEMENT

A conditional statement is basically a simple yes or no question.

‘Mahal mo ba ako?’:

‘Oo’:

“Pakasal na tayo.”

‘Hindi Eh’:

“Iyak na lang ako.”

Page 26: Python Programming - III. Controlling the Flow

CONDITIONAL STATEMENTS

Conditional statements are one of the most important programming

concepts: They let your programs react to different situations and

behave intelligently.

Page 27: Python Programming - III. Controlling the Flow

CONDITIONAL STATEMENTS

Page 28: Python Programming - III. Controlling the Flow

CONDITIONAL STATEMENTS

Conditional statements are also called “if/then” statements,

because they perform a task only if the answer to a question is

true:

‘If may sapat akong pera, then bibili ako ng Windows 8!’

Page 29: Python Programming - III. Controlling the Flow

if SELECTION STRUCTURE

if (kondisyon):

# mga gagawin kung totoo ung kondisyon

if (maitim == True):

print “maitim ako!”

Note: Parentheses are optional.

Page 30: Python Programming - III. Controlling the Flow

if SELECTION STRUCTURE

Pseudocode:

Code:

Page 31: Python Programming - III. Controlling the Flow

if SELECTION STRUCTURE

Flowchart:

Page 32: Python Programming - III. Controlling the Flow

if/else SELECTION STRUCTURE

Page 33: Python Programming - III. Controlling the Flow

if/elif/else SELECTION STRUCTURE

Page 34: Python Programming - III. Controlling the Flow

if/elif/else SELECTION STRUCTURE

Page 35: Python Programming - III. Controlling the Flow

if/elif/else SELECTION STRUCTURE

Page 36: Python Programming - III. Controlling the Flow

if/elif/else SELECTION STRUCTURE

A nested if/else structure is faster than a series of single-selection if

structures because the testing of conditions terminates after one of

the conditions is satisfied.

Page 37: Python Programming - III. Controlling the Flow

if/elif/else SELECTION STRUCTURE

In a nested if/else structure, place the conditions that are more likely

to be true at the beginning of the nested if/else structure.

This enables the nested if/else structure to run faster and exit earlier

Page 38: Python Programming - III. Controlling the Flow

COMPOUND STATEMENT

Page 39: Python Programming - III. Controlling the Flow

EMPTY STATEMENT

if gender == “sirena”:

pass

Page 40: Python Programming - III. Controlling the Flow

while REPETITION STRUCTURE

Page 41: Python Programming - III. Controlling the Flow

COUNTER-CONTROLED REPETITION

Page 42: Python Programming - III. Controlling the Flow

COUNTER-CONTROLED REPETITION

Page 43: Python Programming - III. Controlling the Flow

COUNTER-CONTROLED REPETITION

Page 44: Python Programming - III. Controlling the Flow

COUNTER-CONTROLED REPETITION

Because floating-point values may be approximate, controlling the

counting of loops with floating-point variables may result in imprecise

counter values and inaccurate tests for termination.

Programs should control counting loops with integer values.

Page 45: Python Programming - III. Controlling the Flow

SENTINEL-CONTROLED REPETITION

Sentinel Value:

also called as dummy value, signal value or flag value

Page 46: Python Programming - III. Controlling the Flow

SENTINEL-CONTROLED REPETITION

Page 47: Python Programming - III. Controlling the Flow

SENTINEL-CONTROLED REPETITION

Page 48: Python Programming - III. Controlling the Flow

SENTINEL-CONTROLED REPETITION

Page 49: Python Programming - III. Controlling the Flow

SENTINEL-CONTROLED REPETITION

In a sentinel-controlled loop, the prompts requesting data entry

should explicitly remind the user of the sentinel value.

Page 50: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

Write a program to summarize the exam results of 10 students. Next

to each name is written a I if the student passed the exam and a 2 if

the student failed.

1. Input each test result (i.e., a 1 or a 2). Display the message

“Enter result” on the screen each time the program requests

another test result.

2. Count the number of test results of each type.

3. Display a summary of the test results: the number of students

who passed and the number of students who failed.

4. If more than 8 students passed the exam, print the message

“Raise tuition.”

Page 51: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

Page 52: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

Page 53: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

Sample Run 1:

Page 54: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

Sample Run 2:

Page 55: Python Programming - III. Controlling the Flow

NESTED CONTROL STRUCTURES

The most difficult part of solving a problem on a computer is

developing an algorithm for the solution.

Once a correct algorithm has been specified, the process of

producing a working Python program from the algorithm normally is

straightforward.

Page 56: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

Page 57: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

the built-in range(start, end, step) function returns a list containing

integers in the range of start to end-1.

What is range(10, 0, -1)?

Page 58: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

Page 59: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

PRACTICE EXERCISE:

using for loop print the following number series:

a.) 7, 14, 21, …, 70, 77

b.) 20, 18, 16, …, 4, 2

c.) 99, 88, 77, …, 11, 0

Page 60: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

Page 61: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

Compound Interest

Page 62: Python Programming - III. Controlling the Flow

for REPETITION STRUCTURE

Page 63: Python Programming - III. Controlling the Flow

while VERSUS for REPETITION

Page 64: Python Programming - III. Controlling the Flow

STRUCTURED PROGRAMMING SUMMARY

Page 65: Python Programming - III. Controlling the Flow

break AND continue STATEMENTS

programmer could also alter the flow of a loop

using the break and continue statements

Page 66: Python Programming - III. Controlling the Flow

break STATEMENT

breaks or causes immediate exit from while or for structure

Page 67: Python Programming - III. Controlling the Flow

break STATEMENT

Page 68: Python Programming - III. Controlling the Flow

break STATEMENT

Page 69: Python Programming - III. Controlling the Flow

continue STATEMENT

skips the remaining statements in the body of a while or for structure

and proceeds with the next iteration of the loop

Page 70: Python Programming - III. Controlling the Flow

continue STATEMENT

causes immediate exit from while or for structure

Page 71: Python Programming - III. Controlling the Flow

break AND continue STATEMENTS

break and continue statements are also used to improve performance

by minimizing the amount of processing by causing early exit or

avoiding unneeded computations or cases.

Page 72: Python Programming - III. Controlling the Flow

LOGICAL OPERATORS

Relational Operators:

<, >, <=, >=, ==, !=

Logical Operators:

and, or, not

Page 73: Python Programming - III. Controlling the Flow

LOGICAL and OPERATOR

Page 74: Python Programming - III. Controlling the Flow

LOGICAL or OPERATOR

Page 75: Python Programming - III. Controlling the Flow

LOGICAL not OPERATOR

Page 76: Python Programming - III. Controlling the Flow

AUGMENTED ASSIGNMENT

Assignment Expressions could be abbreviated.

Page 77: Python Programming - III. Controlling the Flow

AUGMENTED ASSIGNMENT

The += symbol adds the value of the expression on the right of the

+= sign to the value of the variable on the left of the sign and stores

the result in the variable on the left of the sign.

Page 78: Python Programming - III. Controlling the Flow

AUGMENTED ASSIGNMENT

Page 79: Python Programming - III. Controlling the Flow

AUGMENTED ASSIGNMENT

Page 80: Python Programming - III. Controlling the Flow

PYTHON 2.2 KEYWORDS

special/reserved words used for control structures &

other Python features

they could not be used as variable names

Page 81: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 1

Write a program that reads a positive integer and

determines if it is a prime number or not.

Page 82: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 2

A palindrome is a number or a text phrase that reads the same

backwards or forwards.

For example, each of the following five-digit integers is a palindrome:

12321, 55555, 45554 and 11611.

Write a program that reads in a five-digit integer and determines

whether it is a palindrome. (Hint: Use the division and modulus

operators to separate the number into its individual digits.)

Page 83: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 3

Write a program that reads a nonnegative integer and computes and

prints its factorial.

The factorial of a nonnegative integer n is written n!

n! = n· (n - 1) · (n - 2) · … · 1

(for values of n >= 1) and

n! = 1

(for n = 0).

For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120.

Page 84: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 4

Write a program that reads a nonnegative integer and computes and

prints its factorial.

The factorial of a nonnegative integer n is written n!

n! = n· (n - 1) · (n - 2) · … · 1

(for values of n >= 1) and

n! = 1

(for n = 0).

For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120.

Page 85: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 5

What is the output of this? Explain why.

for row in range(0,5):for column in range(0,3):

print “*”print

Page 86: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 6

What is the output of this? Explain why.

for row in range(0,5):for column in range(0,3):

print “*”,print

Page 87: Python Programming - III. Controlling the Flow

PRACTICE EXERCISE 7

What is the output of this? Explain why.

for group in range(0,3):for row in range(0,4):

for column in range(0,5):print "*",

printprint

Page 88: Python Programming - III. Controlling the Flow

To be able to control the flow is powerful!

Page 89: Python Programming - III. Controlling the Flow

REFERENCES

Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).

Disclaimer: Most of the images/information used here have no proper source

citation, and I do not claim ownership of these either. I don’t want to reinvent the

wheel, and I just want to reuse and reintegrate materials that I think are useful or

cool, then present them in another light, form, or perspective. Moreover, the

images/information here are mainly used for illustration/educational purposes

only, in the spirit of openness of data, spreading light, and empowering people

with knowledge.