9
answers
3
watching
191
views

For Loops in Python

A loop is used to execute the same block of code multiple times. Each time the loop repeats is called an iteration of the loop.

Iterating Through Strings

The following loop repeats four times, one iteration for each letter in the word "word":

word = "word"
for letter in word:
 print(letter)

Output: w o r d

We can use any variable name instead of "letter" and perform any action inside the loop. All statements indented after the for loop statement will repeat four times. For example:

x = 1
for letter in word:
 print(x)
 x += 2

Output: 1 3 5 7

Iterating Through Lists

We can also iterate through each item in a list:

colors = ["red", "blue", "green"]
for x in colors:
 print(x)

Output: red blue green

We can also use a list of integers:

count = [1, 2, 3, 4, 5]
for i in count:
 print(str(i) + " squared equals " + str(i**2))

Output: 1 squared equals 1
2 squared equals 4
3 squared equals 9
4 squared equals 16
5 squared equals 25

The Range Function

Most for loops use the range function for a simple counter. Range returns a list of integers. Here's an example:

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

Output: 2 5 8

The first value is the "from" value, which is inclusive and defaults to 0 if not provided. The second value is the "to" value, which is not inclusive. The third value is the "step" value, which defaults to 1 if not provided. Here are some examples:

  • range(2) returns 0 1
  • range(0, 2) returns 0 1
  • range(0, 2, 1) returns 0 1
  • range(0, 6, 1) returns 0 1 2 3 4 5
  • range(5, 9, 1) returns 5 6 7 8
  • range(5, 9, 2) returns 5 7
  • range(3, 0, -1) returns 3 

For unlimited access to Homework Help, a Homework+ subscription is required.

Avatar image
Liked by noumansamad878 and 3 others

Unlock all answers

Get 1 free homework help answer.
Already have an account? Log in
Already have an account? Log in
Already have an account? Log in
Avatar image
Read by 1 person
Already have an account? Log in
Avatar image
Read by 1 person
Already have an account? Log in
Avatar image
Read by 1 person
Already have an account? Log in
Avatar image
Read by 2 people
Already have an account? Log in
Avatar image
Read by 2 people
Already have an account? Log in
Avatar image
Read by 3 people
Already have an account? Log in

Related questions

Related Documents

Weekly leaderboard

Start filling in the gaps now
Log in