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

Python 03 Ly Reduced

Python code note

Uploaded by

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

Python 03 Ly Reduced

Python code note

Uploaded by

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

Programming Fundamentals with Python

Sri Lanka Technology Campus (SLTC)


2

Introduction

• Pre-programming
– Have a through understanding of the problem
– Have a carefully planned approach to the solution
• When writing the program
– Understand the types of building blocks available
– Use proven program-construction principles

© 2002 Prentice Hall. All rights reserved.


3

while Repetition Structure

• Repetition Structures
– Allow a program to repeat an action while a statement is true
• Using while Repetition
– The action is contained within the body of the loop
• Can be one or more than one action
– Condition should evaluate to false at some point
• Creates a infinite loop and program hangs

© 2002 Prentice Hall. All rights reserved.


4

while Repetition Structure

product = 2

true
Product <= 1000 Product = 2 * product

false

© 2002 Prentice Hall. All rights reserved.


5

Counter Controlled Repetition

• Counter controlled repetition


– Called definite repetition
• The number of loops is known before the loop starts
– Uses a counter to limit the number of times a loop repeats
– Counter must be incremented or decremented in the loop

© 2002 Prentice Hall. All rights reserved.


6

Essentials of Counter-Controlled Repetition

• Essentials
– The counter
• A named variable to control the loop
– Initial value
• That which the counter starts at
– Increment
• Modifying the counter to make the loop eventually terminate
– Condition
• The test that the counter must pass in order to continue looping

© 2002 Prentice Hall. All rights reserved.


7
1 # Fig. 3.17: fig03_17.py Outline
2 # Counter-controlled repetition.
3 The counter with an
4 counter = 0 initial value of zero Fig03_17.py
5
The conditional that if the counter
6 while counter < 10:
is above 10 the loop breaks
7 print(counter)
8 Counter = Counter + 1 The incrementing
of the counter

Program Output
0
1
2
3
4
5
6
7
8
9

© 2002 Prentice Hall.


All rights reserved.
8

Counter Controlled Repetition

• Example: A class of 10 students took a quiz.


The grades (integers in the range 0 to 100) for this
quiz are available to you. Determine the class
average on the quiz.

© 2002 Prentice Hall. All rights reserved.


9

Counter Controlled Repetition

Pseudocode algorithm that uses counter-controlled repetition to


solve the class-average problem.

Set total to zero


Set grade counter to one

While grade counter is less than or equal to ten


Input the next grade
Add the grade into the total
Add one to the grade counter

Set the class average to the total divided by ten


Print the class average

© 2002 Prentice Hall. All rights reserved.


10
1 # Fig. 3.10: fig03_10.py
2 # Class average program with counter-controlled repetition.
Outline
3
4 # initialization phase
5 total = 0 # sum of grades Fig03_10.py
6 gradeCounter = 1 # number of grades entered
7
8 # processing phase
9 while gradeCounter <= 10: # loop 10 times
10 grade = input( "Enter grade: " ) # get one grade
11 grade = int( grade ) # convert string to an integer
12 total = total + grade
13 gradeCounter = gradeCounter + 1
14
15 # termination phase
16 average = total / 10 # integer division
17 print ("Class average is", average)

Enter grade: 98 int(x) - x converted to integer


Program Output
Enter grade: 76
long(x) - x converted to long integer
Enter grade: 71
Enter grade: 87 float(x) - x converted to floating point
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81 © 2002 Prentice Hall.
All rights reserved.
11

Nested Control Structures


• Nesting
– Inserting one control structure into another
• A loop inside of a loop
• E.g: An if statement inside of a loop

• Exercise:
• A class has a list of test results (1 = pass, 2 = fail) for
10 students. Write a program that analyzes the results
and display “Good class!”, if more than 8 students
have passed. Display the number of passes and failures.
• Note: You will receive the results (1 = pass, 2 = fail)
during run time

© 2002 Prentice Hall. All rights reserved.


12

Nested Control Structures


Initialize passes to zero
Initialize failures to zero
Initialize student counter to one

While student counter is less than or equal to ten


Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter

Print the number of passes


Print the number of failures

If more than eight students passed


Print “Good Class”
© 2002 Prentice Hall. All rights reserved.
13
1 # Fig. 3.15: fig03_15.py Outline
2 # Analysis of examination results.
3
4 # initialize variables Fig03_15.py
5 passes = 0 # number of passes
6 failures = 0 # number of failures
7 studentCounter = 1 # student counter
8
9 # process 10 students; counter-controlled loop
10 while studentCounter <= 10:
11 result = input( "Enter result (1=pass,2=fail): " )
12 result = int(result) # one exam result
13
14 if result == 1:
15 passes = passes + 1
16 else:
17 failures = failures + 1
18
19 studentCounter = studentCounter + 1
20
21 # termination phase
22 print ("Passed", passes)
23 print ("Failed", failures)
24
25 if passes > 8:
26 print(“Good Class“) © 2002 Prentice Hall.
All rights reserved.
14
Enter result (1=pass,2=fail): 1 Outline
Enter result (1=pass,2=fail): 1
Fig03_15.py
Enter result (1=pass,2=fail): 1 Program Output
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 2
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Passed 9
Failed 1
Good Class

© 2002 Prentice Hall.


All rights reserved.
15
Enter result (1=pass,2=fail): 1 Outline
Enter result (1=pass,2=fail): 2
Fig03_15.py
Enter result (1=pass,2=fail): 2 Program Output
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 2
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 2
Passed 6
Failed 4

© 2002 Prentice Hall.


All rights reserved.
16

Augmented Assignment Symbols

• Augmented addition assignment symbols


– x = x +5 is the same as x += 5
– y = y + 1 is the same as y += 1 and y++

• Other math signs


– The same rule applies to any other mathematical symbol
• *, **, /, %

© 2002 Prentice Hall. All rights reserved.


17

Augmented Assignment Symbols

Assignment Sample Explanation Assigns


symbol expression
Assume: c = 3,
d = 5, e = 4,
f = 2, g = 6,
h = 12
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
**= f **= 3 f = f ** 3 8 to f
/= g /= 3 g = g / 3 2 to g
%= h %= 9 h = h % 9 3 to h

© 2002 Prentice Hall. All rights reserved.


18

for Repetition Structure

• The for loop


– Function range is used to create a list of values
– range ( integer )
• Values go from 0 to given integer
– 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

– The loop will execute as many times as the value passed


– for counter in range (value)

© 2002 Prentice Hall. All rights reserved.


19
Outline
1 # Fig. 3.18: fig03_18.py
2 # Counter-controlled repetition with the Fig03_18.py
3 # for structure and range function.
4
5 for counter in range( 10 ): Makes the counter go from zero to nine
6 print counter

Program Output
0
1
2
3
4
5
6
7
8
9

© 2002 Prentice Hall.


All rights reserved.
20
Outline

© 2002 Prentice Hall.


All rights reserved.
21
Outline

© 2002 Prentice Hall.


All rights reserved.
22

Using the for Repetition Structure

• Techniques
– If the third value passed is negative then the loop will count
backwards through the provided numbers

© 2002 Prentice Hall. All rights reserved.


23

Using the for Repetition Structure

Exercise: Write a program using for loop to sum all


the even integers from 2 to 100.

© 2002 Prentice Hall. All rights reserved.


24
1 # Fig. 3.22: fig03_22.py Outline
2 # Summation with for.
3 Fig03_22.py
4 sum = 0
5 Loops from 2 to 101
6 for number in range( 2, 101, 2 ): in increments of 2
7 sum = sum + number
8
9 print("Sum is", sum )

A sum of all the even


numbers from 2 to 100

Program Output

Sum is 2550

© 2002 Prentice Hall.


All rights reserved.
25

Using the for Repetition Structure

• Write a program to find the sum of odd and even


numbers from 1 to N. N is given by the user.

© 2002 Prentice Hall. All rights reserved.


26

Using the for Repetition Structure

© 2002 Prentice Hall. All rights reserved.


27

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 are not executed
• But the loop will continue to run

© 2002 Prentice Hall. All rights reserved.


28
1 # Fig. 3.24: fig03_24.py Outline
2 # Using the break statement in a for
structure.
Fig03_24.py
3
4 for x in range( 1, 11 ):
5
6 if x == 5: When x equals 5 the loop breaks.
7 break Only up to 4 will be displayed
8
9 print x,
10
11 print "\nBroke out of loop at x =", x

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

© 2002 Prentice Hall.


All rights reserved.
29
1 # Fig. 3.26: fig03_26.py Outline
2 # Using the continue statement in a for/in structure.
3
Fig03_26.py
4 for x in range( 1, 11 ):
5 The loop will continue
6 if x == 5: if the value equals 5
7 continue
8
The value 5 will never be
9 print x, output but all the others will
10 Program Output
11 print ("\nUsed continue to skip printing the value 5“)

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

© 2002 Prentice Hall.


All rights reserved.

You might also like