Easily Repeat Tasks Using Loops (2024)

When to Use Loops

In programming, there are sets of instructions you will need to repeat multiple times. For example, if you want to perform the same task on every item in a list. What if you have a list of campaigns, andyou want to printevery one of them?

When you need to repeat a set of instructions, sometimes you know the number of repetitions in advance; other times, you don't. Thereare also times when the number ofrepetitions does not matter, and you want to repeat the code until a certain condition is met.

For all of these purposes, you use loops.

The for Loop

Theforloop is the core type of looping in Python. A for loop is used to iterate over any sequence. That can be a list, tuple, dictionary, or even a string. With a for loop, you can execute the same code for each element in that sequence.

Python makes it very easy to loop through every element of a sequence. If you want to print every element in a list, it will look like this:

dog_breeds = ["golden retriever", "chihuahua", "terrier", "pug"]for dog in dog_breeds: print(dog)

In this code, each element in dog_breeds willbe printed to the terminal. dogis a variable name that updates to be the next element every time the loop repeats. Theoretically,you could change dog to co*ckadoodledoo and it would still perform the same functionality.

Easily Repeat Tasks Using Loops (1)

You can do the same type of for loop if you want to loop over every character in a string.

To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.

for x in range(5): print(x)

This code will print 0, 1, 2, 3, 4 sequentially.

for x in range(100): print(f"{x} bottles of beer on the wall!")

The curly brackets {} here will take whatever value is in variablexand put it in its place. So in this example, the code will print:

0 bottles of beer on the wall!1 bottles of beer on the wall!…99 bottles of beer on the wall!

The range() function defaults to 0 as a starting value, but you can changeit by adding another integer like so: range(4, 10)!

This range would return values from 4 to 10 (but not including 10).

The while Loop

While theforloop lets you execute code a certain specified number of times, thewhileloopkeeps executing until a certain condition is met.

In the previous chapter,you learned about conditions as statements that evaluate to true or false. The same applies here: code within a while statementwill keep executing until the condition becomes false.

The code snippet below checks the current capacity and increases it by 1 until the maximum capacity is reached (+= 1increases the current value by 1).

maximum_capacity = 10current_capacity = 3while current_capacity <= maximum_capacity: current_capacity += 1

Because the current_capacity starts at 3, this code executes 7 times until current_capacity hits 10.

Easily Repeat Tasks Using Loops (2)

It’s important to be aware of infinite loops. If the condition you set is always true, the loop will continue to run forever!

For example:

x = 0while x != 5: x += 2

In this situation, x will never hit 5!

Level-Up:Loop-the-Loop

Easily Repeat Tasks Using Loops (3)

Context:

Now you are going to write a program that calculates various statistics for a set of numbers provided by the user. This task will allow you to review lists and address the new concept of this chapter: loops.

Instructions:

  1. Ask the user to enter a list of numbers separated by commas (e.g., 1,2,3,4), and display this list.

  2. Calculate and display the sum of the numbers in the list.

  3. Calculate and display the average of the numbers in the list.

  4. Calculate and display the number of numbers in the list that are greater than the average.

  5. Calculate and display the number of numbers in the list that are even.

Once you have completed the exercise, you can run the following command in the VS code terminal pytest tests.py

Let’s Recap!

  • Loops let you easily repeat tasks or execute code over every element in a list.

  • Afor loop enables you to repeat code a certain amount of time.

  • Awhile loop lets you repeat code until a certain condition is met.

Loops are great to help you repeat code easily. Next, we’ll dive into functions; another way to help you bundle repeatable tasks.

Easily Repeat Tasks Using Loops (2024)
Top Articles
10 signs of dehydration you need to know | GoHealth Urgent Care
6 Brilliant Ways to Open Stubborn Jars
Lakers Game Summary
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Splunk Stats Count By Hour
Federal Fusion 308 165 Grain Ballistics Chart
Craigslist Portales
Coffman Memorial Union | U of M Bookstores
Txtvrfy Sheridan Wy
The Potter Enterprise from Coudersport, Pennsylvania
Nyuonsite
Mivf Mdcalc
Craigslist Greenville Craigslist
Driving Directions To Atlanta
Teenleaks Discord
Sport-News heute – Schweiz & International | aktuell im Ticker
Stardew Expanded Wiki
Fort Mccoy Fire Map
Little Caesars 92Nd And Pecos
Wbiw Weather Watchers
About My Father Showtimes Near Copper Creek 9
SOGo Groupware - Rechenzentrum Universität Osnabrück
Gillette Craigslist
Visit the UK as a Standard Visitor
Tripcheck Oregon Map
Dairy Queen Lobby Hours
Otis Offender Michigan
Graphic Look Inside Jeffrey Dresser
Plato's Closet Mansfield Ohio
2015 Chevrolet Silverado 1500 for sale - Houston, TX - craigslist
The Ride | Rotten Tomatoes
Truckers Report Forums
Helloid Worthington Login
Ljw Obits
Craigs List Stockton
Can You Buy Pedialyte On Food Stamps
20 Best Things to Do in Thousand Oaks, CA - Travel Lens
Game8 Silver Wolf
Pp503063
Myanswers Com Abc Resources
8 Ball Pool Unblocked Cool Math Games
2020 Can-Am DS 90 X Vs 2020 Honda TRX90X: By the Numbers
T&Cs | Hollywood Bowl
Alba Baptista Bikini, Ethnicity, Marriage, Wedding, Father, Shower, Nazi
Ts In Baton Rouge
Cvs Coit And Alpha
Jimmy John's Near Me Open
25 Hotels TRULY CLOSEST to Woollett Aquatics Center, Irvine, CA
Ajpw Sugar Glider Worth
Congressional hopeful Aisha Mills sees district as an economical model
Morgan State University Receives $20.9 Million NIH/NIMHD Grant to Expand Groundbreaking Research on Urban Health Disparities
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 6149

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.