Python Forum
For Loops & Variables
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loops & Variables
#1
for i in range(3):
    for j in range(2):
        print(j)
I don't understand how the output of this is:
0
1
0
1
0
1

-why do those variables contain these integer values already?
Thats the only part i really dont get. I understand that for every loop in i, 2 loops of j play out, that why for each loop, the value generated is first 0 then 1 but where did these values come from?
Reply
#2
your outer loop runs 3 times.
for each iteration of the outer loop, the inner loop prints out two numbers in range (2) which are 0 and 1
so you get 3 groups of 0 and 1, or 010101, each on a new line

What were you expecting?
Reply
#3
You may see the answer more clearly if you run this code:
for i in range(3):
    for j in range(2):
        print(i, j)
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply
#4
@Larz, what im failing to understand is that when we define a variable with a string, it clear how the loops run, but here the variables arent defined so then why are integers produced in the output?
Reply
#5
The variables are defined when you put them in the for loop. You don't have to explicitly define variables in Python, they are defined as soon as you assign something to them. That's what the for loop does: it successively assigns the values looped over (the range calls) to the looping variables (i and j). And that's why the range(2) values print out when you print j.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020