Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Loops (for, while) and iterating through sequences.


Tutorial 3.2 - Control Flow

Loops (for, while) and Iterating through sequences.

Loops are used in Python to execute a block of code repeatedly. There are two main types of loops: for loops and while loops. Both types of loops can be used to Iterate through sequences such as lists, strings, and ranges. Let's explore how to use these loops with detailed examples:

1. for Loop:

The for loop is used to iterate over a sequence (like a list, string, or range) and execute a block of code for each element in the sequence.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

2. for Loop with Range:

You can also use the range() function to generate a sequence of numbers and iterate over it using a for loop.

for num in range(1, 6):
    print(num)

3. while Loop:

The while loop is used to repeatedly execute a block of code as long as a certain condition remains true.

count = 0 
while count
    print("Count:", count)
    count += 1

4. Iterating Through Strings:

You can use loops to iterate through each character in a string:

word = "Python"

for letter in word:
    print(letter)

5. Iterating Through Dictionaries:

You can also use loops to iterate through dictionaries, where you'll get the keys by default. If you need both keys and values, you can use the .items() method.

person = {"name": "Alice", "age": 30}

for key in person:
    print(key, ":", person[key])


Or, using
.items():


for key, value in person.items():
    print(key, ":", value)

6. break and continue:

  • The break statement is used to exit a loop prematurely when a certain condition is met.
  • The continue statement is used to skip the current iteration and proceed to the next one.
for num in range(10):
    if num == 5: 
        break 
    print(num)
 
for num in range(10):
    if num == 5:
        continue
    print(num)

Loops are fundamental for automating repetitive tasks and processing collections of data. Whether you're iterating through sequences or executing code conditionally, loops allow your programs to perform tasks efficiently and effectively.


This post first appeared on Tsarde, please read the originial post: here

Share the post

Python Loops (for, while) and iterating through sequences.

×

Subscribe to Tsarde

Get updates delivered right to your inbox!

Thank you for your subscription

×