Python Programming - III. Controlling the Flow

Post on 15-Jan-2015

1.043 views 0 download

Tags:

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

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

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

CONTROLLING THE FLOW

CONTROLLING THE FLOW

CONTROLLING THE FLOW

CONTROLLING THE FLOW: STRUCTURES

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?

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)

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

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

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.

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

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

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

PROGRAM CONTROL

Program Control

specifying the order in which statements are to be executed

in a computer program

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.

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.

STRUCTURED PROGRAMMING

Structured programs are clearer, easier to debug and modify and

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

CONTROL STRUCTURES

Structured programs could be written in terms of

three control structures:

I. Sequence

II. Selection

III. Repetition

CONTROL STRUCTURES

I. Sequence Control Structure

- the default flow of program

CONTROL STRUCTURES

II. Selection Control Structures

a. if (single selection)

b. if/else (double selection)

c. if/elif/else (multiple selection)

CONTROL STRUCTURES

III. Repetition Control Structures

a. while (single selection)

b. for (double selection)

CONTROL STRUCTURES

In Summary:

I. Sequence

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

III. Repetition (while, for)

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)

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.”

CONDITIONAL STATEMENTS

Conditional statements are one of the most important programming

concepts: They let your programs react to different situations and

behave intelligently.

CONDITIONAL STATEMENTS

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!’

if SELECTION STRUCTURE

if (kondisyon):

# mga gagawin kung totoo ung kondisyon

if (maitim == True):

print “maitim ako!”

Note: Parentheses are optional.

if SELECTION STRUCTURE

Pseudocode:

Code:

if SELECTION STRUCTURE

Flowchart:

if/else SELECTION STRUCTURE

if/elif/else SELECTION STRUCTURE

if/elif/else SELECTION STRUCTURE

if/elif/else SELECTION STRUCTURE

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.

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

COMPOUND STATEMENT

EMPTY STATEMENT

if gender == “sirena”:

pass

while REPETITION STRUCTURE

COUNTER-CONTROLED REPETITION

COUNTER-CONTROLED REPETITION

COUNTER-CONTROLED REPETITION

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.

SENTINEL-CONTROLED REPETITION

Sentinel Value:

also called as dummy value, signal value or flag value

SENTINEL-CONTROLED REPETITION

SENTINEL-CONTROLED REPETITION

SENTINEL-CONTROLED REPETITION

SENTINEL-CONTROLED REPETITION

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

should explicitly remind the user of the sentinel value.

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.”

NESTED CONTROL STRUCTURES

NESTED CONTROL STRUCTURES

NESTED CONTROL STRUCTURES

Sample Run 1:

NESTED CONTROL STRUCTURES

Sample Run 2:

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.

for REPETITION STRUCTURE

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)?

for REPETITION STRUCTURE

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

for REPETITION STRUCTURE

for REPETITION STRUCTURE

Compound Interest

for REPETITION STRUCTURE

while VERSUS for REPETITION

STRUCTURED PROGRAMMING SUMMARY

break AND continue STATEMENTS

programmer could also alter the flow of a loop

using the break and continue statements

break STATEMENT

breaks or causes immediate exit from while or for structure

break STATEMENT

break STATEMENT

continue STATEMENT

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

and proceeds with the next iteration of the loop

continue STATEMENT

causes immediate exit from while or for structure

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.

LOGICAL OPERATORS

Relational Operators:

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

Logical Operators:

and, or, not

LOGICAL and OPERATOR

LOGICAL or OPERATOR

LOGICAL not OPERATOR

AUGMENTED ASSIGNMENT

Assignment Expressions could be abbreviated.

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.

AUGMENTED ASSIGNMENT

AUGMENTED ASSIGNMENT

PYTHON 2.2 KEYWORDS

special/reserved words used for control structures &

other Python features

they could not be used as variable names

PRACTICE EXERCISE 1

Write a program that reads a positive integer and

determines if it is a prime number or not.

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.)

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.

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.

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

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

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

To be able to control the flow is powerful!

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.