Search code examples
pythonfunctionfor-loopreturnprogram-entry-point

Returning in for loops python


I've been trying a while now but i just can't seem to get it right. I'm a starting programmer and have to do an assignment for school. The program should ask the user for a number and print a diamond shape, based on this number. Now I've got it working fine.. but I have print statements outside my main. How do i get this inside my main?

my code:

def loop(start, eind, step, ei):
    for a in range (start, eind, step):       
        for b in range(a):                  
            print(" ", end="")                
        for c in range(ei+1, a, -1):
            print(a, end="")            
        for d in range(a, ei):           
            print(a, end="")             
    print("")  

def main():
    print("Welcome!  :) ")
    loop(y,0,-1,y)
    loop(2,y+1,1,y)

Hope you guys can help me out! By the way, I've got more code for this program but that's not relevant (like asking the user for "y").


Solution

  • Assuming the indentation you have pasted is correct (and y variable is defined in global scope), your current code does not produce a diamond shape , it would only get produced correctly if the last print("") inside the loop() function was indented inside the for loop.

    Given that, what you may want to look into is generator functions with yield statements . Example -

    def loop(start, eind, step, ei):
        for a in range (start, eind, step):       
            for b in range(a):                  
                yield " "                
            for c in range(ei+1, a, -1):
                yield a            
            for d in range(a, ei):           
                yield a
            yield '\n'
    
    def main():
        print("Welcome!  :) ")
        for x in loop(y,0,-1,y):
            print(x,end="")
        for x in loop(2,y+1,1,y):
            print(x,end="")
    

    This assumes y variable is defined in global scope.

    Demo -

    >>> def loop(start, eind, step, ei):
    ...     for a in range (start, eind, step):
    ...         for b in range(a):
    ...             yield " "
    ...         for c in range(ei+1, a, -1):
    ...             yield a
    ...         for d in range(a, ei):
    ...             yield a
    ...         yield '\n'
    ...
    >>> def main():
    ...     print("Welcome!  :) ")
    ...     y = 5
    ...     for x in loop(y,0,-1,y):
    ...         print(x,end="")
    ...     for x in loop(2,y+1,1,y):
    ...         print(x,end="")
    ...
    ...
    >>> main()
    Welcome!  :)
         5
        444
       33333
      2222222
     111111111
      2222222
       33333
        444
         5