For Loop
Part of the Fundamentals section of Coddy's Python journey — lesson 35 of 77.
Sometimes when programming, it's necessary to perform the same or almost the same operation a couple of times.
To prevent writing the same thing over and over again, we can use loops.
The for loop has the following syntax:
for i in range(start, end):
codeThe range(start, end) determines what is the start value and what is the end value. The i will receive all values from start to end (not including end) sequentially. For example:
for i in range(0, 5):
print(i)It will execute the print statement 5 times:
0
1
2
3
4We can simplify the
range(0, 5)torange(5):for i in range(5): print(i)
You can also combine i with other text using an f-string. Place an f before the string and use {i} inside it to insert the value of i:
for i in range(1, 4):
print(f"Item number: {i}")This will print:
Item number: 1
Item number: 2
Item number: 3Loops have many use cases. For example, let's sum all the numbers from 1 to 100:
sum_numbers = 0
for i in range(1, 101):
sum_numbers += i
print(sum_numbers)This will first loop through all numbers between 1 and 101 (not including 101) and sum all of them. Then it will print the sum_numbers variable.
Challenge
BeginnerWrite a program that prints "Hello Coddy: " and the i value from 3 to 27 (both numbers inclusive), using a for loop.
This means you'll print 25 lines in total, starting from 3 and ending at 27.
The output will look like this:
Hello Coddy: 3
Hello Coddy: 4
...
Hello Coddy: 27Cheat sheet
The for loop in Python is used to iterate over a sequence:
for i in range(start, end):
# code to be executedKey points about range():
range(end): Starts from 0, goes up to (but not including)endrange(start, end): Goes fromstartto (but not including)end
Example of a for loop:
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2