- Home
- About us
- Contact us
- Sitemap
- Disclaimer
- Privacy Policy
- Terms and Condition
-
Settings
- Dark mode
for loop in python for beginners part -1
for loops
A for loop acts as an iterator in Python; it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.
We've already seen the for statement a little bit in past lectures but now let's formalize our understanding.
Here's the general format for a for loop in Python:
for item in object:
statements to do stuff
The variable name used for the item is completely up to the coder, so use your best judgment for choosing a name that makes sense and you will be able to understand when revisiting your code. This item name can then be referenced inside your loop, for example, if you wanted to use if statements to perform checks.
Let's go ahead and work through several examples of for loops using a variety of data object types. We'll start simple and build more complexity later on.
Example 1
list1 = [1,2,3,4,5,6,7,8,9,10]
for num in list1:
print(num)
OUTPUT
1
2
3
4
5
6
7
8
9
10
Great! Hopefully, this makes sense. Now let's add an if statement to check for even numbers. We'll first introduce a new concept here--the modulo.
Modulo
The modulo allows us to get the remainder in a division and uses the % symbol. For example
# This makes sense since 17 divided by 5 is 3 remainder 2
17 % 5
# 3 Remainder 1
10 % 3
# 2 Remainder 4
18 % 7
# 2 no Remainder
4 % 2
OUTPUT
2
1
4
0
Notice that if a number is fully divisible with no remainder, the result of the modulo call is 0. We can use this to test for even numbers since if a number modulo 2 is equal to 0, that means it is an even number!
Back to the for loops!
Example 2
for num in list1:
if num % 2:
print(num)
OUTPUT
2
4
6
8
10
We could have also put an else statement in there:
for num in list1:
if num % 2:
print(num)
else:
print("Odd Number")
OUTPUT
Odd Number
2
Odd Number
4
Odd Number
6
Odd Number
8
Odd Number
10
Post a Comment
Post a Comment
if you have any doubts, please let me know