Cool Computer Science Thing of the Day
Reading Questions
Quiz
Emacs Tip of the Day
- M-/ auto complete
Nested Loops
Can put any code you want inside of a loop, including another loop
for i in range(2): for j in range(3): print(i, j)
- This is useful when dealing with information in a grid, spreadsheets, simulations, or images
Where nested loops get a bit more tricky is when the inner loops uses the outer loop’s iterator variable
for i in range(1, 4): for j in range(i): print(i, j)
Print Options
- Have your tried to put a comma after a variable or a period at the end of a sentence when printing?
- For example:
print('the result is', result, '.')
- There is a space between the value and the period
- The documentation for the print function lists a couple of optional arguments
sep
specifies what separates each thing that is printed- It defaults to a space, ‘’, but we can set it to be the empty string, ’’
- So the above example becomes
print('the result is ', result, '.', sep='')
- Note we now need a space in the string before the result because we lost that space as well.
- The print function also always gives a new line, sometimes you don’t want that.
- The
end
argument lets you change that. - For example,
print(i, j, end='')
will put all print statements on one line - This is useful when working with a loop.
- But how do you get a new line when you are done?
- What if you are nesting and want new lines in the outer loop?