Loops
(Read time is about 2 minutes)
Computers love to do the same/simular task over and over again.
Unlike Humans, Computers will do the exact same thing without making mistakes. (Unless there is another mistake, commonly called a programming error)
So what can we do with a loop?
my_list = [0, 1, 2, 3, 4, 5, 6, 7.0, 8, "9"]
for l in my_list:
if type(l) == type(0.0):
print(f"I found {l} to be a {type[0.0]}")
else:
print(f"I found {l} to not be type {type[0.0]} but type {type(l)}")
I found 0 to not be type <class 'float'> but type <class 'int'>
I found 1 to not be type <class 'float'> but type <class 'int'>
I found 2 to not be type <class 'float'> but type <class 'int'>
I found 3 to not be type <class 'float'> but type <class 'int'>
I found 4 to not be type <class 'float'> but type <class 'int'>
I found 5 to not be type <class 'float'> but type <class 'int'>
I found 6 to not be type <class 'float'> but type <class 'int'>
I found 7.0 to be a <class 'float'>
I found 8 to not be type <class 'float'> but type <class 'int'>
I found 9 to not be type <class 'float'> but type <class 'str'>
So before you get ready to close the page due to complete confusion lets start by breaking this down...
We have the list
my_list = [0, 1, 2, 3, 4, 5, 6, 7.0, 8, "9"]
There are different types inside this list that I am having python display...
I am itterating over the list using for itterator_name in my_list
for l in my_list:
# Notice the 4 spaces, this tells python these lines are inside the for loop!
If I print(l) we would get the following...
0
1
2
3
4
5
6
7.0
8
9
Next we have the If and Else statement comparing the type of our itterator to the float type...
# Still in the for loop so 4 spaces for each line!
if type(l) == type(0.0):
# Another 4 spaces to indicate we are inside the if.
print("Float")
else:
# This is inside the else not the if!
print(type(l))
This has been simplified so I can keep this shorter.
Next we will talk about Files