Home > Mobile >  How do I change initial index value of for loop in python?
How do I change initial index value of for loop in python?

Time:10-07

I want to do this exact code, but instead of i, using bricks. There are the same amount of bricks as i, but the i automatically initilises at 0, rather than 1 (That's what I assume).

My workaround is below, but thought there must be a better way for future.

import cs50


height = 0
while height < 1 or height > 8:
    height = cs50.get_int("Height: ") # this is fetching the levels from the user

bricks = 1                      #want to remove this line
for i in range(height):         #want to replace i with bricks starting at bricks = 1
    spaces = height - bricks
    #print spaces
    print(" " * spaces, end = "")
    #print bricks/hashes
    print("#" * bricks, end = "")
    #print middle fixed gap of two spaces
    print("  ", end = "")
    #print right bricks/hashes
    print("#" * bricks) #auto prints next line as default

    bricks  = 1           #want to remove this line

CodePudding user response:

The for loop has the following syntax: for in range(start, stop, step) default, start is 0. To change the value, enter your desired start value in the range() function. Eg: for i in range(7,15) here the start value of i is 7, and end value of i is 14 (n-1)

CodePudding user response:

Got there eventually. For those looking on, the passive aggressive link to the documentation had the answer, but coneptually the confusing thing coming from other languages is that range sets all your parameters including for i/bricks whatever you're iterating with.

So setting a start value within the range function rather than the default of 0.

Also had to 1 to my end to get the same amount of loops while starting from 1.

for bricks in range(1, height   1):
  • Related