5.2: For Loop
- Page ID
- 117550
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Explain the
forloop construct. - Use a
forloop to implement repeating tasks.
For loop
In Python, a container can be a range of numbers, a string of characters, or a list of values. To access objects within a container, an iterative loop can be designed to retrieve objects one at a time. A for loop iterates over all elements in a container. Ex: Iterating over a class roster and printing students' names.
A string variable can be considered a container of multiple characters, and hence can be iterated on. Given the following code, answer the questions.
str_var = "A string"
count = 0
for c in str_var:
count += 1
print(count)
What is the program's output?
789
- Answer
-
b. Eight characters exist in the
str_var. Iterating over all characters and incrementing the value ofcountvariable at each iteration results in thecount'svalue of8.
What's the code's output if the line count += 1 is replaced with count *= 2?
01628
- Answer
-
a. Since the initial
count's value is0, multiplyingcountby any number results in the output of0.
What is printed if the code is changed as follows?
str_var = "A string"
count = 0
for c in str_var:
count += 1
# New line
print(c, end = '*')
print(count)
A string*A*s*t*r*i*n*g*A* *s*t*r*i*n*g*
Range()
- Answer
-
c. The added line prints each character that is looped on (character
c), and prints an additional * after the character.
function in for loop
A for loop can be used for iteration and counting. The range() function is a common approach for implementing counting in a for loop. A range() function generates a sequence of integers between the two numbers given a step size. This integer sequence is inclusive of the start and exclusive of the end of the sequence. The range() function can take up to three input values. Examples are provided in the table below.
| Range function | Description | Example | Output |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
||
|
|
|
|
|
|
|
|
||
|
|
|
||
|
|
|
for
construction compared to the
while
)
# For loop condition using
# range() function to print
# all multiples of 5 less than 50
for i in range(0, 50, 5):
print(i)
|
# While loop implementation of printing
# multiples of 5 less than 50
# Initialization
i = 0
# Limiting the range to be less than 50
while i < 50:
print(i)
i+=5
|
What are the arguments to the range() function for the increasing sequence of every 3rd integer from 10 to 22 (inclusive of both ends)?
range(10, 23, 3)range(10, 22, 3)range(22, 10, -3)
- Answer
-
a. The output will be an increasing sequence between
10and22(inclusive of both):10,13,16,19, and22.
What are the arguments to the range() function for the decreasing sequence of every integer from 5 to 1 (inclusive of both ends)?
range(5, 1, 1)range(5, 1, -1)range(5, 0, -1)
- Answer
-
c. The expression starts a sequence from
5, decreases by 1 at every step, and ends at1.
What is the sequence generated from range(-1, -2, -1)?
1-1, -2-2
- Answer
-
a. The
range()function generates a descending sequence, beginning from-1until-2. Hence, the output is-1.
What is the output of the range(1, 2, -1)?
11, 2- empty sequence
- Answer
-
c. When the step size is negative, the generated sequence will be in descending order. Hence,
startmust be larger thanend; otherwise, no sequence will be generated.
What is the output of range(5, 2)?
0, 2, 42, 3, 4- empty sequence
- Answer
-
c. When two arguments are provided to the
range()function, arguments are considered asstartandendof the sequence, and the step size will be1. When step size is positive, the generated sequence will be in ascending order, and hence,startmust be less thanend. Otherwise, no sequence will be generated.
Write a program using a for loop that takes in a string as input and counts the number of spaces in the provided string. The program must print the number of spaces counted. Ex: If the input is "Hi everyone", the program outputs 1.
Interactive Code
- Input
-
This is the input - Answer
-
usr_in = input()count = 0
for c in usr_in:
if c == ' ':
count += 1
print(count)
Write a program that reads two integer values, n1 and n2, with n1 < n2, and performs the following tasks:
- Prints all even numbers between the two provided numbers (inclusive of both), in ascending order.
- Prints all odd numbers between the two provided numbers (exclusive of both), in descending order.
Input: 2 8
Prints:
2 4 6 8
7 5 3
Note: the program should return an error message if the second number is smaller than the first.
Interactive Code
- Input
-
10
20 - Answer
-
n1 = int(input("Enter an integer: "))
n2 = int(input("Enter another integer larger than the first one: "))if n2 <= n1:
print("Error: n2 must be greater than n1.")
else:# Printing even numbers in increasing order (inclusive)
if n1%2 == 0:
for i in range(n1, n2+1, 2):
print(i, end = ' ')
else:
for i in range(n1+1, n2+1, 2):
print(i, end = ' ')print()
# Printing odd numbers in decreasing order (exclusive)
if (n2-1)%2 == 1:
for i in range(n2-1, n1, -2):
print(i, end = ' ')
else:
for i in range(n2-2, n1, -2):
print(i, end = ' ')


