3 Looping with for
Looping with for
¶
So far, we have covered creating variables of different types and if statements.
Now we want to try looping some code with the keyword for
We will start with a simple example using a List of [3, 5, 7, 9]
for i in [3, 5, 7, 9]:
print('i is:', i)
i is: 3 i is: 5 i is: 7 i is: 9
The list could also come from a variable!
aList = [3, 5, 7, 9]
for i in aList:
print('i is:', i)
i is: 3 i is: 5 i is: 7 i is: 9
When we write
for i in [3, 5, 7, 9]:
print('i is:', i)
Python will step
over the values in the list and assign i
to the value at each step
.
In the above examples, what is this i
? Well it is just a vraiable name we create.
Here is an example where we use something other than i
.
aList = [3, 5, 7, 9]
for oneItem in aList:
print(oneItem)
3 5 7 9
Is a string a list?¶
Python is incredibly flexible. For example, a string can be treated like a list.
This makes sense? A string is just a list of characters.
aString = 'abcdefg'
for oneCharacter in aString:
print(oneCharacter)
a b c d e f g
# We can also access a string using our list index with []
aString = 'abcdefg'
print(aString[2])
c
Built in functions like range()¶
We have been using some built in function in Python. Things like if ... else
and print()
.
For looping there is one very useful built in function named range(int)
. Range takes an integer value and returns a list from 0 up to value-1.
Here are some examples.
for i in range(5):
print('i is:', i)
range(0, 5) i is: 0 i is: 1 i is: 2 i is: 3 i is: 4
# range can of course take an integer variable that we define
myRange = 3
for i in range(myRange):
print('i is:', i)
i is: 0 i is: 1 i is: 2
Can range(int) take a float? If your not sure, just test it out!
myFloat = 3.14
for i in range(myFloat):
print('i is:', i)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/cudmore/Dropbox/teaching-2023/iot-fall-2023/docs/docs/3.looping.ipynb Cell 13 line 2 <a href='vscode-notebook-cell:/Users/cudmore/Dropbox/teaching-2023/iot-fall-2023/docs/docs/3.looping.ipynb#X16sZmlsZQ%3D%3D?line=0'>1</a> myFloat = 3.14 ----> <a href='vscode-notebook-cell:/Users/cudmore/Dropbox/teaching-2023/iot-fall-2023/docs/docs/3.looping.ipynb#X16sZmlsZQ%3D%3D?line=1'>2</a> for i in range(myFloat): <a href='vscode-notebook-cell:/Users/cudmore/Dropbox/teaching-2023/iot-fall-2023/docs/docs/3.looping.ipynb#X16sZmlsZQ%3D%3D?line=2'>3</a> print('i is:', i) TypeError: 'float' object cannot be interpreted as an integer
Nope, range(int) can not take a float. The error is actually informative, it tells us that range(int) by its definition is expecting an int
value variable.
TypeError: 'float' object cannot be interpreted as an integer
Tutorial¶
- Make a list of 5 float numbers.
- Write a for loop to print out each items value.
# add you code here (press run in the top toolbar to run your code)