Python Forum

Full Version: Assigning a new variable in a IF loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying a very basic IF loop in which i am trying to create a new variable like below
for i in range(1,16):
   for j in range(i,i+14):
       if (j > 13):
            {
             jdisplay = "j%13"
            }
       else:
            {
             jdisplay=j
            }
print(i,j)
i am not getting this right, i want the number not to exceed 13, if it is greater than 13 a new variable called jdisplay should be created and the value should be modulo division of j with 13.
(Mar-01-2018, 05:09 PM)pythoneer Wrote: [ -> ]a new variable called jdisplay should be created
How many different variables, all named jdisplay, do you want?
And why are there braces in your code?
oops, sorry , i got this working, this is what happens when i switch from something else to something i started to learn..thanks
for i in range(1,16):
   for j in range(i,i+14):
       if (j > 13):
        jdisplay = j%13

       else:
        jdisplay=j
        print(i,jdisplay)
i think you need to dedent line 8 one level.
Also note that your indentation is not consistent - you have 3, 4 and 1 space indentation.
So that works, right? I'm not a huge fan of hoisting variables to their containing scope, so even though it works, I'd put a default value before the loop. Something like:
jdisplay = None
for i in range(1, 16):
    for j in range(i, i+14):
        if j > 13:
            jdisplay = j % 13
        else:
            jdisplay = j
print(jdisplay)
(Mar-01-2018, 06:19 PM)buran Wrote: [ -> ]i think you need to dedent line 8 one level.
Also note that your indentation is not consistent - you have 3, 4 and 1 space indentation.

Thanks for the inputs, will correct it

(Mar-01-2018, 07:42 PM)nilamo Wrote: [ -> ]So that works, right? I'm not a huge fan of hoisting variables to their containing scope, so even though it works, I'd put a default value before the loop. Something like:
jdisplay = None
for i in range(1, 16):
    for j in range(i, i+14):
        if j > 13:
            jdisplay = j % 13
        else:
            jdisplay = j
print(jdisplay)

Curious to know the difference it would make. Anyways the old one works.