Our Python articles also frequently mentioned the
for loop when solving problems. Today we will introduce
for loop in more detail to you through for loop in Python examples. Continue reading the article to know more.
The for loop in Python examples for beginners
Below, we’ll show you the
for loop examples in Python that even a beginner can understand.
Loop through a string
for loop is used to iterate through iterable objects such as lists, tuples, and even strings.
We can use the
for loop with a string like this:
string = "learnshareit.com" for char in string: # Print in the same line print(char, end = " ")
l e a r n s h a r e i t . c o m
You can do the same with a list or tuple like the one below.
Loop through a list of numbers
The list data type is the most common type for storing multiple values. We can use
for loop to iterate through a list as follows:
score = [1, 3, 4, 2, 3, 9, 11] total = 0 for num in score: # Get the sum of the numbers in the list total += num print("Total: ", total)
continue keywords in the Python loop
Like their name, the break keyword stops the loop before iterating over all the elements. The continue keyword skips the current loop to jump to the next loop.
Suppose we want to get the sum of even numbers in a list. If their sum exceeds 20, we will stop the loop. Here is how:
numbers = [1, 3, 4, 2, 3, 8, 11, 8] total = 0 for num in numbers: # If num is odd -> jump to the next loop if num % 2 != 0: continue # Get the sum total += num # If total > 20 -> back to the previous value and stop the loop if total > 20: total -= num break print("Total: ", total)
for loop with
for(i = 0; i < list.length; i++) Do you find it familiar?
In Python, we have the same way, but the syntax is much easier to see and read using range() in combination with len(). Like this:
We can use the
for loop in combination with Comprehension in Python to quickly create data structures like list, set, and dict. Here’s how to use a
for loop with List Comprehension to quickly create a list object.
# Use for loop and List Comprehensions to create a list object listObj = [i for i in range(1, 11)] print(listObj)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python for loop tutorials
You can learn more about Loop in Python in the articles below:
- Count in a for loop in Python
- For loop 1 to 10 in Python
- Foreach in python
- Exit for loop in python
- Python loop through files in directory
- What does for i in range len mean in Python?
- How to count in a for loop in Python
- How to Iterate through a Queue in Python
That’s all for the
for loop examples. We hope the above examples have given you a better understanding of for loop in Python examples. Regularly visit LearnShareIT to learn new knowledge about Python.
Name of the university: HCMUE