Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop beginner
#1
I'm just learning to code right now and Im experimenting with For Loops.
I tried this 2 options that I thought are the same but a get different results.

Anybody can tell me what the difference is?

a, b = 0, 1

for i in range(10):
    print(a)
    a, b = b, a+b
a = 0
b = 1

for i in range(10):
    print(a)
    a = b
    b = a + b
Reply
#2
This has nothing to do with for loops. The difference is how you do the assignment.

When you do "a, b = b, a + b", the assignment "a, b =" happens after "b, a + b" completes. The value of "a" does not change until after evaluating "a + b". It is like you wrote the program this way:
temp = a
a = b
b = temp + b
When you split this into multiple statements:
    a = b
    b = a + b
a is assigned a new value before calling "b = a + b"

Doing multiple assignments in one statement can be very useful. This is a common way to swap two values in Python.
a, b = b, a
In C you would need a temporary variable for this.
Output:
temp = a a = b b = temp
But you need to be careful when doing multiple assignments in one statement. Everything on the right side of the "=" is going to happen before assigning any values to the left side of the "=".
Reply
#3
Awesome, thanks for the help!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Beginner problem, replace function with for loop Motley_Cow 9 6,263 Sep-13-2019, 06:24 AM
Last Post: Motley_Cow
  Beginner Loop question BigDisAok 5 4,816 Jul-24-2018, 02:04 PM
Last Post: BigDisAok

Forum Jump:

User Panel Messages

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