top of page
  • Andrew Jones

HOW TO: Python - Your first For Loop


For our post on For Loop's in R - click here!

 

In many programming languages, For Loops are used to repeat a specific block of code. Many programmers refer to the 'DRY' principle (Don't Repeat Yourself!) as a best practice, and this will help ensure you don't!

Imagine this simple scenario - you want to print out a list of text showing increasing page numbers in a book

You could do this manually, like below:

print("The page number is", 1)

"The page number is 1"

print("The page number is", 2)

"The page number is 2"

print("The page number is", 3)

"The page number is 3"

print("The page number is", 4)

"The page number is 4"

print("The page number is", 5)

"The page number is 5"

This works fine and gives you exactly the output you wanted, but what if instead of 5 pages would wanted to print 500 pages - it now becomes very time consuming

Instead, let's make Python do all the hard work by putting in place a For Loop

for page_number in (1,2,3,4,5): print("The page number is", page_number)

"The page number is 1"

"The page number is 2"

"The page number is 3"

"The page number is 4"

"The page number is 5"

In the scenario we mentioned above, where we needed 500 pages listed, it's just as easy!

for page_number in range (1,501): print("The page number is", page_number)

"The page number is 1"

"The page number is 2"

"The page number is 3"

....

....

"The page number is 499"

"The page number is 500"

That was a basic run through of a For Loop in Python, if it was helpful, please share!

For our post on For Loop's in R - click here!

52 views0 comments

Recent Posts

See All
bottom of page