Posts: 27
Threads: 11
Joined: Aug 2024
1 2 |
for i in range ( 2 ):
print ( "Hello" )
|
I'd like some help regarding how this actually works.
Here's what I think is going on:
1. The loop counter, i, is assigned a value. With Python, unless otherwise specified, i = 0
2. Python checks if i >= 2. It isn't and so it executes the commands (here it is simply to print Hello) in the loop. We see a Hello.
3. Python increments i i.e. i = i + 1. That's i = 0 + 1 = 1
4. Python checks if i >= 2. It isn't and so it executes the loop once more. We see one more Hello
5. Python increments i i.e. i = i + 1. That's i = 1 + 1 = 2
6. Python checks if i >= 2. It is and so it exits the loop
The end result is that the For Loop executed the Loop twice, just as we wanted by giving 2 as the argument for range in the For Loop.
Now I tried the following:
1 2 |
for i in range ( 1 , 3 ):
print ( "Hello" )
|
It has the same output, 2 Hellos.
This is what I think is going on:
1. Python assigns i = 1.
2. Python checks if i >= 3. It isn't. So it prints Hello
3. Python increments i i.e. i = i + 1. That's i = 1 + 1 = 2
4. Python checks if i >= 3. It isn't. So it prints Hello
5. Python increments i i.e. i = i + 1. That's i = 2 + 1 = 3
6. Python checks if i >= 3. It is. So it exits the loop
My conclusion is Python checks for the stop/exit loop condition BEFORE it executes the loop.
Is this correct? Are there any helpful shortcuts to remember how many times a loop gets executed when we specify the start and stop conditions?
Thank you.
Posts: 2,168
Threads: 35
Joined: Sep 2016
Nov-10-2024, 08:10 AM
(This post was last modified: Nov-10-2024, 08:13 AM by Yoriz.)
The for statement iterates over elements in a sequence such as a string, tuple or list) or other iterable object.
The range creates a terable sequence of numbers.
1 2 |
for i in range ( 1 , 3 ):
print ( "Hello" )
|
- the
for calls for the next item from the sequence, the range gives it 1, i assigned to 1
print hello
- the
for calls for the next item from the sequence, the range gives it 2, i assigned to 2
print hello
- the
for calls for the next item from the sequence, the range raises StopIteration , so the looping stops
Posts: 27
Threads: 11
Joined: Aug 2024
(Nov-10-2024, 08:10 AM)Yoriz Wrote: The for statement iterates over elements in a sequence such as a string, tuple or list) or other iterable object.
The range creates a terable sequence of numbers.
1 2 |
for i in range ( 1 , 3 ):
print ( "Hello" )
|
- the
for calls for the next item from the sequence, the range gives it 1, i assigned to 1
print hello
- the
for calls for the next item from the sequence, the range gives it 2, i assigned to 2
print hello
- the
for calls for the next item from the sequence, the range raises StopIteration , so the looping stops
Thanks. I know of 2 kinds of programming loops:
1. The For Loop
2. The While Loop
Which one is a Master Loop i.e. we can construct the other one with it, but not vice versa? My hunch, it's The While Loop.
1 2 3 4 |
x = 1
while x < 2 :
print ( "Hello" )
x = x + 1
|
should do the same thing as
1 2 |
for i in range ( 2 ):
print ( "Hello" )
|
Posts: 1,950
Threads: 8
Joined: Jun 2018
To understand how for-loop "actually" works type help('for') into interactive interpreter:
Quote:The "for" statement
*******************
The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" starred_list ":" suite
["else" ":" suite]
The "starred_list" expression is evaluated once; it should yield an
*iterable* object. An *iterator* is created for that iterable. The
first item provided by the iterator is then assigned to the target
list using the standard rules for assignments (see Assignment
statements), and the suite is executed. This repeats for each item
provided by the iterator. When the iterator is exhausted, the suite
in the "else" clause, if present, is executed, and the loop
terminates.
A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite. A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.
The for-loop makes assignments to the variables in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:
for i in range(10):
print(i)
i = 5 # this will not affect the for-loop
# because i will be overwritten with the next
# index in the range
Names in the target list are not deleted when the loop is finished,
but if the sequence is empty, they will not have been assigned to at
all by the loop. Hint: the built-in type "range()" represents
immutable arithmetic sequences of integers. For instance, iterating
"range(3)" successively yields 0, 1, and then 2.
Changed in version 3.11: Starred elements are now allowed in the
expression list.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 2,128
Threads: 11
Joined: May 2017
In Python the index is 0-based and everything follows the 0-based indexing. It has pros and cons. Contra is that humans start usually counting with 1.
Posts: 6,812
Threads: 20
Joined: Feb 2020
Nov-15-2024, 01:02 PM
(This post was last modified: Nov-15-2024, 01:02 PM by deanhystad.)
The for statement is an iterator that executes a block of code until a StopIteration exception is raised. The for loop does not care at all about the values produced while iterating.
These steps somewhat duplicate what is happening in your code
Output: >>> x = range(2) # Create a range object that generates a sequence of int (0, 1).
>>> y = iter(x) # The for loop is an iterator. Begin iterating the range object.
>>> next(y) # Get the first value. In your code this does i = next(y), but I want to see the iterator values, so no assignment.
0
>>> next(y)
1
>>> next(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration # The StopIteration exception stops the for loop.
As for the range(stop) or range(start, stop[, step]) command, this creates a range object that produces a sequence of int starting at the start value (default 0) and incrementing by the step value (default 1) until the stop value is reached. The stop value is not included in the sequence of values.
You can use this equation to compute the length of the sequence produced by the range(start, stop, step) command.
length = max(0, ceil((stop - start) / step))
1 2 3 4 5 6 7 8 9 10 |
def my_range(start, stop, step = 1 ):
length = max (math.ceil((stop - start) / step), 0 )
return length, list ( range (start, stop, step))
print (my_range( 0 , 2 ))
print (my_range( 1 , 3 ))
print (my_range( 1 , 10 , 5 ))
print (my_range( 3 , 1 , - 1 ))
print (my_range( 3 , 1 ))
print (my_range( 1 , 3 , - 1 ))
|
Output: (2, [0, 1])
(2, [1, 2])
(2, [1, 6])
(2, [3, 2])
(0, [])
(0, [])
As to why the stop value is not included in the sequence, I think that is so the stop value = the loop count when the default start and increment values are used. for i in range(2) will loop 2 times, even though i will never be assigned the value 2.
|