Skip to content

Instantly share code, notes, and snippets.

@funkycoder
Created December 8, 2020 03:48
Show Gist options
  • Save funkycoder/4483a4de28d1359c3ad5837d87c0f4c1 to your computer and use it in GitHub Desktop.
Save funkycoder/4483a4de28d1359c3ad5837d87c0f4c1 to your computer and use it in GitHub Desktop.
For loop in Python
# For loops in Python works like iterator in other language
# Execute a set of statements, once for each item in a list, tuple or set
# Print name in a list of names
names = ["John", "Henry", "Matt", "Rocky"]
for name in names:
print(name)
# >>>John
# >>>Henry
# >>>Matt
# >>>Rocky
# --------------------------------------------
# You can loop through characters of a string
for char in "Habanna":
print(char)
# >>>H
# >>>a
# >>>b
# >>>a
# >>>n
# >>>n
# >>>a
# --------------------------------------------
# Break from the loop
# Break when reach "Matt" before printing it
names = ["John", "Henry", "Matt", "Rocky"]
for name in names:
if name == "Matt":
break
print(name)
# >>>John
# >>>Henry
# --------------------------------------------
# With the continue statement we can stop the current iteration of the loop,
# and continue with the next
# Don't print "Matt"
names = ["John", "Henry", "Matt", "Rocky"]
for name in names:
if name == "Matt":
continue
print(name)
# >>>John
# >>>Henry
# >>>Rocky
# --------------------------------------------
# Using range() function
for x in range(4):
print(x)
# >>>0
# >>>1
# >>>2
# >>>3
# --------------------------------------------
# Using range with start parameter
for x in range(2,4):
print(x)
# >>>2
# >>>3
# --------------------------------------------
# Using range with increment sequence
# default increment is 1
for x in range (2,6,3):
print(x)
# >>>2
# >>>5
# --------------------------------------------
# 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 (3):
print(x)
else:
print("Completed!")
# --------------------------------------------
# Nested loop
names = ["John", "Henry", "Matt", "Rocky"]
chars = ["handsome", "nice", "fun"]
for name in names:
for char in chars:
print(name, char)
# >>> John handsome
# >>> John nice
# >>> John fun
# >>> Henry handsome
# >>> Henry nice
# >>> Henry fun
# >>> Matt handsome
# >>> Matt nice
# >>> Matt fun
# >>> Rocky handsome
# >>> Rocky nice
# >>> Rocky fun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment