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

Python Note 8

Python Learning Notes

Uploaded by

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

Python Note 8

Python Learning Notes

Uploaded by

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

Python Note 8

03/01/2024

The while loop: more examples

Let's look at another example employing the while loop. Follow the
comments to find out the idea and the solution.

# A program that reads a sequence of numbers


# and counts how many numbers are even and how many are odd.
# The program terminates when zero is entered.

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)

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:

Using a counter variable to exit a loop

Look at the snippet below:

counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)

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.

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.

LAB

Estimated time

15 minutes

Level of difficulty

Easy

Objectives

Familiarize the student with:

 using the while loop;


 reflecting real-life situations in computer code.

Scenario

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."

The magician is counting on you! Don't disappoint him.

EXTRA INFO

By the way, look at the print() function. The way we've used it here is
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. Experiment with it.

secret_number = 777

print("""

+================================+

| Welcome to my game, muggle! |

| Enter an integer number |

| and guess what number I've |

| picked for you. |


| So, what is the secret number? |

+================================+

""")

Answer:

while True:
# Ask the user to guess the secret number
user_guess = int(input("""Enter an integer number to guess the secret
number:"""))

# Check if the guess is incorrect


if user_guess != secret_number:
# User guessed the wrong number
print("""Ha ha! You're stuck in my loop!""")
else:
print("""secret_number""")
print("""Well done, muggle! You are free now.""")

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.

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)

Our next examples will be a bit more modest in the number of loop
repetitions.

Take a look at the snippet below. Can you predict its output?
for i in range(10):
print("The value of i is currently", i)

Run the code to check if you were right.

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 )

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)

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.

Note: the range() function accepts only integers as its arguments, and
generates sequences of integers.

Can you guess the output of the program? Run it to check if you were right
now, too.

The first value shown is 2 (taken from the range() 's first argument.)

The last is 7 (although the range() 's second argument is 8 ).


More about the for loop and

the range() function with three arguments

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).

Can you tell us how many lines will appear in the console and what values
they will contain?

Run the program to find out if you were right.

for i in range(2, 8, 3):


print("The value of i is currently", i)

You should be able to see the following lines in the console window:

The value of i is currently 2


The value of i is currently 5

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.

2 (starting number) → 5 ( 2 increment by 3 equals 5 - the number is within the


range from 2 to 8) → 8 ( 5 increment by 3 equals 8 - the number is not within
the range from 2 to 8, because the stop parameter is not included in the
sequence of numbers generated by the function.)

Note: 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)

Note: 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)

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

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 20 is equal to 1, then 2 × 1 is equal to 2 1, 2 × 21 is
equal to 22, and so on. What is the greatest exponent for which our program
still prints the result?

Run the code and check if the output matches your expectations.

LAB

Estimated time

5-15 minutes
Level of difficulty

Very easy

Objectives

Familiarize the student with:

 using the for loop;


 reflecting real-life situations in computer code.

Scenario

Do you know what Mississippi is? Well, it's the name of one of the states and
rivers in the United States. The Mississippi River is about 2,340 miles long,
which makes it the second longest river in the United States (the longest
being the Missouri River). It's so long that a single drop of water needs 90
days to travel its entire length!

The word Mississippi is also used for a slightly different purpose: to count
mississippily.

If you're not familiar with the phrase, we're here to explain to you what it
means: it's used to count seconds.

The idea behind it is that adding the word Mississippi to a number when
counting seconds aloud makes them sound closer to clock-time, and therefore
"one Mississippi, two Mississippi, three Mississippi" will take approximately an
actual three seconds of time! It's often used by children playing hide-and-seek
to make sure the seeker does an honest count.
Your task is very simple here: write a program that uses a for loop to "count
mississippily" to five. Having counted to five, the program should print to the
screen the final message "Ready or not, here I come!"

Use the skeleton we've provided in the editor.

EXTRA INFO

Note that the code in the editor contains two elements which may not be fully
clear to you at this moment: the import time statement, and
the sleep() method. We're going to talk about them soon.

For the time being, we'd just like you to know that we've imported
the time module and used the sleep() method to suspend the execution of
each subsequent print() function inside the for loop for one second, so that
the message outputted to the console resembles an actual counting. Don't
worry - you'll soon learn more about modules and methods.

Answer:

import time

# Start counting
for i in range(1, 6): # Range from 1 to 5
print(f"{i} Mississippi")
time.sleep(1) # Wait for a second

# Print the final message


print("Ready or not, here I come!")

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.

Now we'll show you two simple examples to illustrate how the two instructions
work. Look at the code in the editor. Run the program and analyze the output.
Modify the code and experiment.

# 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.")

LAB

Estimated time

10-20 minutes

Level of difficulty

Easy

Objectives

Familiarize the student with:

 using the break statement in loops;


 reflecting real-life situations in computer code.

Scenario

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:
user_enter = input("Enter a word as the secret exit word: ")
if user_enter == "chupacabra":
break

print("You've successfully left the loop.")

LAB

Estimated time

10-20 minutes

Level of difficulty

Easy

Objectives

Familiarize the student with:

 using the continue statement in loops;


 reflecting real-life situations in computer code.
Scenario

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

It can be used with both the while and for loops.

Your task here is very special: you must design a 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
methods and 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;
 print the uneaten letters to the screen, each one of them on a separate
line.

Test your program with the data we've provided for you.

# Prompt the user to enter a word


# and assign it to the user_word variable.
user_word = input("Enter a word: ")

# Convert the word to uppercase


user_word = user_word.upper()

# Iterate over the word using a for loop


for letter in user_word:
# Use conditional execution to "eat" the vowels
if letter in ["A", "E", "I", "O", "U"]:
continue # Skip the printing of the vowel and move to the
next iteration
# Print the uneaten letters
print(letter)

LAB

Estimated time

5-15 minutes

Level of difficulty

Easy

Objectives

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
methods and 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.

Test your program with the data we've provided for you.

# Ask the user to enter a word


user_word = input("Enter a word: ")

# Convert the word entered by the user to upper case


user_word = user_word.upper()

# Create a new variable to store the letters without vowels


word_without_vowels = ""
# Iterate over the word using a for loop
for letter in user_word:
# Use conditional execution to "eat" the vowels
if letter in ["A", "E", "I", "O", "U"]:
continue # Skip the vowel and move to the next iteration
# Concatenate the uneaten letters to the word_without_vowels
variable
word_without_vowels += letter

# Print the word_without_vowels variable to the screen


print(word_without_vowels)

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.

i=1

while i < 5:

print(i)

i += 1

else:

print("else:", i)
As you may have suspected, loops may have the else branch too,
like if s.

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:

i = 5
while i < 5:
print(i)
i += 1
else:
print("else:", i)

The while 's condition is False at the beginning - can you see it?

Run and test the program, and check whether the else branch has been
executed or not.

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.

for i in range(5):

print(i)

else:

print("else:", i)

The output may be a bit surprising.

The i variable retains its last value.


Modify the code a bit to carry out one more experiment.

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

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.

How do you feel about this variant of else ?

Now we're going to tell you about some other kinds of variables. Our current
variables can only store one value at a time, but there are variables that
can do much more - they can store as many values as you want.

LAB

Estimated time

20-30 minutes
Level of difficulty

Medium

Objectives

Familiarize the student with:

 using the while loop;


 finding the proper implementation of verbally defined rules;
 reflecting real-life situations in computer code.

Scenario

Listen to this story: a boy and his father, a computer programmer, are playing
with wooden blocks. They are building a pyramid.

Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat.


The pyramid is stacked according to one simple principle: each lower layer
contains one block more than the layer above.

The figure illustrates the rule used by the builders:


Your task is to write a program which reads the number of blocks the builders
have, and outputs the height of the pyramid that can be built using these
blocks.

Note: the height is measured by the number of fully completed layers - if


the builders don't have a sufficient number of blocks and cannot complete the
next layer, they finish their work immediately.

Test your code using the data we've provided.

blocks = int(input("Enter the number of blocks: "))

# Initialize the height of the pyramid.


height = 0

# Loop to build the pyramid layer by layer.


while blocks > height:
height += 1 # Move to the next layer.
blocks -= height # Use the blocks for the current layer.

# The loop exits when there are not enough blocks to complete the
next layer.
# At this point, 'height' is the height of the last completed layer.

print("The height of the pyramid:", height)

LAB

Estimated time

20 minutes
Level of difficulty

Medium

Objectives

Familiarize the student with:

 using the while loop;


 converting verbally defined loops into actual Python code.

Scenario

In 1937, a German mathematician named Lothar Collatz formulated an


intriguing hypothesis (it still remains unproven) which can be described in the
following way:

1. take any non-negative and non-zero integer number and name it c0 ;


2. if it's even, evaluate a new c0 as c0 ÷ 2 ;
3. otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1 ;
4. if c0 ≠ 1 , skip to point 2.

The hypothesis says that regardless of the initial value of c0 , it will always go
to 1.

Of course, it's an extremely complex task to use a computer in order to prove


the hypothesis for any natural number (it may even require artificial
intelligence), but you can use Python to check some individual numbers.
Maybe you'll even find the one which would disprove the hypothesis.
Write a program which reads one natural number and executes the above
steps as long as c0 remains different from 1. We also want you to count the
steps needed to achieve the goal. Your code should output all the
intermediate values of c0 , too.

Hint: the most important part of the problem is how to transform Collatz's idea
into a while loop - this is the key to success.

# Read a natural number from the user.


c0 = int(input("Enter a non-negative and non-zero integer: "))

# Check to make sure the input is a non-negative and non-zero


integer.
if c0 <= 0:
print("The number must be a non-negative and non-zero integer.")
else:
steps = 0 # Initialize the step counter.

# Execute the steps of the Collatz conjecture.


while c0 != 1:
if c0 % 2 == 0: # If c0 is even.
c0 = c0 // 2
else: # If c0 is odd.
c0 = 3 * c0 + 1
print(c0) # Print the intermediate value of c0.
steps += 1 # Increment the step counter.

# Print the total number of steps taken to reach 1.


print("Steps taken:", steps)

You might also like