SlideShare a Scribd company logo
1 of 19
Introduction to Programming
Python Lab 8:
Loops
19 November 2019
or 6 March 2020
1
PythonLab8 lecture slides.ppt
Ping Brennan (p.brennan@bbk.ac.uk)
Getting Started
• Create a new folder in your disk space with the name PythonLab8
• Launch the Python Integrated Development Environment (IDLE) -
begin with the Start icon in the lower left corner of the screen.
• If you are in a DCSIS laboratory, search using the keyword Python
and click on IDLE (Python 3.6 64-bit) .
A window with the title Python 3.6.2 Shell should appear. This
window is the Shell.
2
Getting Started (2)
• If you are in the ITS laboratory MAL 109, then right mouse click on
the Start icon in the lower left corner of the screen.
A list of menu options should appear and click on Search. Type
Python in the search text box at the bottom of the pop-up
window. A list of Apps should appear and select
Python 3.4 IDLE(PythonGUI)
A window with the title Python 3.4.3 Shell should appear. This
window is the Shell.
• In the Shell click on File. A drop down menu will appear.
Click on New File. A window with the `title` Untitled should
appear. This window is the Editor.
3
Getting Started (3)
• In the Editor, click on File, and then in the drop down menu click
on Save As… .
A window showing a list of folders should appear.
– To search any folder on the list, double click on the folder.
– Find the folder PythonLab8 and double click on it.
– In the box File name at the bottom of the window
1. Type Vowels.py
2. Then click on the button Save in the lower right corner of the
window.
The title of the Editor should change to show the location of the file
Vowels.py.
4
Objectives of the exercises set
• Objectives
– Use for statements to implement count-controlled loops that
iterate over a range of integer values or the contents of any
container.
5
Syntax Example Explanation
for variable in container:
statements #loop body
stateName = "Ohio"
for letter in stateName:
print(letter)
# loop body
The string "Ohio" is
stored in the variable
stateName.
The loop body is
executed for each
successive character of
the string in
stateName, starting
with the first character.
The header
ends in a
colon
All the statements in
the block (loop body)
have the same level
of indentation.
The variable letter takes
each of the values 'O', 'h', 'i',
'o' in turn for each iteration.
iteration letter Output
1 O O
h
i
o
2 h
3 i
4 o
• Objectives
– Use while statements to implement event-controlled
loops.
A while loop executes instructions repeatedly while a
condition is true.
Objectives of the exercises set (2)
6
1
2
3
4
The header
ends in a
colon.
1
2
3
4
In the example, the variable i is initialised outside the while loop (statement )
and updated in the loop body (statement ).
1
4
All the statements
in the block (loop
body) have the
same indentation.
condition
Syntax Example Flow chart
while condition :
statements
i = 0
while i < 3 :
print(i)
i = i + 1
Output
0
1
2
Objectives of the exercises set (3)
– The table below shows the working of the while loop
example shown on page 6.
7
i i < 3 ? Output using
print(i)
i = i + 1
0 True 0 1
1 True 1 2
2 True 2 3
3 False – end of the while loop
Program Vowels.py: Vowels
• Question 2: Problem statement
Consider the following for loop,
stateName = "Ohio"
for letter in stateName :
print(letter)
The variable letter takes each of the values "O", "h", "i", "o"
in turn.
The output of the code is
O
h
i
o
8
Program Vowels.py: Vowels (2)
• Problem statement (continued)
i. Write a program that requests a string from the keyboard and
then prints out the characters in the string in a vertical line, as
in the above example. (see page 8)
ii. Add to your program code to count the number of lower case
vowels in the input string and then print out this number after
printing out the vertical line of characters. The vowels are a, e,
i, o, u.
9
Program Vowels.py: Vowels (3)
• Problem solving - Convert the following pseudo code into a
sequence of Python statements in your program.
1. Read in a string and store it in a variable named s.
2. Declare a variable named n and assign a value of 0 to it.
The variable n is used to keep a count of the number of lower case
vowels (a, e, i, o, u) in the input string s.
3. Add the following for statement to print out the characters in the
string s in a vertical line, as shown in the output example on page 8.
for letter in s :
print(letter) # loop body
10
Indent the
print statement
in the block
(loop body).
Input
Process
the input
and
display
the
output
(steps 2
to 5).
Program Vowels.py: Vowels (4)
• Problem solving (continued)
4. Inside the for loop, add an if statement to check if the letter is equal
to an "a", "e", "i", "o", or "u" after the print statement in step 3. Align
the print and if statements at the same level of indentation.
If the combined Boolean expression is true, then add 1 to the current
value of n. Use the if statement below to help you get started.
if letter == "a" or letter == "e" or complete the combined
Boolean expression by adding test conditions for the
remaining vowels (i,o,u) :
# True branch - if the combined expression is true
Indent & write an assignment statement to add 1 to n
and store the result in n. Recall n keeps a count of
the number of lower case vowels.
5. Outside the for loop, write the code to print out the number of lower
case vowels. Align the print and for statements.
• Provide a comment at the beginning of the program to explain
the purpose of the program together with your name and the
date. Save the program to the file Vowels.py and then run it. 11
Note the
indentation
of the code.
Program NumberProperties.py:
NumberProperties
• Create a new Editor for a new file called NumberProperties.py
• Question 3: Problem statement
Write a program that reads a list of strictly positive integers from the
keyboard, one at a time.
Use a while loop to read these integers.
The end of the input is indicated by the integer 0. Note that this 0 is a
sentinel in that it marks the end of the input but does not belong to
the set of integers whose properties are sought (PFE Section 4.3).
The program then prints out the following numbers.
i. the average value
ii. the smallest of the values
iii. the largest of the values
iv. the inclusive range, that is one more than the difference between the
smallest and the largest values.
It can be assumed that the input contains at least one number other
than 0. See PFE P4.5.
12
Program NumberProperties.py:
NumberProperties (2)
• Problem statement (continued)
Include a comment with each number that is printed out, for
example:
The average value is: …
If you need to check how a while loop behaves, then test the
following code.
nextNumber = 5
while not (nextNumber == 0) : # test for entry to the loop
print(nextNumber) # in the loop do something with the data
nextNumber = nextNumber-1 # get the next number
13
All the statements
in the block (loop
body) have the
same indentation.
Program NumberProperties.py:
NumberProperties (3)
14
Input
A set of positive
integer numbers.
For example,
the numbers:
2 5 3 9
are typed in at
the keyboard,
one at a time.
Computations
1. average =
(2 + 5 + 3 + 9) / 4
2. mn = min(2, 5, 3, 9)
3. mx = max(2, 5, 3, 9)
4. range = (mx - mn) + 1
Output
The average
value is 4.75
The smallest
value is 2
The largest value
is 9
The range is 8
Note: The Python built-in function max returns the largest value of the
arguments; and the function min returns the smallest value of the arguments.
Flow chart of a while
loop for the program
NumberProperties.py
(4)
15
The largest and
smallest of the
values are stored in
the variables mx and
mn respectively.
Program NumberProperties.py:
NumberProperties (5)
• Problem solving - Convert the following pseudo code into a
sequence of Python statements in your program.
1. Read in an integer and store it in a variable named number *
2. Create a variable named count and initialise it with the value of 1.
The variable keeps a count of the number of inputs.
3. Create variables, for example, total to store the total of the inputs,
mx to store the largest value and mn to store the smallest value.
Set the value of each variable to be the value of the variable number
initially.
An example is shown below for the variable total.
total = number
* Assume that the first numeric value read in from the keyboard is a
positive integer greater than 0.
16
Input
Process
the input
and
display all
required
results
(steps 2
to 5).
Program NumberProperties.py:
NumberProperties (6)
• Problem solving (continued)
4. Write a while loop statement to read in more integers as long as the
condition, number > 0, remains true. Below is an outline of the
algorithm needed to solve the problem set inside the loop.
while number > 0 :
# loop body
# Add code below to read in a number
number = read in an integer similar to step 1
# Add an if statement below to check if the number is not
# equal to zero.
if (condition tests if the number is not equal to zero) :
# True branch of the if statement
# i) add 1 to count as shown, indented below.
count = count + 1
# Write more code inside the True branch to
# ii) add number to total and store result in total
# iii) Set mx to be the larger of the two values in
# the variables mx and number using the max function.
# iv) Set mn to be the smaller of the two values in
# the variables mn and number using the min function. 17
Note the
indentation
of the
statements.
Program NumberProperties.py:
NumberProperties (7)
• Problem solving (continued)
5. Outside the while loop, write additional code to find the average value
and the inclusive range. Then write code to print all required results
separately together with suitable messages.
For example, the print statement below can be used to display the
inclusive range.
print("The range is ", mx – mn + 1)
Align the while statement and the additional code for step 5, such as
print statements.
• Provide a comment at the beginning of the program to explain
the purpose of the program together with your name and the
date.
• Save your program to the file NumberProperties.py and
then run it.
18
Supplementary Questions for Private
Study
• The laboratory worksheet contains supplementary questions in
section 4 for private study.
• You are encouraged to complete the supplementary questions at
home, or in the laboratory if you have time after completing
questions 2 to 3.
19

More Related Content

Similar to Looping in PythonLab8 lecture slides.pptx

Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptxNileshBorkar12
 
Lab6: I/O and Arrays
Lab6: I/O and ArraysLab6: I/O and Arrays
Lab6: I/O and Arraysenidcruz
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonmckennadglyn
 
Devry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsDevry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsjody zoll
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL Rishabh-Rawat
 
An overview on python commands for solving the problems
An overview on python commands for solving the problemsAn overview on python commands for solving the problems
An overview on python commands for solving the problemsRavikiran708913
 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfAbdulmalikAhmadLawan2
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience App Ttrainers .com
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
 
Hey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addiHey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addisorayan5ywschuit
 
Python Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptxPython Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptxMohammad300758
 

Similar to Looping in PythonLab8 lecture slides.pptx (20)

lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
Lab6: I/O and Arrays
Lab6: I/O and ArraysLab6: I/O and Arrays
Lab6: I/O and Arrays
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.pptx
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Devry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsDevry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and strings
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL
 
An overview on python commands for solving the problems
An overview on python commands for solving the problemsAn overview on python commands for solving the problems
An overview on python commands for solving the problems
 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Hey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addiHey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addi
 
Python Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptxPython Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptx
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Looping in PythonLab8 lecture slides.pptx

  • 1. Introduction to Programming Python Lab 8: Loops 19 November 2019 or 6 March 2020 1 PythonLab8 lecture slides.ppt Ping Brennan (p.brennan@bbk.ac.uk)
  • 2. Getting Started • Create a new folder in your disk space with the name PythonLab8 • Launch the Python Integrated Development Environment (IDLE) - begin with the Start icon in the lower left corner of the screen. • If you are in a DCSIS laboratory, search using the keyword Python and click on IDLE (Python 3.6 64-bit) . A window with the title Python 3.6.2 Shell should appear. This window is the Shell. 2
  • 3. Getting Started (2) • If you are in the ITS laboratory MAL 109, then right mouse click on the Start icon in the lower left corner of the screen. A list of menu options should appear and click on Search. Type Python in the search text box at the bottom of the pop-up window. A list of Apps should appear and select Python 3.4 IDLE(PythonGUI) A window with the title Python 3.4.3 Shell should appear. This window is the Shell. • In the Shell click on File. A drop down menu will appear. Click on New File. A window with the `title` Untitled should appear. This window is the Editor. 3
  • 4. Getting Started (3) • In the Editor, click on File, and then in the drop down menu click on Save As… . A window showing a list of folders should appear. – To search any folder on the list, double click on the folder. – Find the folder PythonLab8 and double click on it. – In the box File name at the bottom of the window 1. Type Vowels.py 2. Then click on the button Save in the lower right corner of the window. The title of the Editor should change to show the location of the file Vowels.py. 4
  • 5. Objectives of the exercises set • Objectives – Use for statements to implement count-controlled loops that iterate over a range of integer values or the contents of any container. 5 Syntax Example Explanation for variable in container: statements #loop body stateName = "Ohio" for letter in stateName: print(letter) # loop body The string "Ohio" is stored in the variable stateName. The loop body is executed for each successive character of the string in stateName, starting with the first character. The header ends in a colon All the statements in the block (loop body) have the same level of indentation. The variable letter takes each of the values 'O', 'h', 'i', 'o' in turn for each iteration. iteration letter Output 1 O O h i o 2 h 3 i 4 o
  • 6. • Objectives – Use while statements to implement event-controlled loops. A while loop executes instructions repeatedly while a condition is true. Objectives of the exercises set (2) 6 1 2 3 4 The header ends in a colon. 1 2 3 4 In the example, the variable i is initialised outside the while loop (statement ) and updated in the loop body (statement ). 1 4 All the statements in the block (loop body) have the same indentation. condition Syntax Example Flow chart while condition : statements i = 0 while i < 3 : print(i) i = i + 1 Output 0 1 2
  • 7. Objectives of the exercises set (3) – The table below shows the working of the while loop example shown on page 6. 7 i i < 3 ? Output using print(i) i = i + 1 0 True 0 1 1 True 1 2 2 True 2 3 3 False – end of the while loop
  • 8. Program Vowels.py: Vowels • Question 2: Problem statement Consider the following for loop, stateName = "Ohio" for letter in stateName : print(letter) The variable letter takes each of the values "O", "h", "i", "o" in turn. The output of the code is O h i o 8
  • 9. Program Vowels.py: Vowels (2) • Problem statement (continued) i. Write a program that requests a string from the keyboard and then prints out the characters in the string in a vertical line, as in the above example. (see page 8) ii. Add to your program code to count the number of lower case vowels in the input string and then print out this number after printing out the vertical line of characters. The vowels are a, e, i, o, u. 9
  • 10. Program Vowels.py: Vowels (3) • Problem solving - Convert the following pseudo code into a sequence of Python statements in your program. 1. Read in a string and store it in a variable named s. 2. Declare a variable named n and assign a value of 0 to it. The variable n is used to keep a count of the number of lower case vowels (a, e, i, o, u) in the input string s. 3. Add the following for statement to print out the characters in the string s in a vertical line, as shown in the output example on page 8. for letter in s : print(letter) # loop body 10 Indent the print statement in the block (loop body). Input Process the input and display the output (steps 2 to 5).
  • 11. Program Vowels.py: Vowels (4) • Problem solving (continued) 4. Inside the for loop, add an if statement to check if the letter is equal to an "a", "e", "i", "o", or "u" after the print statement in step 3. Align the print and if statements at the same level of indentation. If the combined Boolean expression is true, then add 1 to the current value of n. Use the if statement below to help you get started. if letter == "a" or letter == "e" or complete the combined Boolean expression by adding test conditions for the remaining vowels (i,o,u) : # True branch - if the combined expression is true Indent & write an assignment statement to add 1 to n and store the result in n. Recall n keeps a count of the number of lower case vowels. 5. Outside the for loop, write the code to print out the number of lower case vowels. Align the print and for statements. • Provide a comment at the beginning of the program to explain the purpose of the program together with your name and the date. Save the program to the file Vowels.py and then run it. 11 Note the indentation of the code.
  • 12. Program NumberProperties.py: NumberProperties • Create a new Editor for a new file called NumberProperties.py • Question 3: Problem statement Write a program that reads a list of strictly positive integers from the keyboard, one at a time. Use a while loop to read these integers. The end of the input is indicated by the integer 0. Note that this 0 is a sentinel in that it marks the end of the input but does not belong to the set of integers whose properties are sought (PFE Section 4.3). The program then prints out the following numbers. i. the average value ii. the smallest of the values iii. the largest of the values iv. the inclusive range, that is one more than the difference between the smallest and the largest values. It can be assumed that the input contains at least one number other than 0. See PFE P4.5. 12
  • 13. Program NumberProperties.py: NumberProperties (2) • Problem statement (continued) Include a comment with each number that is printed out, for example: The average value is: … If you need to check how a while loop behaves, then test the following code. nextNumber = 5 while not (nextNumber == 0) : # test for entry to the loop print(nextNumber) # in the loop do something with the data nextNumber = nextNumber-1 # get the next number 13 All the statements in the block (loop body) have the same indentation.
  • 14. Program NumberProperties.py: NumberProperties (3) 14 Input A set of positive integer numbers. For example, the numbers: 2 5 3 9 are typed in at the keyboard, one at a time. Computations 1. average = (2 + 5 + 3 + 9) / 4 2. mn = min(2, 5, 3, 9) 3. mx = max(2, 5, 3, 9) 4. range = (mx - mn) + 1 Output The average value is 4.75 The smallest value is 2 The largest value is 9 The range is 8 Note: The Python built-in function max returns the largest value of the arguments; and the function min returns the smallest value of the arguments.
  • 15. Flow chart of a while loop for the program NumberProperties.py (4) 15 The largest and smallest of the values are stored in the variables mx and mn respectively.
  • 16. Program NumberProperties.py: NumberProperties (5) • Problem solving - Convert the following pseudo code into a sequence of Python statements in your program. 1. Read in an integer and store it in a variable named number * 2. Create a variable named count and initialise it with the value of 1. The variable keeps a count of the number of inputs. 3. Create variables, for example, total to store the total of the inputs, mx to store the largest value and mn to store the smallest value. Set the value of each variable to be the value of the variable number initially. An example is shown below for the variable total. total = number * Assume that the first numeric value read in from the keyboard is a positive integer greater than 0. 16 Input Process the input and display all required results (steps 2 to 5).
  • 17. Program NumberProperties.py: NumberProperties (6) • Problem solving (continued) 4. Write a while loop statement to read in more integers as long as the condition, number > 0, remains true. Below is an outline of the algorithm needed to solve the problem set inside the loop. while number > 0 : # loop body # Add code below to read in a number number = read in an integer similar to step 1 # Add an if statement below to check if the number is not # equal to zero. if (condition tests if the number is not equal to zero) : # True branch of the if statement # i) add 1 to count as shown, indented below. count = count + 1 # Write more code inside the True branch to # ii) add number to total and store result in total # iii) Set mx to be the larger of the two values in # the variables mx and number using the max function. # iv) Set mn to be the smaller of the two values in # the variables mn and number using the min function. 17 Note the indentation of the statements.
  • 18. Program NumberProperties.py: NumberProperties (7) • Problem solving (continued) 5. Outside the while loop, write additional code to find the average value and the inclusive range. Then write code to print all required results separately together with suitable messages. For example, the print statement below can be used to display the inclusive range. print("The range is ", mx – mn + 1) Align the while statement and the additional code for step 5, such as print statements. • Provide a comment at the beginning of the program to explain the purpose of the program together with your name and the date. • Save your program to the file NumberProperties.py and then run it. 18
  • 19. Supplementary Questions for Private Study • The laboratory worksheet contains supplementary questions in section 4 for private study. • You are encouraged to complete the supplementary questions at home, or in the laboratory if you have time after completing questions 2 to 3. 19