I am wondering if there is any way to use if
-statement in one cell, then use elif
in another cells, then use else
in the final cell, in google colab.
The reason not to have all code in one cells is because I want to add text cells for each if
case.
for the same concept, can I do it with while
and for
loop. for example in while
loop, original code as following:
while True:
print('this is my first job)
print('this is my second job)
in colab, isn't it possible to have this in one cell:
while True:
print('this is my first job)
then this for another cell?
print('this is my second job)
another example on for
loop, this is the original code:
for n in range(100):
print(n + 10)
print(n + 20)
in colab, then I want one cell include:
for n in range(100):
print(n + 10)
another cell includes, possible?
print(n + 20)
No, you can't do this.
Google colab is basically just a IPython Notebook, and each executable cell must be a valid "chunk" of python code on it's own. The first "chunk" would be valid, but subsequent "chunks" would not be valid, because the interpreter assumes each cell starts at the minimum indent level. Take the following example:
if False:
print('false')
print('how did we get here?')
running each cell sequentially might make this seem to make sense, but "how did we get here" will always print, where "false" will not. The kernel cannot assume the second cell is associated with the first because notebooks are inherently designed to be run out of order if desired. Therefore, the starting indent level for a cell is just taken to be the "module" level in terms of call stack. Consider if you tried to run this cell first:
print('this should print if True')
elif False:
print('this should print if False')
What should the interpreter do if this is the first piece of code it sees? it will return an error, because "un-indenting" is analogous to popping a stack frame, and there is no frame to pop in this instance.