Statement while. Examples

Statement while. Examples


Contents


1. The purpose of the while statement. The general form of the while statement

The while statement is intended for organizing a cyclic process in a program. In the Python programming language, the while statement is used in cases where the number of repetitions of a loop is not known in advance (as opposed to the for statement). In the while statement, the next iteration of the loop is determined based on the truth of a condition.

The general form of the while statement is

while condition:
    instructions

here

  • condition – condition for the execution of the instruction line (s);
  • instructions – one statement or a set of statements that are executed if value condition = True. If the condition value becomes equal to False, the execution of the while loop operator is completed.

 

2. Examples of solving of tasks using the while statement
2.1. Calculate the sum of the elements of the list

The task. Some list A is given containing integers. Using a while statement to develop a program that calculates the sum of the elements of the list.

# create a list and initialize the variables
A=[1,3,5,8,-3,10]
i=0
summ=0 # the required sum

# the loop of sum calculation
while i<len(A):
    summ=summ+A[i]
    i=i+1
print("summ = ", summ) # summ = 24

To determine the number of elements of the list A, the function len(A) is used. As a result of executing the above code, the result will be obtained.

summ = 24

 

2.2. Create a list of a given length and write the specified number into it

In the example, using a while loop, two lists A and B are formed in different ways.

# create a list of items
A=[]
n=10
i=0

while i<n: # the list is formed in a cycle [0,1,2,3,4,5,6,7,8,9]
    A=A+[i]
    i=i+1

# create a new list
B=[]
k=5 # the number that is written to list B
n=4 # amount of numbers

# while loop
i=0
while i<n: # list is formed [5,5,5,5]
    B = B + [k]
    i=i+1

# display A list
i=0
print("List A:")
while i<len(A):
    print(A[i])
    i=i+1

# display B list
i=0
print("List B:")
while i<len(B):
    print(B[i])
    i=i+1

As a result of executing the above code, the following result will be obtained.

List A:
0
1
2
3
4
5
6
7
8
9
List B:
5
5
5
5

 

2.3. List creation by condition

The number a (1<a<1.5) is given. From numbers 1+1/2, 1+1/3, 1+1/4 … print those that are not less than a.

Decision.

a=1.08
print("Number a = ", a)
n=2
t=1+1/n
print("Numbers, that are not less then a:")
while t>a:
    print(t)
    n=n+1
    t=1+1/n
print("-----------------------")

As a result of executing the above code, the following result will be displayed.

Number a = 1.08
Numbers, that are not less then a:
1.5
1.3333333333333333
1.25
1.2
1.1666666666666667
1.1428571428571428
1.125
1.1111111111111112
1.1
1.0909090909090908
1.0833333333333333
-----------------------

 

3. The concept of a nested instruction (statement) while

The while statement can have multiple levels of nesting. It may be external to other instructions, for example, for, if, while. Also, a while statement can be placed inside other instructions (for, if, while). The number of levels (depth) of nestings is unlimited.



 

4. Examples of task solving, where the while statement is external to other statements
4.1. Counting the number of occurrences of a given string in the list of strings

The while loop uses a nested if statement.

# Counting the number of occurrences of a given string in the list of strings
# Input data
LIST = [ 'abc', 'bcd', 'xvm', 'abc', 'abd', 'bcd', 'abc' ]
ITEM = str(input('Input the string: '))

# calculation
i=0
k=0
while i<len(LIST):
    if LIST[i]==ITEM:
        k=k+1
    i=i+1
print ("k = ", k)

As a result of executing the above code, the following result will be obtained.

Input the string: bcd
k = 2

 

4.2. Definition of the month, day and day of the week for the ordinal number of the day in the year

 An integer k is set (1<k<365). Write a code snippet that defines:

  • what will be the k-th day of the year: weekend (Saturday, Sunday);
  • what will be the date (month and day).

In the program it is needed to use the while statement.

The text of the program is as follows:

# input data
print("Input data: ")
k = int(input('Number of the day in the year: '))
first_day=3 # first day of the year, 3 - Wednesday
print("The first day of the week of the year: ", first_day)

# auxiliary list - the number of days in months of the year
MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31]

# initial initialization before calculation
tk=1 # the current value of the day
tday=first_day # current day of the week
tmonth=1 # the current number of the month
tday2=1 # the current number of day in the month tmonth

# statement while - calculation
while tk<k:
    # go to the next day
    tday=tday+1
    tday2=tday2+1
    tk=tk+1

    # correct the day of the week
    if tday>7:
        tday=1

    # correct the day of the month and the number of the month
    if tday2>MONTHS[tmonth-1]:
        tday2=1
        tmonth=tmonth+1 # go to next month
print("--------------------")
print("Result: ")
print("Day of the week: ", tday)
print("Month number: ", tmonth)
print("Number: ", tday2)

In the above code, the additional internal variables (objects) tk, tday, tmonth, td2 and the MONTHS list containing the number of days in any month of the year are used for the calculation. In the example, the while loop contains several nested assignment statements and two if statements.

As a result of executing the above code, the following result will be obtained:

Input data:
Number of the day in the year: 256
The first day of the week of the year: 3
--------------------
Result:
Day of the week: 6
Month number: 9
Number: 13

As you can see, the 256th day in the non-leap year falls on September 13, which corresponds to the Programmer’s Day (and what else could it be?).

 

4.3. Counting the number of occurrences of a given character in a string

A list of strings is specified. In each string, count the number of occurrences of a given character.

The code in Python will be the next

# the number of occurrences of a character in the list of strings
ListStr=['text', 'file', 'notepad', 'windows', 'hello']
c='t' # character 't'
List=[] # number of occurences
i=0
while i<5:
    j=0
    k=0
    while j<len(ListStr[i]):
        if c==ListStr[i][j]:
            k=k+1
        j=j+1
    ListK=ListK+[k]
    i=i+1
print(ListK) # ListK = [2, 0, 1, 0, 0]

After executing the above code, the following result will be obtained

[2, 0, 1, 0, 0]

 

5. Examples of solving of tasks in which the while statement is nested
5.1. Zeroing a two-dimensional list

In this example, the while statement implements another, nested while statement. Zeroing of a two-dimensional list of numbers using a nested while instruction is implemented

# some list A is defined by size 3 * 4
A=[ [1, 3, -2, -3], [0, 8, 1, -3], [2, 5, 3, 1]]

# zeroing of list A
# use of a nested while statement
i=0 # strings
while i<3:
    j=0
    while j<len(A[i]):
        A[i][j]=0
        j=j+1
    i=i+1

# output the list A
print("List A:")
i=0
while i<3:
    j=0
    while j<len(A[i]):
        print("A[", i,"][",j,"] = ", A[i][j])
        j=j+1
    i=i+1
print("--------------------")

 

5.2. The task of bulls, cows and calves

The task. Available $ 100. How many bulls, cows and calves can be bought with all this money, if the fee for a bull is $ 10, the fee for a cow is $ 5, and the fee for a calf is $ 0.5. Be sure to buy at least one copy of each species (one bull, one cow, one calf). Print all possible payment options.

Decision. This task is solved in different ways. In this case, the problem is solved in a simplified way of understanding using nested while loops.

# the task about bulls, cows and calves
x=1
while x<98:
    y=1
    while y<=(100-x):
        z=1
        while z<=(100-x-y):
            cost=10*x+5*y+0.5*z
            if cost==100:
                print("x=", x,"; y=", y, "z=", z)
            z=z+1
        y=y+1
    x=x+1

As a result of the above code, a list of possible options (combinations) is displayed on the screen, which form a set of solutions to this problem.

 

6. The general form of a while statement that uses the break statement

The while statement has another, more complete form of use, which involves the use of the break instruction. In this case, the general form of the while statement is as follows:

while <condition1>:
    <instructions1>
    if <condition2>: break # get out of the cycle
    if <condition3>: continue # go to the condition1
else:
    <instructions2> # executed if break instruction was not used

here

  • condition1 determines whether to perform the next iteration of the loop. If the value of condition1 is True, then the next iteration of the loop is performed;
  • condition2 determines whether the break statement should be executed;
  • condition3 determines whether the continue statement should be executed;
  • instructions1, instructions2 are one or several operators.

The above form of the while loop operator works according to the following principle. First, condition1 is checked. If the condition1 is true (equal to True), then the instructions1 are executed. The conditions of condition2, condition3 are also checked in the body of the while loop operator. If condition2 is True, the loop is exited. If condition3 is True, the next iteration of the loop proceeds until condition1 is checked.

If the break statement is not executed in the loop body, this means that all possible iterations have been completed. In this case, the corresponding instructions are defined in the else block of the while statement.

 

7. An example of using a while statement that involves using a break statement

In the example, a search (determination of the presence) of a given item in the list is performed. If the item is not found, the corresponding message is displayed.

# given a list
List=[2,8,3,4,3,5,2,1,0,3,4,4,5,8,7,7,5]

print("Specified list:", List)

# input of the desired element
t = int(input("The item to find: "))

# loop
i=0
while i<len(List):
    if List[i]==t:
        print("The item ", t, " is in the list")
        break
    i=i+1
else:
    print("The item ", t, " is not in the list")

In the above while loop, the condition for executing a looping process is checked

i<len(List)

In the body of the while loop, it is checked whether the value of the desired element t matches the value of the List[i] element of the list

if List[i]==t:
    ...

If a match is found, then there is no point in continuing to further traverse the list. Therefore, the break statement is called in the body of the if statement.

If the entire list is passed and no elements are found, this means that the break statement was not executed once. In this case, the else block of the while statement is called:

...
else:
    print("The item ", t, " is not in the list")

After running the program above, the following result will be displayed.

Specified list: [2, 8, 3, 4, 3, 5, 2, 1, 0, 3, 4, 4, 5, 8, 7, 7, 5]
The item to find: 4
The item 4 is in the list

 


Related topics