1 structured programming 3 types of control structure – sequential structure built into python –...

24
1 Structured programming 3 types of control structure Sequential structure • Built into Python Selection structure • The if statement • The if/else statement • The if/elif/else statement Repetition structure • The while repetition structure • The for repetition structure All have one entry point and one exit point

Post on 20-Dec-2015

259 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

1

Structured programming

• 3 types of control structure – Sequential structure

• Built into Python

– Selection structure• The if statement• The if/else statement• The if/elif/else statement

– Repetition structure• The while repetition structure• The for repetition structure

• All have one entry point and one exit point

Page 2: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2

Sequence Control Structure

Fig. 3.1 Sequence structure flowchart with pseudo code.

add grade to total

add 1 to counter

total = total + grade;

counter = counter + 1;

Page 3: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

3

if Selection Structure

Fig. 3.3 if single-selection structure flowchart.

print “Passed”Grade >= 60true

false

Page 4: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

4

if/else Structure

Fig. 3.4 if/else double-selection structure flowchart.

Grade >= 60

print “Passed”print “Failed”

false true

Page 5: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

5

if/elif/else Selection Structure

condition atrue

false

.

.

.

false

false

condition z

default action(s)

true

true

condition b

case a action(s)

case b action(s)

case z action(s)

if statement

first elif statement

last elif statement

else statement

Fig. 3.5 if/elif/else multiple-selection structure.

Page 6: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

6

while Repetition Structure

• Repetition Structures– Allow a program to repeat an action while a condition is

true

• Using while Repetition– Action(s) contained within the body of the loop– Condition should evaluate to false at some point

• Otherwise infinite loop and program hangs

Page 7: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

7

while Repetition Structure

true

false

Product = 2 * productProduct <= 1000

Fig. 3.8 while repetition structure flowchart.

Page 8: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

8

Greatest common divisor algorithm

1. Get two integers a, b > 0 from the user

2. If a and b are the same, GCD = a, exit

3. Otherwise, repeat:– If a > b: Replace a with a % b. If a is now 0, GCD = b,

exit.– Case b > a analogous

Page 9: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

9gcd.

py

Note

• % operator for table

•if/else

• indentation: dangling else

Page 10: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

10

Running the program

Input first integer > 0: 81

Input second integer > 0: 45

a b

81 45

36 45

36 9

The greatest common divisor of 81 and 45 is 9

Page 11: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

11

for Repetition Structure

• The for loop– Function range is used to create a list of values

– range ( integer )• Values go from 0 up to given integer (i.e., not

including) – range ( integer, integer )

• Values go from first up to second integer– range ( integer, integer, integer )

• Values go from first up to second integer but increases in intervals of the third integer

– This loop will execute howmany times:

for counter in range ( howmany ):

and counter will have values

0, 1,.. howmany-1

Page 12: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig03_18.py

Program Output

1 # Fig. 3.18: fig03_18.py2 # Counter-controlled repetition with the3 # for structure and range function.4 5 for counter in range( 10 ):6 print counter

0123456789

Makes the counter go from zero to nine

Page 13: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

13

range function

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> range( 10 )[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> range( 10, 0, -1 )[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Fig. 3.20 Function range with a third value.

Fig. 3.19 Function range.

Page 14: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig03_22.py

Program Output

1 # Fig. 3.22: fig03_22.py2 # Summation with for.3 4 sum = 05 6 for number in range( 2, 101, 2 ):7 sum += number8 9 print "Sum is", sum

Sum is 2550

Loops from 2 to 101 in increments of 2

A sum of all the even numbers from 2 to 100

Another example

Page 15: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall. All rights reserved.

15

3.15 break and continue Statements

• The break statement– Used to make a loop stop looping

– The loop is exited and no more loop code is executed

• The continue statement– Used to continue the looping process

– All following actions in the loop body are not executed• But the loop will continue to run

Page 16: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig03_24.py

Program Output

1 # Fig. 3.24: fig03_24.py2 # Using the break statement in a for structure.3 4 for x in range( 1, 11 ):5 6 if x == 5:7 break8 9 print x,10 11 print "\nBroke out of loop at x =", x

1 2 3 4Broke out of loop at x = 5

Shows that the counter does not get to 10 like it normally would have

When x equals 5 the loop breaks. Only up to 4 will be displayed

The loop will go from 1 to 10

Page 17: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig03_26.py

Program Output

1 # Fig. 3.26: fig03_26.py2 # Using the continue statement in a for/in structure.3 4 for x in range( 1, 11 ):5 6 if x == 5:7 continue8 9 print x,10 11 print "\nUsed continue to skip printing the value 5"

1 2 3 4 6 7 8 9 10Used continue to skip printing the value 5

The value 5 will never be output but all the others will

The loop will continue if the value equals 5

continue skips rest of body but continues loop

Page 18: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall. All rights reserved.

18

Functions

• Purpose– Building blocks for the program (separate functionality

in independant parts)

– Avoid code repetition

• Calling/invoking a function– functionName ( argument1, argument2 )

• Details– Variables created in a function are local to that function

– Arguments are also local variables

– A function may return a result using the return statement

Page 19: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall. All rights reserved.

19

Modules

• A module contains useful function definitions and other elements– All of which are related in some way

• The import keyword is used to include a module

• A function from a module is invoked like this:

moduleName.functionName( arguments )

Page 20: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall. All rights reserved.

20

Functions in math Module

2.3 (#1, Aug 4 2003, 10:37:16)

[GCC 3.1.1] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>>

>>> print sqrt( 900 )

Traceback (most recent call last):

File "<stdin>", line 1, in ?

NameError: name 'sqrt' is not defined

>>>

>>> import math

>>>

>>> print math.sqrt( 900 )

30.0

>>>

>>>

Fig. 4.2 Function sqrt of module math.

Page 21: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall. All rights reserved.

21

User-defined functions

Functions must be defined before they are used:

def functionName ( paramList ):

• paramList is a comma separated list of parameters• The actions of the function then follow

– They should all be indented appropriately– The actions are also called the block or the function

body

Page 22: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig04_04.py

Program Output

1 # Fig. 4.4: fig04_04.py2 # Creating and using a programmer-defined function.3 4 # function definition5 def square( y ):6 return y * y7 8 for x in range( 1, 11 ):9 print square( x ),10 11 print

 1 4 9 16 25 36 49 64 81 100

This is a function definition, the function is called square and is passed the value y

The function returns the passed value multiplied by itself

This calls the square function and passes it the value x

Page 23: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig04_05.py

1 # Fig. 4.5: fig04_05.py2 # Finding the maximum of three integers.3 4 def maximumValue( x, y, z ):5 maximum = x6 7 if y > maximum:8 maximum = y9 10 if z > maximum:11 maximum = z12 13 return maximum14 15 a = int( raw_input( "Enter first integer: " ) )16 b = int( raw_input( "Enter second integer: " ) )17 c = int( raw_input( "Enter third integer: " ) )18 19 # function call20 print "Maximum integer is:", maximumValue( a, b, c ) 21 print # print new line22 23 d = float( raw_input( "Enter first float: " ) )24 e = float( raw_input( "Enter second float: " ) )25 f = float( raw_input( "Enter third float: " ) )26 print "Maximum float is: ", maximumValue( d, e, f )27 print28 29 g = raw_input( "Enter first string: " )30 h = raw_input( "Enter second string: " )31 i = raw_input( "Enter third string: " )32 print "Maximum string is: ", maximumValue( g, h, i )

This is a function that receives three values

The function determines the greater of three values and returns it

Gets three integers, passes them to the maximumValue function, and displays the results to the user

The same process is performed on float and string variables to show the diversity of the function

Note: only possible because of dynamic typing! Function parameters not type declared

Page 24: 1 Structured programming 3 types of control structure – Sequential structure Built into Python – Selection structure The if statement The if/else statement

2002 Prentice Hall.All rights reserved.

Fig04_05.pyProgram Output

 Enter first integer: 27Enter second integer: 12Enter third integer: 36Maximum integer is: 36 Enter first float: 12.3Enter second float: 45.6Enter third float: 9.03Maximum float is: 45.6 Enter first string: helloEnter second string: programmingEnter third string: goodbyeMaximum string is: programming