For-Loop

For-Loop#

A for-loop repeats a block of code for a given amount.

The for-loop in combination with range() iterates over a range of numbers. For each iteration, the current number is stored in a variable.

for i in range(3):
    print(i)
0
1
2

Commonly, variables that act like an index are named i or index, but it’s possible to give them other names.

for a in range(2, 5):
    print(a)
2
3
4
# Code without the loop

from fpdf import FPDF

pdf = FPDF(format=(115, 180))
pdf.add_page()
pdf.set_font('helvetica', size=48)
pdf.cell(text="hello world")
pdf.output("pdfs/hello_world.pdf")
# Code with a for loop

from fpdf import FPDF

pdf = FPDF(format=(115, 180))

for i in range(4):
    # Everything inside this code block will be
    # repeated 4 times. 
    pdf.add_page()
    pdf.set_font('helvetica', size=48)
    pdf.cell(text="hello world")
    
# This happens after the 4 iterations of the for-loop
pdf.output("pdfs/hello_world.pdf")

003.png

Loop (iterate) over a list#

l = [5, "hello", -1.5, "🐍", "πŸ•"*9]

for item in l:
    print(item)
5
hello
-1.5
🐍
πŸ•πŸ•πŸ•πŸ•πŸ•πŸ•πŸ•πŸ•πŸ•
from fpdf import FPDF

pdf = FPDF(format=(115, 180))

words = ['hello', 'world', '!']

# Loop over the list of words
for word in words:
    # in every loop, the next item from the list is stored in the variable word
    pdf.add_page()
    pdf.set_font('helvetica', size=48)
    pdf.set_y(70)
    pdf.multi_cell(w=0, text=word, align='C')
    
# This happens after the 4 iterations of the for-loop
pdf.output("pdfs/hello_world.pdf")

loop over a list