Python Forum
Two loops behaving differently
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Two loops behaving differently
#1
One of the options below prints "a = 1" as the first term and the other doesn't. WHY ?

for a in range(1, 4, 1): # This option prints a = 1 as first term in results
#for a in range(1, 50, 10): # This option does not print a = 1
print(a = ", a)
b = 0
while b < 5:
z = b*4
z += 1
print(" b = ",b)
Reply
#2
Both print a = 1 on my machine
Reply
#3
Please post the code that causes the problem. The code you provided does not run (error in the first print statement, while b < 5 loop never ends). When I fixed the error I could not make the code exhibit the behavior you describe.

I'm sure this code is similar to your code, but the most important part is missing. The part that demonstrates your problem. You cut that part out because you didn't think it mattered. Obviously it does. Please post the actual code that has the actual problem.
Reply
#4
(Dec-26-2020, 08:05 PM)deanhystad Wrote: Please post the code that causes the problem. The code you provided does not run (error in the first print statement, while b < 5 loop never ends). When I fixed the error I could not make the code exhibit the behavior you describe.

I'm sure this code is similar to your code, but the most important part is missing. The part that demonstrates your problem. You cut that part out because you didn't think it mattered. Obviously it does. Please post the actual code that has the actual problem.
Reply
#5
I'm sorry. Of course the last line should be b += 1 not z += 1. Also, for some reason in my post I could not get the code to indent. I'm sure you twigged this.

I ran the two variants on a Google Colab notebook.

The two variants appear logically identical to me and if you list the ranges there seems no reason why a = 1 should not be printed in both cases.
Reply
#6
In the posed code both variants print a = 1. I do not think the code you posted accurately represents the code you are trying to debug. Please post the code that is not printing a = 1. Configure the code to not print = 1. Run the code on your notebook to verify it does not print a = 1. Copy the exact and post the code without any further edits.

When you post the code use python tags (use the button provided in the editor window) to retain indentation.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  if condition not behaving as expected EricBHK 10 1,457 May-16-2020, 03:41 PM
Last Post: EricBHK
  Hash command works differently for me in CMD and Spyder ZweiDCG 3 968 Sep-10-2019, 01:10 PM
Last Post: DeaD_EyE
  Requests not behaving... PythonLamer 1 3,427 Dec-01-2017, 06:45 PM
Last Post: nilamo
  Why does Function behave differently in a class vs. outside a class? Leaf 4 2,439 Nov-30-2017, 11:13 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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