Module 3.2 - Loops in Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

KeyboardInterrupt

To terminate a loop, just press Ctrl-C (or Ctrl-Break on some computers). This will cause the so-called

Multi-Line Printing

You can use triple quotes to print strings on multiple lines in order to make text easier to read, or create a special text-based design.

Infinite Loop

also called an endless loop, is a sequence of instructions in a program which repeat indefinitely (loop endlessly.) Here's an example of a loop that is not able to finish its execution: while True: print("I'm stuck inside a loop.")

Loop's Body

an instruction or set of instructions executed inside the while loop is called the

Control Variable

any variable after the for keyword is the ?; it counts the loop's turns, and does it automatically;

continue

behaves as if the program has suddenly reached the end of the body; the next turn is started and the condition expression is tested immediately.

Using a counter variable to exit a loop This code is intended to print the string "Inside the loop." and the value stored in the counter variable during a given loop exactly five times. Once the condition has not been met (the counter variable has reached 0), the loop is exited, and the message "Outside the loop." as well as the value stored in counter is printed.

counter = 5 while counter != 0: print("Inside the loop.", counter) counter -= 1 print("Outside the loop.", counter) But there's one thing that can be written more compactly - the condition of the while loop. Can you see the difference? counter = 5 while counter: print("Inside the loop.", counter) counter -= 1 print("Outside the loop.", counter) Is it more compact than previously? A bit. Is it more legible? That's disputable. REMEMBER Don't feel obliged to code your programs in a way that is always the shortest and the most compact. Readability may be a more important factor. Keep your code ready for a new programmer.

the for loop

executes a set of statements many times; it's used to iterate over a sequence (e.g., a list, a dictionary, a tuple, or a set - you will learn about them soon) or other objects that are iterable (e.g., strings). You can use the for loop to iterate over a sequence of numbers using the built-in range function. Look at the examples below: # Example 1 word = "Python" for letter in word: print(letter, end="*") output: P*y*t*h*o*n* ----------------------------------------- # Example 2 for i in range(1, 10): if i % 2 == 0: print(i) output: 2 4 6 8

the while loop

executes a statement or a set of statements as long as a specified boolean condition is true, e.g.: # Example 1 while True: print("Stuck in an infinite loop.") output: *infinite loop ---------------------------------------------- # Example 2 counter = 5 while counter > 2: print(counter) counter -= 1 output: 5 4 3

break

exits the loop immediately, and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body

if the set generated by the range() function is empty, the loop won't execute its body at all. Just like here - there will be no output:

for i in range(1, 1): print("The value of i is currently", i)

The set generated by the range() has to be sorted in ascending order. There's no way to force the range() to create a set in a different form when the range() function accepts exactly two arguments. This means that the range()'s second argument must be greater than the first. Thus, there will be no output here, either:

for i in range(2, 1): print("The value of i is currently", i)

The range() function invocation may be equipped with two arguments, not just one:

for i in range(2, 8): print("The value of i is currently", i) output: The value of i is currently 2 The value of i is currently 3 The value of i is currently 4 The value of i is currently 5 The value of i is currently 6 The value of i is currently 7 note: In this case, the first argument determines the initial (first) value of the control variable. The last argument shows the first value the control variable will not be assigned.

The range() function may also accept three arguments - take a look at the code in the editor. The third argument is an increment - it's a value added to control the variable at every loop turn (as you may suspect, the default value of the increment is 1). Do you know why? The first argument passed to the range() function tells us what the starting number of the sequence is (hence 2 in the output). The second argument tells the function where to stop the sequence (the function generates numbers up to the number indicated by the second argument, but does not include it). Finally, the third argument indicates the step, which actually means the difference between each number in the sequence of numbers generated by the function.

for i in range(2, 8, 3): print("The value of i is currently", i) output: The value of i is currently 2 The value of i is currently 5

The for loop and the else branch for loops behave a bit differently - take a look at the snippet in the editor and run it. The output may be a bit surprising. The i variable retains its last value.

for i in range(5): print(i) else: print("else:", i) output: 0 1 2 3 4 else: 4

Analyze the program carefully. See where the loop starts (line 8). Locate the loop's body and find out how the body is exited:

# Store the current largest number here. largest_number = -999999999 # Input the first value. number = int(input("Enter a number or type -1 to stop: ")) # If the number is not equal to -1, continue. while number != -1: # Is number larger than largest_number? if number > largest_number: # Yes, update largest_number. largest_number = number # Input the next number. number = int(input("Enter a number or type -1 to stop: ")) # Print the largest number. print("The largest number is:", largest_number)

Looping your code with for

Another kind of loop available in Python comes from the observation that sometimes it's more important to count the "turns" of the loop than to check the conditions. Imagine that a loop's body needs to be executed exactly one hundred times. If you would like to use the while loop to do it, it may look like this: i = 0 while i < 100: # do_something() i += 1 It would be nice if somebody could do this boring counting for you. Is that possible? Of course it is - there's a special loop for these kinds of tasks, and it is named "for". Actually, the for loop is designed to do more complicated tasks - it can "browse" large collections of data item by item. We'll show you how to do that soon, but right now we're going to present a simpler variant of its application.

Looping your code with while while conditional_expression: instruction_one instruction_two instruction_three : : instruction_n It is now important to remember that: if you want to execute more than one statement inside one while, you must (as with if) indent all the instructions in the same way; an instruction or set of instructions executed inside the while loop is called the loop's body; if the condition is False (equal to zero) as early as when it is tested for the first time, the body is not executed even once (note the analogy of not having to do anything if there is nothing to do); the body should be able to change the condition's value, because if the condition is True at the beginning, the body might run continuously to infinity - notice that doing a thing usually decreases the number of things to do).

Do you agree with the statement presented below? while there is something to do do it Note that this record also declares that if there is nothing to do, nothing at all will happen. In general, in Python, a loop can be represented as follows: while conditional_expression: instruction If you notice some similarities to the if instruction, that's quite all right. Indeed, the syntactic difference is only one: you use the word while instead of the word if. The semantic difference is more important: when the condition is met, if performs its statements only once; while repeats the execution as long as the condition evaluates to True.

The break and continue statements

So far, we've treated the body of the loop as an indivisible and inseparable sequence of instructions that are performed completely at every turn of the loop. However, as developer, you could be faced with the following choices: it appears that it's unnecessary to continue the loop as a whole; you should refrain from further execution of the loop's body and go further; it appears that you need to start the next turn of the loop without completing the execution of the current turn. Python provides two special instructions for the implementation of both these tasks. Let's say for the sake of accuracy that their existence in the language is not necessary - an experienced programmer is able to code any algorithm without these instructions. Such additions, which don't improve the language's expressive power, but only simplify the developer's work, are sometimes called syntactic candy, or syntactic sugar. These two instructions are: break - exits the loop immediately, and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body; continue - behaves as if the program has suddenly reached the end of the body; the next turn is started and the condition expression is tested immediately. Both these words are keywords.

syntactic candy, or syntactic sugar These two instructions are: - break - exits the loop immediately, and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body; - continue - behaves as if the program has suddenly reached the end of the body; the next turn is started and the condition expression is tested immediately.

Such additions, which don't improve the language's expressive power, but only simplify the developer's work, are sometimes called

example: for i in range(10): print("The value of i is currently", i)

The value of i is currently 0 The value of i is currently 1 The value of i is currently 2 The value of i is currently 3 The value of i is currently 4 The value of i is currently 5 The value of i is currently 6 The value of i is currently 7 The value of i is currently 8 The value of i is currently 9 Note: - the loop has been executed ten times (it's the range() function's argument) - the last control variable's value is 9 (not 10, as it starts from 0, not from 1)

Take a look at the snippet: for i in range(100): # do_something() pass

There are some new elements. Let us tell you about them: - the for keyword opens the for loop; note - there's no condition after it; you don't have to think about conditions, as they're checked internally, without any intervention; - any variable after the for keyword is the control variable of the loop; it counts the loop's turns, and does it automatically; - the in keyword introduces a syntax element describing the range of possible values being assigned to the control variable; - the range() function (this is a very special function) is responsible for generating all the desired values of the control variable; in our example, the function will create (we can even say that it will feed the loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98, 99; note: in this case, the range() function starts its job from 0 and finishes it one step (one integer number) before the value of its argument; - note the pass keyword inside the loop body - it does nothing at all; it's an empty instruction - we put it here because the for loop's syntax demands at least one instruction inside the body (by the way - if, elif, else and while express the same thing)

while and for

There are two types of loops in Python:

range() function The syntax of range() looks as follows: range(start, stop, step), where: start is an optional parameter specifying the starting number of the sequence (0 by default) stop is an optional parameter specifying the end of the sequence generated (it is not included), and step is an optional parameter specifying the difference between the numbers in the sequence (1 by default.) example: for i in range(3): print(i, end=" ") # Outputs: 0 1 2 print() for i in range(6, 1, -2): print(i, end=" ") # Outputs: 6, 4, 2 output: 0 1 2 6 4 2

generates a sequence of numbers. It accepts integers and returns range objects

The while loop and the else branch Both loops, while and for, have one interesting (and rarely used) feature. We'll show you how it works - try to judge for yourself if it's usable and whether you can live without it or not. In other words, try to convince yourself if the feature is valuable and useful, or is just syntactic sugar. Take a look at the snippet in the editor. There's something strange at the end - the else keyword. As you may have suspected, loops may have the else branch too, like ifs. The loop's else branch is always executed once, regardless of whether the loop has entered its body or not. Can you guess the output? Run the program to check if you were right. Modify the snippet a bit so that the loop has no chance to execute its body even once: The while's condition is False at the beginning - can you see it?

i = 1 while i < 5: print(i) i += 1 else: print("else:", i) output: 1 2 3 4 else: 5

Can you guess the output? The loop's body won't be executed here at all. Note: we've assigned the i variable before the loop. Run the program and check its output. When the loop's body isn't executed, the control variable retains the value it had before the loop. Note: if the control variable doesn't exist before the loop starts, it won't exist when the execution reaches the else branch.

i = 111 for i in range(2, 1): print(i) else: print("else:", i) output: else: 111

pass keyword

inside the loop body - it does nothing at all; it's an empty instruction - we put it here because the for loop's syntax demands at least one instruction inside the body (by the way - if, elif, else and while express the same thing)

the range() function accepts only

integers as its arguments, and generates sequences of integers.

the in keyword

introduces a syntax element describing the range of possible values being assigned to the control variable;

range() function

is responsible for generating all the desired values of the control variable; in our example, the function will create (we can even say that it will feed the loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98, 99; note: in this case, this function starts its job from 0 and finishes it one step (one integer number) before the value of its argument;

The continue statement

is used to skip the current block and move ahead to the next iteration, without executing the statements inside the loop.

The while and for loops can also have an else clause in Python. The else clause executes after the loop finishes its execution as long as it has not been terminated by break, e.g.:

n = 0 while n != 3: print(n) n += 1 else: print(n, "else") print() for i in range(0, 3): print(i) else: print(i, "else") output: 0 1 2 3 else 0 1 2 2 else

The while loop: more examples Certain expressions can be simplified without changing the program's behavior. Try to recall how Python interprets the truth of a condition, and note that these two forms are equivalent: while number != 0: and while number:. The condition that checks if a number is odd can be coded in these equivalent forms, too: if number % 2 == 1: and if number % 2:.

odd_numbers = 0 even_numbers = 0 # Read the first number. number = int(input("Enter a number or type 0 to stop: ")) # 0 terminates execution. while number != 0: # Check if the number is odd. if number % 2 == 1: # Increase the odd_numbers counter. odd_numbers += 1 else: # Increase the even_numbers counter. even_numbers += 1 # Read the next number. number = int(input("Enter a number or type 0 to stop: ")) # Print results. print("Odd numbers count:", odd_numbers) print("Even numbers count:", even_numbers)

The break and continue statements example: # break - example print("The break instruction:") for i in range(1, 6): if i == 3: break print("Inside the loop.", i) print("Outside the loop.") # continue - example print("\nThe continue instruction:") for i in range(1, 6): if i == 3: continue print("Inside the loop.", i) print("Outside the loop.")

output: The break instruction: Inside the loop. 1 Inside the loop. 2 Outside the loop. The continue instruction: Inside the loop. 1 Inside the loop. 2 Inside the loop. 4 Inside the loop. 5 Outside the loop.

Let's have a look at a short program whose task is to write some of the first powers of two:

power = 1 for expo in range(16): print("2 to the power of", expo, "is", power) power *= 2 output: 2 to the power of 0 is 1 2 to the power of 1 is 2 2 to the power of 2 is 4 2 to the power of 3 is 8 2 to the power of 4 is 16 2 to the power of 5 is 32 2 to the power of 6 is 64 2 to the power of 7 is 128 2 to the power of 8 is 256 2 to the power of 9 is 512 2 to the power of 10 is 1024 2 to the power of 11 is 2048 2 to the power of 12 is 4096 2 to the power of 13 is 8192 2 to the power of 14 is 16384 2 to the power of 15 is 32768 The expo variable is used as a control variable for the loop, and indicates the current value of the exponent. The exponentiation itself is replaced by multiplying by two. Since 2(to the 0 power) is equal to 1, then 2 × 1 is equal to 2(to the 1 power), 2 × 2(to the 1 power) is equal to 2(to the 2 power), and so on.

A junior magician has picked a secret number. He has hidden it in a variable named secret_number. He wants everyone who run his program to play the Guess the secret number game, and guess what number he has picked for them. Those who don't guess the number will be stuck in an endless loop forever! Unfortunately, he does not know how to complete the code. Your task is to help the magician complete the code in the editor in such a way so that the code: - will ask the user to enter an integer number; - will use a while loop; - will check whether the number entered by the user is the same as the number picked by the magician. If the number chosen by the user is different than the magician's secret number, the user should see the message "Ha ha! You're stuck in my loop!" and be prompted to enter a number again. If the number entered by the user matches the number picked by the magician, the number should be printed to the screen, and the magician should say the following words: "Well done, muggle! You are free now."

secret_number = 777 number = int(input("Type in a number: ")) while number != secret_number: print("Ha ha! You're stuck in my loop!") number = int(input("Type in another number loser!!: ")) else: print("Well done, muggle! You are free now.")

Example of continue statement

user_word = input("Enter your word: ") user_word = user_word.upper() for letter in user_word: if letter == "A": continue elif letter == "E": continue elif letter == "I": continue elif letter == "O": continue elif letter == "U": continue else: print(letter) Input: Gregory Output: GRGRY

The break statement is used to exit/terminate a loop. Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters "chupacabra" as the secret exit word, in which case the message "You've successfully left the loop." should be printed to the screen, and the loop should terminate. Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.

while True: word = input("You're stuck in an infinite loop!\nEnter the secret word to leave the loop: ") if word == "chupacabra": break print("You've successfully left the loop!")

Another example of continue statement and assigning the output to a new variable: Familiarize the student with: using the continue statement in loops; modifying and upgrading the existing code; reflecting real-life situations in computer code. Scenario Your task here is even more special than before: you must redesign the (ugly) vowel eater from the previous lab (3.1.2.10) and create a better, upgraded (pretty) vowel eater! Write a program that uses: a for loop; the concept of conditional execution (if-elif-else) the continue statement. Your program must: ask the user to enter a word; use user_word = user_word.upper() to convert the word entered by the user to upper case; we'll talk about the so-called string methodsand the upper() method very soon - don't worry; use conditional execution and the continue statement to "eat" the following vowels A, E, I, O, U from the inputted word; assign the uneaten letters to the word_without_vowels variable and print the variable to the screen. Look at the code in the editor. We've created word_without_vowels and assigned an empty string to it. Use concatenation operation to ask Python to combine selected letters into a longer string during subsequent loop turns, and assign it to the word_without_vowels variable.

word_without_vowels = "" user_word = input("Enter your word: ") user_word = user_word.upper() for letter in user_word: if letter == "A": continue elif letter == "E": continue elif letter == "I": continue elif letter == "O": continue elif letter == "U": continue else: word_without_vowels += letter print(word_without_vowels) Output: Enter your word: Gregory GRGRY


Set pelajaran terkait

personal finance exam 1 (ch 1-4) terms

View Set

142 Final - Part 4 - PRACTICE QUESTIONS

View Set

Sleeping needs of the infant, toddler, and young child

View Set