4 Python indenting
Now that we covered logic with if
and looping with for
, we really need to talk about indenting in Python. By indenting, we mean the amount of space before each line in your code.
Python is very strict with how code is indented or how it has spaces (like the space bar on your keyboard).
Here are some examples...
In [1]:
Copied!
# here is some valid code
if 12 == 12:
print('yes that is true')
# here is some valid code
if 12 == 12:
print('yes that is true')
yes that is true
In [2]:
Copied!
# here is some invalid code because of indentation/spacing
if 12 == 12:
print('yes that is true')
# here is some invalid code because of indentation/spacing
if 12 == 12:
print('yes that is true')
Cell In[2], line 3 print('yes that is true') ^ IndentationError: expected an indented block after 'if' statement on line 2
With that second example, we got an error:
IndentationError: expected an indented block after 'if' statement on line 2
Basically, all if
and for
statements have to have correct indentation.
In [1]:
Copied!
# Here is a properly indented for loop
myList = [1,26, 12, 100, 14]
for myItem in myList:
print(myItem)
# Here is a properly indented for loop
myList = [1,26, 12, 100, 14]
for myItem in myList:
print(myItem)
1 26 12 100 14
In [2]:
Copied!
# and here is an inproperly indented for loop
aList = [12, 20, 2, 3000, 3.14]
for anItem in aList:
print(anItem)
# and here is an inproperly indented for loop
aList = [12, 20, 2, 3000, 3.14]
for anItem in aList:
print(anItem)
Cell In[2], line 4 print(anItem) ^ IndentationError: expected an indented block after 'for' statement on line 3
Tutorial¶
Make two variables and write an if statement to check if they are equal.
Make a list and write a for loop to step/iterate through its values and print each value.
In [3]:
Copied!
# add you code here. Remember we have two steps in this tutorial.
# add you code here. Remember we have two steps in this tutorial.