For-Loops in Python - Data Science Discovery (2024)

← Random Numbers in Python Next: Simple Simulations in Python →

In all of the Python programs we've seen so far, the computer executes the commands one line at a time, from top to bottom. However, most programming languages contain several powerful features that can change the flow of the program. These statements that alter the flow of a program are called control flow statements. One such control flow statement is the ability to iterate--to repeat parts of the code.

Python uses a for-loop to repeat the same block of code a set number of times. Below is a for-loop that repeats three print statements five times (and then prints Bye exactly once):

for i in range(5): print("Data") print("Science") print("DISCOVERY")print("Bye")

There are a few features to notice:

  • The line of code with the for statement ends in a colon (:). This colon indicates that the next block of code should be repeated a number of times.
  • The number of times the for-loop repeats in indicated in what appears after the in statement. In the code above, range(5) runs the code inside of the for-loop five times.
  • The block of code following the for statement is indented. This indentation defines the block of code that should run multiple times and we refer to this code as being "inside" of the for-loop.
  • The code after the for-loop, back at the original indentation, will only run after the for-loop finishes running.
for i in range(5): print("Data") print("Science") print("DISCOVERY")print("Bye")

The output of your first for-loop!

Application of for-loops: Simulation

A simple and widely used application is to re-run a simulation multiple times and these for-loops nearly always use for i in range(17) (where 17 is replaced with the number of times our simulation runs).

  • range(17) is shorthand for listing out a long sequence of numbers starting with zero and going to one less than the end of the range -- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -- that will be "looped through" by the for-loop.
  • The variable i will take on each of these each time it goes through the loop. Even if we never use i, it's still required syntax in our for-loop.

Example: Printing i in a for-loop

# Notice the use of `range(17)` to run this code 17 times:for i in range(17): print(i)
012345678910111213141516

Ten cards randomly drawn (with replacement) using a for-loop.

Simulation Example: Repeating Rolling a Die

When we discussed generating Random Numbers in Python, we explored generating 100 rolls of a six-sided die. Now we can do this in just two lines of code:

# Notice the use of `range(100)` to run this code 100 times:for i in range(100): print(random.randint(1, 6))
1436633353546243254163413241663624233131335242355552411126616354125141553324452526365252516533255422

One hundred randomly generated numbers using random.radint(1, 6), using a for-loop.

Simulation Example: Drawing 10 Cards (with replacement)

# Notice the use of `range(10)` to run this code 10 times:for i in range(10): rank = random.choice( ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] ) suit = random.choice( ["Club", "Heart", "Diamond", "Spade"] ) print(f"{rank} of {suit}s")
5 of Hearts2 of DiamondsA of Spades3 of SpadesJ of Clubs8 of Spades2 of Hearts10 of DiamondsA of ClubsK of Clubs

Ten cards randomly drawn (with replacement) using a for-loop.

Application of for-loops: Iteration

The other major common application of a for-loop is to iterate through a list. This can be done using a Python list, such as the lists we use in random.choice. Instead of using i, the variable used between for and in should be descriptive of the data that it will contain. If we are looping through a list of suits of cards, the variable suit makes a lot of sense.

Iteration Example: Python List of Card Suits

# Notice the variable `suit` and the list of all suits:for suit in ["Club", "Heart", "Diamond", "Spade"]: print(suit)
ClubHeartDiamondSpade

Using a for-loop to visit every element in a Python List.

Iteration Example: Python List of Primary and Secondary Colors

# Notice the variable `color` and the list of primary and secondary:for color in ["Red", "Yellow", "Blue", "Orange", "Green", "Violet"]: print(color)
RedYellowBlueOrangeGreenViolet

Using a for-loop to visit every element in a Python List.

Video 1: Examples of "for" Loops in Python

Follow along with the worksheet to work through the problem:

  • Download Blank Worksheet (PDF)

Q1: Looking at the snippet of code below, how many times will the for loop execute? For-Loops in Python - Data Science Discovery (1)

Q2: Looking at the image below, which snippet of code will incorrectly print the list `data`? For-Loops in Python - Data Science Discovery (2)

← Random Numbers in Python Next: Simple Simulations in Python →

`); } else { $e.prop("disabled", true); $e.html((i, html) => "❌ " + html); $e.after(`

Try Again. ${d.comment}

For-Loops in Python - Data Science Discovery (2024)
Top Articles
Upgrade WCF application to .NET 6.0 - Microsoft Q&A
Choosing between Human Life and Cultural Heritage in War
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6441

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.