Create a python programming using looping and counting

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.

Video: Python while Loop

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:
    Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Flowchart of while Loop

Create a python programming using looping and counting
Flowchart for while loop in Python

Example: Python while Loop

# Program to add natural
# numbers up to 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).

We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).

Finally, the result is displayed.


While loop with else

Same as with for loops, while loops can also have an optional else block.

The else part is executed if the condition in the while loop evaluates to False.

The while loop can be terminated with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.

'''Example to illustrate
the use of else statement
with the while loop'''

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the fourth iteration, the condition in while becomes False. Hence, the else part is executed.

Table of Contents

  • What is while loop in Python?
    • Syntax of while Loop in Python
    • Flowchart of while loop
    • Example: Python while Loop
  • While loop with else

The following program counts the number of times the letter “r” appears in a string:

Activity: CodeLens 7.6.1 (strCount)

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an “r” is found. When the loop exits, count contains the result: the total number of r’s.

    11-9-2: What is printed by the following:

    s = "peanut butter"
    count = 0
    for char in s:
        if char == "t":
              count = count + 1
    print(count)
    

  • 0
  • Incorrect! count is initialized to 0, but is then incremented by the for loop. Try again.
  • 3
  • Correct! The letter t appears 3 times in "peanut butter".
  • 4
  • Incorrect! The value of count is initially 0, not 1. Try again.
  • Nothing, this is an infinite loop
  • Incorrect! This for loop will eventually terminate because string s has a finite number of characters. Try again.

There are four errors in the following code. Fix the function so it takes a string and a character as arguments and returns the count of the character within the string.

In line 2, lettercount should be initialized to 0. In line 4, there should be a ==, not a =. In line 5, the variable name should be changed to lettercount. In line 6, the return statement should be indented.

You have attempted of activities on this page

How do you do a counting loop in Python?

Use the enumerate() function to count in a for loop, e.g. for index, item in enumerate(my_list): . The function takes an iterable and returns an object containing tuples, where the first element is the index, and the second - the item.

How do you write a loop program in Python?

Basic Syntax of the Python for loop.
The first word of the statement starts with the keyword “for” which signifies the beginning of the for loop..
Then we have the iterator variable which iterates over the sequence and can be used within the loop to perform various functions..

Which Python loop is a counting loop?

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.

What is looping and counting in programming?

Looping-In this technique, the program is. instructed to execute certain set of. instructions repeatedly to execute a particular task number of times.  Counting-This technique allows programmer. to count how many times the instruction/set.