Uncategorized

15:Iterations

Iterations

Iterations look similar to If but then the only difference is that when the last line of code block executes, it jumps back and if the condition is True, it will again execute the block and this process will continue until the condition is false. There are some other statements too that help to manage the iterations.

while Iterator

  1. Iterations help to repeat a set of statements again and again.
  2. There should be some condition that allows start and stop the iteration else iteration repeats forever and may crash the program.
  3. Python has a repeating or iterative construct called while.
  4. while is simple like if.
  5. It checks a condition (Boolean expression) and if the condition produces True, it allows to execute the statements under it.
  6. When all statements get executed then it again checks the condition.
  7. If the condition is still True then it again allows executing the statements.
  8. This loop will continue all the time until the condition produces False.
num = 1while (num < 10):    print(num)    num = num + 1print ("Loop finished")

Code 1: Using while Loop

  1. Initially, we create a variable num and store 1 in it.
  2. On line 2, we have while and there is a Boolean expression in front of it.
  3. This expression will produce True because num is less than 10.
  4. As the condition is True, it first executes the print statement and prints the value of num.
  5. On the next line, 1 will be added to num (which is also 1) and result will become 2 will save to num.
  6. The next line (print statement) is indent backed so we jump to line 2 again. Where the expression will again produce True because the value of num is 2 and it is still less than 10.
  7. Line 3 and 4 will execute and 1 increment in num and now the value of num will be 3.
  8. Again, the loop ends so it jumps to line 2 and evaluates the condition will find it still True and the again line 3 and 4 will execute.
  9. It will iterate again and again. On each iteration, we observe that the value of num is increasing 1.
  10. Thus, when the value of num will come to 10, the condition will produce False because 10 is not less than 10.
  11. This time loop will not allow it to continue and it will jump to line 5 and print “Loop finished”.
  12. Like if statement, the while statement can also use logical operators.
  13. It is not necessary that there should be a variable (num in our example) that increases every time. It might be decreased or may be used in some tricky ways.
  14. For example, if we want to print the numbers from 10 to 1 in reverse order then our code will be this.
num = 10while (num > 0):    print(num)    num = num - 1print ("Loop finished")

Code 2: Printing numbers in Reverse Order

  1. Here use small tweaks to change the program.
  2. First the initializing num with 10 rather than 1.
  3. The condition has two changes. First the < symbol changed to > and the value of comparison also changed from 10 to 0.
  4. Similarly, on line 4, we also use – symbol rather + to perform decrement.
  5. Like other programs, there may be many variables in a program that contains while.

Example 1: Write a program that prints the table of given numbers from 1 to 10.

Solution:

  1. Here is the pseudocode
  2. Take an integer from the user.
  3. Take another variable and initialize it with 1 because we have to start the table from 1. This variable can be called an index.
  4. Apply a while and set the condition that checks the index is less or equals than 10.
  5. In the loop, first find the product of the number and index and print this product.
  6. Increment the index for 1.
num = int (input ("Enter a number: "))index = 1while index <= 10:    result = num * index    print(f"{num} x {index} = {result}")    index += 1

Code 3: Generating Simple Table of Given Number

  1. First, we take the variable num and input a number into.
  2. Set the index variable to 1.
  3. Check the condition in while that index is less than 10.
  4. Inside the loop, we find the product of num and index and save it to result.
  5. Print the result in presentable format.

Increase the index by 1. Here you can see the new operator += for this purpose.

Figure 1: Output of Code 3

  1. We can enter any number to print its table.

break and continue Statements

  1. These are two different statements and used for different purposes.
  2. First, we examine the break statement.
  3. If we want to exit from the while loop without making the condition False then we can use it.
num = 1while (num < 10):    print (num)    num += 1    breakprint (num)

Code 4: Using break Statement

  1. We start the loop with a value of num to 1 and the condition is num < 10.
  2. It means that this loop will continue until the value of num reaches 10.
  3. Loop will execute first time because num value is 1.
  4. Print the value of num and make an increment of 1 in num.
  5. There is a break statement on line 4 which forces the CPU to jump on line 5 which is out of the loop.
  6. We will exit the loop and print the value of num which will be 2.
  7. We can see that the value of num is still less than 10 which makes while condition True but we are out of the iteration due to break.
  8. In the above example, we use break statements with any condition but in real world scenarios, we apply some if-else or match-case for break.
  9. Unlike break statements, the continue statement forces the CPU to check the condition without completing the iteration.
num = 1while (num < 10):    print(num)    if (num > 5):        num += 2        continue    num += 1print (num)

Code 5: Using continue Statement

  1. We start the loop with 1 and set the condition to 10.
  2. Inside the loop we first print the value of num.
  3. Then check that the value is num is more than 5 which produces False for the first five iterations and num will increment to 1 each time.
  4. When the value of num exceeds 5, the if condition will be True.
  5. Now num will get incremented to 2 rather 1. This time the value of num is 6 so it will add 2 and the value reaches to 8.
  6. Next is the continue statement that forces you to jump on while condition.
  7. Now it will compare the num value 8 with 10 which True and again go into the while loop.
  8. Print 8.
  9. Again, the comparison with 5 will produce True and add 2 in 8 and will reach to 10 and again encounter with continue which force to jump on while.
  10. Now while condition will produce False because 10 is not less than 10 and the final output of print 10.

Figure 2: Output of continue Statement

  1. You can see that the output prints 1 to 6 in sequence and then omit 7 and 9 due to 2 increments in num value and print 10.

Example 2: We want to calculate the total number of runs made by a player by entering his score in each match. Different players may have different number matches.

Solution:

  1. The problem looks easy initially. We just enter the score and add them into total but the tricky part is how many times to enter the score.
  2. First, we ask how many numbers of matches are played, then we set up the loop for it.
  3. Pseudocode be like
  4. Enter the number of matches played.
  5. Set a variable for the match number. Start from 1.
  6. Set a variable for total runs to 0.
  7. The loop condition will go up to matches played.
  8. In each iteration we enter the number of runs scored.
  9. Number of runs will add to total runs
  10. After the loop we will print the total number of runs.
matches = int (input ("Enter the number of matches: "))total_runs = 0match_no = 1while match_no <= matches:    runs = int (input (f"Enter the runs scored in match {match_no}: "))    total_runs += runs    match_no += 1 print (f"The total runs scored in {matches} matches is: {total_runs}")

Code 6: Using Variable Condition

  1. First, we enter the total number of matches in the matches variable.
  2. For example, if a user entered 7 matches then the loop should iterate 7 times.
  3. Conditions in the while loop will produce True because 1 is less than 7.
  4. We enter the loop where it will ask the score of match number 1.
  5. Let the user enter 37.
  6. Next this 37 will add to total_runs and next an increment in match number.
  7. The loop is ending on the next line so we jump back to the while condition.
  8. This time we have 2 which is still less than 7 and we will again enter the loop.
  9. Again, ask the score of match number 2 and the user enters 20.
  10. 20 will be added to total_runs and now total_runs will become 57.
  11. Again, increment in match_no and again the condition will True.
  12. The loop will continue up to 7 times.
  13. For any other player, the user can enter a number of matches 20. Now this time loop will iterate 20 times.

Example 3: Write a program that takes 10 numbers as input and find how many numbers are even and how many or odd.

Solution:

  1. First, the pseudocode
  2. Set a variable to 1.
  3. Create two variables for even and odd counters and set them on 0.
  4. Set the condition of the loop up to 10 for this variable.
  5. In the loop, input a number from the user.
  6. Check that the number is even (divided by 2).
  7. If the number is even then increment in the even counter.
  8. Else increment in odd counter.
index = 1even_counter = 0odd_counter = 0while index <= 10:    num = int (input (f"Enter number: "))    if (num % 2) == 0:        even_counter += 1      else:        odd_counter += 1    index += 1print (f"Even numbers count: {even_counter}")print (f"Odd numbers count: {odd_counter}")

Code 7: Using if-else inside Loop

  1. You can also use loop structure in if-else and match and similarly, match-case and if-else can be used inside the loop.

Example 4: Write a program that finds the sum of input values entered by the user. The total values are indefinite.

Solution:

  1. The problem is very small but quite tricky. You have to find the sum of numbers but it is not defined how many numbers will enter by user. Users may want to calculate the sum of 5 numbers like 2, 7, 3, 5, 1 or may want to sum 3 numbers like 6, 6, 9 or any other list of numbers.
  2. We cannot set the while condition on limit and increment.
  3. We have to create some tricks for it.
  4. Pseudocode be like this
  5. Create a variable named “Choice” or “Option” and set it to “y”. This is a string variable.
  6. Create a variable named “Total” and set to 0.
  7. In while set the condition that is always True.
  8. We are in loop and we will add this number to Total.
  9. Now we will enter next number with y for yes and n for no.
  10. Next, we can an if condition that will check the value of choice string with y.
  11. If it produces True then we should continue the while loop and keep asking the number.
  12. Else we break to loop immediately and print the Sum.
sum = 0while True:    num = int (input ("Enter a number: "))    sum += num    choice = input ("Do you want to add another number? (y/n): ")    if (choice == "y"):        continue    else:        breakprint (f"The total sum is: {sum}")

Code 8: Using String as Condition and Use of continue and break

Figure 3: Output of Code 8

  1. We can see that the first user entered the number 6.
  2. They asked “Do you want to add another number? (y/n): ” and y was entered.
  3. It again asked the number, this time 4 entered and continue the program with y
  4. Next, 8 was entered and entered n to stop the program.
  5. Finally, it printed 18 which is the sum of 6, 4 and 8.

Leave a Reply

Your email address will not be published. Required fields are marked *