Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
274 views

04 - Python - Repetition Control Structure

The document discusses repetition control structures in programming, specifically while and for loops. It provides examples of how to use while loops with conditional statements and variables to control repetition. It also describes the pass, continue, break, and else keywords used in loops. For loops are explained as iterating over sequences like lists, tuples, and strings, optionally using break, continue, and else. Key parts of loops like the header, body, and termination condition are defined.

Uploaded by

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

04 - Python - Repetition Control Structure

The document discusses repetition control structures in programming, specifically while and for loops. It provides examples of how to use while loops with conditional statements and variables to control repetition. It also describes the pass, continue, break, and else keywords used in loops. For loops are explained as iterating over sequences like lists, tuples, and strings, optionally using break, continue, and else. Key parts of loops like the header, body, and termination condition are defined.

Uploaded by

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

Repetition Control

Structure
CC2 – Introduction to Computer Programming
Repetition Control Structure
• Repetition control structures are also referred to as iterative
structures.
• These are groupings of code which are designed to repeat a set
of related statements.
• This repetition can repeat zero or more times, until some control
value or condition causes the repetition to cease.
Loops
• The most common term to describe repetition control structures
is a loop.
• Loops have two parts:
• Condition – The logic that evaluates a condition.
• Body – This is where the code integral to the loop is located.
Loops
• There are two common types of looping structures that can be
found in an application:
• Pre-test Loop – This type of loop can execute its body a minimum of
zero times, if the initial condition evaluates to False.
• Post-test Loop – This type of loop can execute its body a minimum of
one time even if the initial condition evaluates to False.
Loops
• Pre-test Loop • Post-test Loop
WHILE Loops
Repetition Control Structures
WHILE Loops
• The WHILE statement is a statement in Python that repeatedly
executed a block of statements if a test at the top keeps
evaluating to a true value.
• When the test in the WHILE statement becomes false, control
passes to the statement that follows the WHILE block.
• The effect of this is that the statements in the WHILE block are
executed repeatedly while the test is true.
• If the test is false to begin with, the body never runs.
WHILE Loops
• The WHILE statement consists of a header line with a test
expression, a body of one or more indented statements, and an
optional else that is executed if control exits the loop without a
break statement.
• The general format of the WHILE statement is as follows:
• while <test>: # Loop test/condition
• <statements1> # Loop Body
• else: # Optional else
• <statements2> # Runs if didn’t exit loop with break
WHILE Loops
• An example of how to use the WHILE loop is shown below:
• while True:
• print("An endless loop...") # prints an endless loop of statements
• This sort of behavior in Python and in other languages is
commonly known as an Infinite Loop.
• This means that a loop with continue to run nonstop since no
stop conditions have been set.
WHILE Loops
• You can place a variable as part of the test in a WHILE loop.
• This allows you to assign a value that can stop the loop when it
is no longer needed.
• An example of this is shown here:
• x = True
• while x:
• print("wow!") # prints a single "wow!"
• x = False
WHILE Loops
• You can also make use of conditional statements as the test in
your WHILE loop.
• This will allow you to set a limit on the number of times the
WHILE block will execute based on a given condition.
• An example of this is shown below:
• y=0
• while (y < 5): # Conditional Statement
• print(y)
• y = y + 1 # Increments y to increase it
WHILE Loops
• You can also make use the characteristics of strings as the test
condition in a WHILE loop.
• This is recommended to using a more verbose equivalent (e.g.,
while (x != “”)).
• This is because strings with text count as a True value while
empty strings count as a False value.
WHILE Loops
• You can use string values in your WHILE loops, as shown
below:
• z = "cheese"
• while z:
• print(z, end=' ') # prints cheese heese eese ese se e
• z = z[1:] # removes the first letter in the string
PASS, CONTINUE, BREAK
and ELSE
Repetition Control Structures
PASS, CONTINUE, BREAK and ELSE
• Pass
• Does nothing at all; this is meant to be placeholder
• Continue
• Jumps to the top of the closest enclosing loop (to the loop’s header line)
• Break
• Jumps out of the closest enclosing loop (past the entire loop statement)
• Else
• In loops, this runs if and only if the loop is exited normally (i.e, without
hitting a break)
PASS, CONTINUE, BREAK and ELSE
• If we include the previous statements in our WHILE loop, it will
look something like this:
• while <test1>:
• <statement1>
• if <test2>: break # exits the loop now, skips else
• if <test3>: continue # go to the top of the loop now, to test1
• else:
• <statement2> # run if we didn't hit a "break"
PASS, CONTINUE, BREAK and ELSE
• BREAK and CONTINUE statements can appear anywhere
inside the WHILE loop body.
• They are usually coded further nested in an IF test to act in
response to some condition.
PASS, CONTINUE, BREAK and ELSE
• An example of this is shown here:
• x=0
• while x <= 3:
• print("zoom")
• x += 1
• if x == 2: break # outputs zoom twice because the loop is stopped
• else:
• print("doom") # never executes since it is skipped due to the break
PASS
• The PASS statement is a no-operation placeholder that is used
when the syntax requires a statement, but you don’t have any
code to place.
• The syntax for this is shown below:
• while True:
• pass # does nothing endlessly
PASS
• The PASS statement is like the “None” value for variables.
• This is meant to be a placeholder; you can think if it as a space
“to be filled in later”.
• Additionally, we can't leave the body of a WHILE loop empty,
so we use the PASS statement to fill in the space temporarily.
CONTINUE
• The CONTINUE statement causes an immediate jump to the
top of a loop.
• It can also help you avoid statement nesting.
• The syntax for this is shown below:
• while <test1>:
• <statements>
• if <test2>: continue # go to the top of the loop now, to test1
CONTINUE
• An example of the CONTINUE statement is shown below:
• x = 10
• while x:
• x=x-1 # this decrements the value of x by 1 per loop
• if x % 2 != 0: continue # this makes the loop skip odd numbers
• print(x, end=" ")
• As seen on the example above, the CONTINUE statement
allows you to skip or ignore certain values based on a given
criteria.
BREAK
• The BREAK statement causes an immediate exit from the loop.
• The code that follows in the loop is not executed if the break is
reached, so you can sometimes avoid nesting with this
statement.
• The syntax for this is shown below:
• while <test1>:
• <statements>
• if <test2>: break # exits the loop now
BREAK
• An example of how the BREAK statement is used is shown
below:
• student_list = []
• while True:
• new_name = input("Enter a student name to be added to the list:")
• if new_name == 'stop': break
• student_list.append(new_name)
• print(student_list)
LOOP ELSE
• Loop ELSE provides a way for us to catch the “other” way out
of a loop, without setting and checking flags or conditions.
• The ELSE statement only executes after a for loop terminates by
iterating to completion, or after a while loop terminates by its
conditional expression becoming false.
• The else clause does not execute if the loop terminates some
other way (through a break statement or by raising an
exception).
LOOP ELSE
• An example of how LOOP ELSE is used can be seen here:
• x = 10
• print("Countdown starting!")
• while x:
• print(x) # prints numbers 10 to 1
• x -= 1
• else:
• print("Time is up!") # executes at the end of the loop once x reaches 0
FOR Loop
Repetition Control Structures
FOR Loop
• A FOR loop in Python is used for iterating a sequence (a list, a
tuple, a dictionary, a set, or a string).
• The FOR loop can execute a set of statements, once for each item
in a list, tuple, dictionary, etc.
FOR Loop
• The python FOR loop begins with a header line that specifies an
assignment target, along with the object you want to step
through.
• The header is followed by a block of statements you want to
repeat:
• for <target> in <object>: # Assign object items to target
• <statements> # Repeated loop body: use target
• else:
• <statements> # If we didn't hit a 'break'
FOR Loop
• When Python runs a FOR loop, it assigns the items in the
sequence object to the target one by one and executes the loop
body for each.
• The loop body typically uses the assignment target to refer to
the current item in the sequence.
• The FOR loop also supports an optional ELSE block, which
works the same way it does for the WHILE loop.
FOR Loop
• An example of the FOR loop being used is seen below:
• food = ['eggs', 'rice', 'chicken', 'beef']
• for x in food: # goes through each value in the loop
• print(x, end=' ') # outputs "eggs, rice, chicken, beef"
FOR Loop
• BREAK, CONTINUE, PASS and ELSE can also be used in FOR
loops.
• An example of these statements being used in a FOR loop is seen
below:
• name_list = ['Jim', 'John', 'Joe', 'Jay', 'Juno']
• name_search = input("Please enter a name to search in the list")
• for names in name_list:
• if names == name_search:
• print("Name found!")
• break
• else:
• print("Name not found!")
FOR Loop
• You can also use other sequences in a FOR loop.
• You can for example use strings and tuples.
• An example of these two being used in a FOR loop can be seen
below:
• string_sample = "charger"
• tuple_sample = ("but", "why", "though")

• for x in string_sample: # for loops allow you to iterate each character in a


string
• print(x, end=" ") # outputs "c h a r g e r"

• for x in tuple_sample: # for loops also allow you to iterate values in a tuple
• print(x, end=" ") # outputs "but why though"
FOR Loop
• You can also iterate through a subsection of lists or tuples.
• This is done by assigning separate variables based on how
many values there are inside each entry in the list or tuple.
• An example of this can be seen below:
• list_sample = [[1,2],[3,4],[5,6]]
• for (a,b) in list_sample: # allows you to assign a variable to each sub list
• print(a,b) # outputs "1 2 \n 3 4 \n 5 6"
FOR Loop
• FOR loops can also be used to iterate through dictionaries.
• You can choose to iterate using just the keys, as seen below:
• dictionary_sample = {"a": 1, "b": 2, "c": 3}
• for key in dictionary_sample:
• print(key) # prints out “a b c”
FOR Loop
• You can also choose to iterate using both the keys and values
for the dictionary, as seen below:
• dictionary_sample = {"a": 1, "b": 2, "c": 3}
• for key, value in dictionary_sample.items(): # we use .items() to return
both keys and values
• print(key, "::", value) # outputs "a :: 1 \n b :: 2 \n c :: 3"
NESTED FOR Loops
Repetition Control Structures
NESTED FOR Loops
• In Python, you can create NESTED loops.
• These are simply loops within loops.
• You can use this to search multiple sets of data in a list.
• NESTED Loops means that multiple loops are running at the
same time, with the outer loop calling the inner loop every time
it iterates.
NESTED FOR Loops
• An example of a NESTED FOR loop is seen below:
• for x in (1, 2, 3):
• for y in (10, 20, 30):
• z=x*y
• print(z)

• Output:
10 20 30 20 40 60 30 60 90
NESTED FOR Loops
• In line with how loops are constructed, the indentation is
important.
• To create a NESTED Loop, you must make sure the inner loop
is indented and in line with the statements in the outer loop.

You might also like