DEV Community

Cover image for Looping in Python
Elijah Macharia
Elijah Macharia

Posted on

Looping in Python

Introduction to loops.

A loop is a series of commands that repeat continuously until a certain condition is reached. This allows you to continuously run the same code multiple times or repeat a subroutine until a stopping condition is met.

loops come in many different types, and each programming language has its own syntax.
The
loops have one thing in common.

Stop condition. This condition is checked each time and the loop continues running until the condition is reached.
Python has two types of loops.

  1. The For Loop is used to determine how many times you want to repeat a block of code. It is used to perform certain actions a certain number of times.
Example
fruits = ["Apples", "Oranges", "Banana"]
for i in fruits:
    print(i)
Enter fullscreen mode Exit fullscreen mode

Note 'i' is a variable assigned to Fruits.

Output:

Apples
Oranges 
Banana
Enter fullscreen mode Exit fullscreen mode
2.While Loop

A while loop is a type of loop in Python that allows you to repeat a block of code until a certain condition is met. The syntax for a while loop is:

while condition:
    # do something
Enter fullscreen mode Exit fullscreen mode

In this syntax, a "condition" is a boolean expression that is evaluated on each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop ends and the program moves to the next line of code.

The body of the while loop can contain any number of statements, just like any other block of code. This can include conditional statements, function calls, I/O operations, and other types of statements for use in Python code.
One important thing to keep in mind when using a while loop is that the condition must eventually be false. Otherwise the loop will continue indefinitely and the program will crash. This is called an infinite loop and is generally considered a bug in the code.

Here is an example of a while loop that repeatedly prompts the user for input until input is complete.

user_input = ""
while user_input != "quit":
    user_input = input("Enter a word (or 'quit' to exit): ")
    print("You entered:", user_input)
print("Goodbye!")
Enter fullscreen mode Exit fullscreen mode

In this example, the while loop continues prompting the user for input until input is complete. As soon as the input becomes "exit", the loop exits and the message "Goodbye!" appears. It prints to the console.

The While Loop is a powerful tool in Python programming that allows you to write more flexible and dynamic code. It can be used in a variety of applications, from processing user input to game loops and simulation programs.

Top comments (0)