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
Exchange Vanilla Gift Card for Cash
Workforce Management Software News, Blog, and Resources
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Winston Salem Nc Craigslist
Craigslist Mpls Mn Apartments
La connexion Ć  Mon Compte
Eric Rohan Justin Obituary
Apply A Mudpack Crossword
1TamilMV.prof: Exploring the latest in Tamil entertainment - Ninewall
Caroline Cps.powerschool.com
Slmd Skincare Appointment
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
House Party 2023 Showtimes Near Marcus North Shore Cinema
Luna Lola: The Moon Wolf book by Park Kara
Grasons Estate Sales Tucson
Vanessa West Tripod Jeffrey Dahmer
Idaho Harvest Statistics
Best Forensic Pathology Careers + Salary Outlook | HealthGrad
Niche Crime Rate
Jayah And Kimora Phone Number
Everything you need to know about Costco Travel (and why I love it) - The Points Guy
Aaa Saugus Ma Appointment
Acts 16 Nkjv
Best Transmission Service Margate
8005607994
Hood County Buy Sell And Trade
Raw Manga 1000
Beaufort 72 Hour
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Bfsfcu Truecar
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
Star News Mugshots
ShadowCat - Forestry Mulching, Land Clearing, Bush Hog, Brush, Bobcat - farm & garden services - craigslist
Kagtwt
Sitting Human Silhouette Demonologist
Litter-Robot 3 Pinch Contact & DFI Kit
Agematch Com Member Login
To Give A Guarantee Promise Figgerits
Go Smiles Herndon Reviews
Raisya Crow on LinkedIn: Breckie Hill Shower Video viral Cucumber Leaks VIDEO Click to watch fullā€¦
Unifi Vlan Only Network
Discover Wisconsin Season 16
Vons Credit Union Routing Number
Yakini Q Sj Photos
Thothd Download
Pgecom
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Lesson 5 Homework 4.5 Answer Key
Shannon Sharpe Pointing Gif
Zom 100 Mbti
When Is The First Cold Front In Florida 2022
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.