Search code examples
pythoninputrow

Turn an input into a number of rows in Python


I need to write a function that receives an input and turns that input into a number of rows and all of the rows will be identical, all of the rows will look like this "**********".

I wrote this:

def rows(n):
    row = "*" * 10 
    for i in range(0,n):
        for j in range(0,i):
            print (row)
    
cant = int(input("Choose the number of rows: "))
total = rows(cant)

But whenever I run it and for example make an input of 4 rows it prints 5, if I use 5 as an input it prints 10 rows. None of the inputs work except if I make a 3,if I make the input a 3 it will properly print 3 rows of 10 stars. How can I fix this?


Solution

  • Your function is overly complicated.

    def rows(n):
        row = "*" * 10
        for i in range(0,n): #Makes a loop that runs n times.
            print(row) #Prints the row
    

    Edit for explanation:
    In your function, the first for loop will run n times, and for each of those times, the second for loop will run i times. meaning;
    For an input n = 4.
    The first time through, nothing is printed, because the second loop ends instantly as the i in range(0,i) is 0. The second round through, i is 1, and the print is called once. The third time, the i is 2, and the print will be called twice. The forth and final time, the i is 3, and the print will be called three times, which is why a rows(4) call makes 6 printed lines.