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

07 - Introduction To Python - Looping

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

07 - Introduction To Python - Looping

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

Introduction to Python

Programming

Part 7: Looping
How to use this resource
Skill Explanations: Pink Slides
• Within each unit, you will learn how to develop
and apply a range of Python programming skills.
Skill explanations are in pink.
Tasks: Rookie Pro Beast
• After reading the explanation of a skill, apply it
within the given tasks. The tasks are categorised
into Rookie (Easy), Pro (Medium) or Beast (Hard).
Challenges: Rookie Pro Beast
• Once you have learned how to apply your new
skills, demonstrate your ability by completing the
given challenges. Don’t forget the debugging task!
• Once complete, review your performance!
Learning Objectives
Rookie
• To be able to write a simple While loop.
• To be able to write a simple For loop.
Pro
• To use both While and For loops to make coding more efficient.
Beast
• To use loops to check for and compare information.
Skill Contents
Once you complete a skill, colour code
Contents Confidence
the box to show your level of Level
confidence. You can always revisit the While loops
skill later on to boost your confidence.
For loops
Key Colour For loops: add a starting number
Code
For loops: increment the number
I am very good at this skill by more than 1
and could show a friend
how to do it. For loops: comparing data
I am confident I can
perform this skill on my
own.

I need to improve my
understanding of this skill.
What is Looping (Iteration)?
Why write all this code:

Walk forward one step


Walk forward one step
Walk forward one step
When you could simply write this:
Walk forward one step
Walk forward one step
Repeat 10 times: Walk forward one step
Walk forward one step
Walk forward one step
Walk forward one step
Walk forward one step
Walk forward one step

• In programming, Looping, or Iteration, means repeating a set of instructions a


certain number of times.
• This allows us to create efficient coding structures, which also saves us time!
• Within this unit of work we will learn how to write two different types of loops:
For Loops and While Loops.
Here are some sporting while loop examples!
Skill 1: While Loops
The first type of loop we will look at is a While
Loop.
START
A While Loop is used to repeat an action or WHILE pedalling = TRUE:
sequence of events while a condition is met. Riding a
bike ride bike
The structure of the while loop in pseudo END WHILE
code and flowchart is as follows: END

Start
WHILE the condition is TRUE:
Perform the task(s)
End START
tired = FALSE
Note how the task to Do WHILE tired = FALSE:
press- perform a press-up
be performed WHILE ups tired = user INPUT( )
the condition is TRUE END WHILE
is indented below the END
while code.
Skill 1: Writing while Loops in Python
In Python, a While loop is structured as follows:

Declare any required variables.

Write the condition.

The indented code


will repeat until the
while condition
becomes FALSE.

Declare any required variables.


While loops can also
Write the condition.
be used to run code
within a numeric
range. You will learn The indented code
will repeat until the
how to do this within while condition
the following tasks. becomes FALSE.
Task 1: Rookie
1. Create a variable called quit. Assign it the value n.
2. Using a WHILE loop, while the value of quit is n, ask the user if they want to quit. If a value other than n
is input, the while loop and programme ends.

Flowchart Pseudo code

START
quit = n
WHILE quit = n:
OUTPUT: Do you want to quit (y/n)?
quit = user INPUT( )
END WHILE
END
Task 1: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 2: Rookie
1. Create a variable called number and assign it the value 1.
2. Using a WHILE loop, print out the numbers 1 to 10 by incrementing the value of the variable number.

Flowchart Pseudo code

START
number = 1
WHILE number < 11:
OUTPUT: number
number = number + 1
END WHILE
END
Task 2: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 3: Pro
1. Create a variable called password. Assign it the password ilovepython.
2. Allow the user to input a password. Use a WHILE loop so that the user is allowed to retype the password until they get
it correct.
3. When the correct password is input, an appropriate success message is displayed and the programme ends.

Flowchart Pseudo code

START
password = ilovepython
WHILE guess ≠ password:
OUTPUT: Please enter the password.
guess = INPUT ( )
IF guess ≠ password:
OUTPUT: Access denied!
ELSE:
END IF
END WHILE
OUTPUT: Password accepted. Welcome back user!
END
Task 3: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 4: Pro
1. Create a variable called number and store a number between 1 and 10 in it.
2. Using a While loop, ask the user to guess your number until they get it right.
3. Make sure you output suitable messages to let the user know if they guessed correctly or not.
4. EXTENSION: Add an option for the user to quit guessing and end the programme.

Flowchart Pseudo code

START
number = [programmers choice]
guess = 0
WHILE guess ≠ number:
OUTPUT: Guess what number I am thinking of!
guess = INPUT ( )
IF guess = number:
OUTPUT: Correct!
ELSE:
OUTPUT: Wrong! Guess again!
END IF
END WHILE
END
Task 4: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 5: Beast
1. Create a variable called number and assign it the value 1.
2. Using a FOR loop, print out the numbers 1 to 10 by incrementing the value of the variable number.

Flowchart Pseudo code

START
OUTPUT: The incredible times table algorithm!
OUTPUT: Enter a number
number = user INPUT( )
i=1
WHILE i < 13
Sum = number x i
OUTPUT: Sum
i=i+1
END WHILE
END
Task 5: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 6: Beast
Extend the guess the number algorithm by adding in an option for the user to quit guessing and end the programme.

Flowchart Pseudo code

START
number = [programmers choice]
QUIT = n
guess = 0
WHILE QUIT = n:
IF guess ≠ number:
OUTPUT: Guess what number I am thinking of!
guess = INPUT ( )
IF guess = number:
OUTPUT: Correct!
ELSE:
OUTPUT: Wrong! Do you want to quit(y/n)?
QUIT = INPUT ( )
END IF
ELSE:
END IF
END WHILE
END
Task 6: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Here is a sporting for loop example!
Skill 2: For Loops
The next type of loop we
will look at is a For Loop.
A For Loop is used to
repeat a set of
instructions a specific
number of times. START
Perform 20 FOR i  1 TO 20:
press-ups Perform a press-up
END FOR
END

Start Difference between FOR and WHILE loops


Repeat for i number of times:
Perform the task(s) FOR loop: Runs for a specific number of times.
End WHILE loop: Runs until a condition becomes FALSE.
Skill 2: Writing FOR Loops in Python The number within the
bracketed range function (6)
refers to the maximum
In Python, a FOR loop is structured as follows: number i can be before the
for loop ends i.e.
When using a for loop, the i ([up to but not including])
is a type of variable known
as a counter. This states By printing i, we can see
how many times to repeat that the initial value of i is
the code for. 0 and the final number to
be printed is 5.

This bracketed number can also be


replaced with a variable as shown below:

In total, a for loop range can take three integer arguments as follows:

([starting number], [up to but not including], [steps])


We will look at how these are used within the following tasks.
Task 7: Rookie
1. Use a for loop to print out “Hello World!” 10 times.
2. Extension: Can you make it repeat 20 times?

Flowchart Pseudo code

START
FOR i  1 TO 10:
OUTPUT: Hello World!
END FOR
END
Task 7: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 8: Pro
1. Ask a user how many numbers they want to add to a list.
2. Use a for loop and the append function to allow a user to enter their chosen number of numbers.
3. Output the finished list.

Flowchart Pseudo code Python

START
number = user INPUT( )
numbers = [ ]
FOR i  1 TO number
numbers = user INPUT
END FOR
OUTPUT: numbers
END
Task 8: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Task 9: Beast
1. Using a for loop, allow a user to input 10 different scores of their choice into an array.
2. Once all the scores have been input, OUTPUT the array.
3. Extension: Ask the user how many scores they wish to enter.

Flowchart Pseudo code Python

START
score = [ ]
FOR i  1 TO 10
score = user INPUT( )
END FOR
OUTPUT: score
END
Task 9: Beast
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Skill 3: Adding a starting number within a FOR loop
A FOR loop automatically starts at 0 unless otherwise stated within the range arguments.
([starting number], [up to but not including])
The range function allows you to In the code, (1,11) means i will start with the value 1 and
state how many times you wish the code will continue to repeat until i becomes 11.
the code to be repeated by Therefore, in this example, the code will repeat 10 times.
assigning values to the counter
variable i.

As such, this example code will generate the following output:


Task 10: Pro
1. Using a for loop, set the starting count to 2, then output For loops are easy! 10 times.
2. Extension: Can you make it repeat 20 times with a starting count of 10?

Flowchart Pseudo code

START
FOR i  2 TO 12:
OUTPUT: For loops are easy!
END FOR
END
Task 10: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Skill 4: Incrementing the counter by more than 1
A FOR loop counter automatically increments by 1 step unless otherwise stated.

([starting number], [up to but not including], [steps])

In the code, (2,11,2) means i will start with the value


2 and increment each step by the value of 2. The code
will continue to repeat while i is less than 11.

In this example, the output shows how i increments


by two until it reaches the end of the loop range (11).
Task 11: Pro
1. Using a for loop, set the starting count to 2, the range to 25 and the step increment to 2 each step to
produce an algorithm to output the 2 times table!
2. Extension: Can you create an algorithm to output the 10 times table?

Flowchart Pseudo code

START
FOR i  2 TO 25:
OUTPUT: i
i=i+2
END FOR
END
Task 11: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Skill 5: Using for loops to compare data
• A for loop can be used to check for specific information within a variable or a list.
• To do this, you will need to understand the following functions:

Technique Explanation Example

Rather than use the range function, this will check


For i in variable: each index within a given variable or list [i].

Conducts a check to see if a variable stores uppercase


.isupper
string

Conducts a check to see if a variable stores lowercase


.islower
string

Conducts a check to see if a variable stores any


.isnumeric numbers
Reminder: Understanding Array/List structures
• Information stored within data structures such as arrays and variables are given an index
value as shown below:
Index 0 1 2 3 4 5 6 7 8 9 10
welcome  H E L L O W O R L D

• Remember: In Python, the first element of a data structure has an index of zero.
• In the example above, the length of the string is 11 characters (note the space is also a
character), however the index range is 0 to 10.
• This means index 0 stores the character H while index 10 stores the character D.
• If we use a FOR loop to check through each index, we need to adjust the FOR loop ranges
as follows:
FOR i  0 TO LEN(list)-1 Final value will be 1
less than the length
First count value will be 0. of the array / string.
Task 12: Beast
1. Ask the user to enter a password. Store it in a variable.
2. Use a for loop and check that it has at least 2 uppercase letters within it.
3. If it does, let the user know their password was accepted, if not, let them know their password was denied.

Flowchart Pseudo code


START
password = user INPUT( )
upper = 0
FOR i  0 TO LEN(password)-1
IF password [ i ] is uppercase:
upper = upper + 1
ELSE:
END IF
END FOR
IF upper > 1:
OUTPUT: Password accepted
ELSE:
OUTPUT: Password denied
END IF
END
Task 12: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Skill 6: Compare information in a variable to a list
• A for loop can be used to compare information against a variable or a list.
• To do this, you will need to understand the following functions:

Technique Explanation Example

LIST = [1,2,3] Declare your list and Assign a variable. For example,
either enter the data yourself or allow a user to enter a
it.
For i in variable Use the range function to repeat the check for as long
length: as the length of the checked word.

Identifying a This is used to check the value of an indexed location


variable index against any value in a list.
Task 13: Beast
1. Create a list and store the following letters within it: A E I O U
2. Ask the user to enter their name. Compare the user name and output the number of vowels within their name in a
suitable string sentence.

Flowchart Pseudo code

START
list = [ A, E, I, O, U ]
name = user INPUT( )
vowels = 0
FOR i  0 TO LEN(name)-1:
IF name[ i ] is in list:
vowels = vowels + 1
ELSE:
END IF
END FOR
OUTPUT: Hello + name + you have + vowels + vowels in your name!
END
Task 13: Solution
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Programming Challenges
• Now you have learned some programming skills, it’s time to
put them into practice!
• Complete the following programming challenges. Start with
the Rookie challenge and see how far you can push yourself.
• Finally, complete the debugging challenge.
• Once you have finished your challenges, complete the
review. Look back at the skills you have learned so far to help
you solve the challenge.
Add a print screen of
your solutions to the
Programming Challenge: Rookie next slide.

Using a loop, output a string phrase


of your choice 20 times.

1 Mark
Programming Challenge: Rookie - Answer
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Add a print screen of
your solutions to the
Programming Challenge: Pro next slide.

1. Create a programme which asks the user to answer the question


‘what is 10 + 10?’
2. If the user gets the question wrong, they are asked to try again.
3. If the user gets the question right, the programme outputs a
suitable response and ends.

1 Mark
Programming Challenge: Pro - Answer
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Add a print screen of
your solutions to the
Programming Challenge: Beast next slide.

1. Create a variable which stores the name of your favourite sporting hero.
2. Ask the user to guess your sporting hero.
3. If the user guesses the correct name, congratulate them and end the programme. If they
guess incorrectly, allow them to have another go if they wish.
4. If they guess incorrectly, give them a clue; let the user know how many letters in their guess
were the same as in your answer.
5. Give them another clue: let the user know the first letter of your sporting hero’s name, the
next guess tell them the first and second, etc.
6. Make sure your coding is robust.

1 Mark
Programming Challenge: Beast - Answer
• Add a print screen to show • Add a print screen to show
your coding here. your output solution here.
Debugging Question
Which piece of code below would output the phrase below 10 times;

Looping is easy!

1 Mark
Complete the table below to help you identify what
Challenges Review areas you are confident at and which areas you need
to improve further:
Challenge Your Score (Max 1 mark each)
Rookie Challenge
Pro Challenge
Beast Challenge
Debugging Challenge

Unit Review
What Went Well:

Even Better If:

You might also like