In computer science, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met. Programmers use loops to cycle through values, add sums of numbers, repeat functions, and many other things.
Loops are supported by all modern programming languages, though their implementations and syntax may differ. Two of the most common types of loops are the while loop and the for loop.
Python Loops
Python has two primitive loop commands:
- while loops
- for loops
Python while Loop
A while loop is the simplest form of a programming loop. It states that while a condition is valid, keep looping
With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i = i + 1
Note: remember to increment i, or else the loop will continue forever.
Python For Loop
Example
Print each name in a name list:
name = ["one", "two", "three"]
for x in name:
print(x)
for x in name:
print(x)
Looping Through a String
for x in "banana":
print(x)
print(x)
Tags:
python