Python While Loops/For Loops

JK JK 2038 
Created at
Updated at  
7,556 0 0

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
  print(i)
  i += 1

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.

 

The break Statement

With the break statement we can stop the loop even if the while condition is true:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

 

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

 

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

The for loop does not require an indexing variable to set beforehand.

 

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

for x in "banana":
  print(x)

 

The break Statement

With the break statement we can stop the loop before it has looped through all the items:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)

 

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

 

The range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

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

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

for x in range(2, 6):
  print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

for x in range(2, 30, 3):
  print(x)

 

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

for x in range(6):
  print(x)
else:
  print("Finally finished!")

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")

Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:
  pass

 

Below YouTube content is also helpful for better understanding:

Tags Python Python For Loops Python While Loops break continue Facebook X
Comments 0
Similar posts
  1. Python Functions
    7,089
  2. Python Conditions and If statements
    7,160
  3. Python Lambda
    7,134
  4. Python Arrays
    7,117
  5. Python Classes/Objects
    7,521
  6. Python Dictionaries
    7,094
  7. Python Sets
    7,137
  8. Python Tuples
    7,207
  9. Python Inheritance
    7,223
  10. Python Iterators
    7,142
  11. Python Comparison Operators
    7,299
  12. Python Arithmetic Operators
    7,110
  13. Printing string n times
    7,094
  14. String concatenation by join()
    7,160
  15. Python Lists
    7,398
  16. Python String Operations
    7,480
  17. Python Data Types
    7,494
  18. Python Polymorphism
    7,110
  19. Python Scope
    7,087
  20. Python Modules
    7,138
  21. Python Variables
    7,465
  22. Python Comments
    7,618
  23. Python Syntax
    7,451
  24. Python Getting Started
    7,514
  25. Python Introduction
    7,133
  26. What is Python?
    7,780
  27. Java Switch Statements
    7,453
  28. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,960
  29. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,419
  30. Machine Learning Types and Programming Languages
    7,289
  31. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,994
  32. Mastering Excel Data Manipulation with Python
    7,110
  33. Challenge: One Code Problem Per Day
    1,196
  34. Clean Python Environments: The Power of venv vs. Docker
    978
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    929
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,357
  3. RegExp example in Python to exclude javascript from HTML code
    7,088
  4. Python code to convert from Lunar to Solar
    7,806
  5. Python example to download webpage
    8,723
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    134
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    120
  3. Michael Jackson's Billie Jean
    287
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    121
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    181
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    197
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    221
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    267
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    792
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    409
  11. The Evolution and Production Reality of Agentic AI
    326
  12. How to Activate or Waive Your UIUC Student Health Insurance
    416
  13. Complete Guide to Building a Machine Learning Model
    438
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,530
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    463
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,158
  17. What is Docker? Why is Docker also useful in a development environment?
    718
  18. UIUC 2026-2027 Academic Calendar
    1,815
  19. Open-Source LLMs: The AI Revolution
    881
  20. Resume 2.0: Leveling Up for My First Software Gig
    2,564
  21. Not everyone will understand what this man just did
    2,136
  22. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,722
  23. Unpacking IU's Shopper
    892
  24. Jackie Chan's Police Story: The Action Masterpiece
    764
  25. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,080
  26. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,295
  27. Open Databases for Sex Crime Occurrences in the U.S.
    838
  28. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,984
  29. My First Day at University of Illinois-Urvana Champaign
    1,293
  30. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,293
  31. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,378
  32. Sipping the Stars: My Starbucks Adventure
    9,876
  33. Exciting explore at Sequoia National Park
    7,787
  34. My Life Shot at Death Valley
    1,882
  35. Ip Man fights with Muay Thai Master
    1,052
  36. Mad Clown - Don't Die
    1,152
  37. How to get Student Enrollment and Degree Verification at UIUC
    5,288
  38. LAX Thanksgiving Rush: A Joyful Reunion
    1,013
  39. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,246
  40. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,081
  41. 10CM - To Reach You (너에게 닿기를)
    1,256
  42. Feeling weak? Transform yourself at the UIUC ARC!
    1,669
  43. BOYNEXTDOOR - If I Say I Love You
    1,285
  44. The Future of Software Engineer - AI Engineering
    1,016
  45. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,011
  46. Lie - Legend song by BIGBANG
    7,920
  47. Why ROLLBACK is useful when you work with Google Gemini CLI?
    963
  48. Reimbursement after Vaccination at McKinley Health Center
    1,121
  49. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,058
  50. Common Questions from UIUC school life in terms of CS Program
    1,234