AgerNic.com
WEB DEVELOPER SITE, HTML, CSS, PHP, SQL

Python For Loops


Python Tutorial » Python For Loops

for loops are used when you have a block of code which you want to repeat a fixed number of times or is used to iterate over a sequence as: list, tuple, string or other iterable objects.

Loop continues until we reach the last item in the sequence.

Example: of "if" statement
# Find the sum of all 7 numbers stored in my_numbers list

# List of numbers
my_numbers = [3, 4, 1, 6, 11, 2, 5]

# variable to store the sum
sum = 0

# iterate over the list
for val in my_numbers:
sum = sum+val

  print("The sum of my_numbers is", sum)

Output:
The sum of my_numbers is 32


range() Function - example


The range() function returns a sequence of numbers increments by 1 (as default)

Example: Using the range() function:
for y in range(2, 6):
  print("We goon time %d" % (y))
Output:
We go on time 2
We go on time 3
We go on time 4
We go on time 5


for loop with else - example

A for loop can have an optional else block as well.

Example:

digits = [0, 3, 4, 7, 12]

for i in digits:
print(i)
else:
print("Not element left.")
Output:
0
3
4
7
12
Not element left.


continue Statement

continue statement stop current iteration of the loop

Example: continue statement
names = ["John", "Tom", "Chris", "Ann"]
for x in names:
  if x == "Tom":
   continue
  print(x)
Output:
John
Chris
Ann




Python for loop: index, break, range, list, continue, one line, dictionary , reverse, array, example
Python For Loops - python

Online Editor
ONLINE EDITOR

news templates


COLOR PICKER

news templates
This tool makes it easy to create, adjust, and experiment with custom colors for the web.


HTML Templates
news templates
Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.


CSS HTML Layout
news templates
Find here examples of creative and unique website layouts.


Free CSS HTML Menu
news templates
Find here examples of creative and unique website CSS HTML menu.


0
Online Editor
ONLINE EDITOR

news templates


COLOR PICKER

news templates
This tool makes it easy to create, adjust, and experiment with custom colors for the web.


HTML Templates
news templates
Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.


CSS HTML Layout
news templates
Find here examples of creative and unique website layouts.


Free CSS HTML Menu
news templates
Find here examples of creative and unique website CSS HTML menu.