Home > Software design >  How do I add values depending on variables?
How do I add values depending on variables?

Time:09-17

So I got a task where I have to make a function that recieves a number and makes that number into an ammount of rows, those rows will basically have one more asterisk than the previous one ( for example if I have 5 rows my print will look like this:

line 1-*
line 2-**
line 3-***
line 4-****
line 5-*****

So my code rn looks like this:

def filastotal(n):
    ast = "*"
    for i in range (n):
        ast = ast   "*"
    return ast

cant = int(input("Ingrese la cantidad de filas: "))
total = filastotal(cant)
print(total)

So my idea was to first make an asterisk using a string and then adding one more asterisk for every element in the n but when I run this I just get the ammount of asterisk I enter as rows one next to the other. Also one of the problems I run to is that my teacher said that functions should only do one thing and no values should be read or printed inside a function that does other thing, so considering this function should recieve the ammount of rows and make them work then it shouldnt print inside them. For example if I enter a 5 I get 5 asterisks next to each other in the same line instead of

line 1-*
line 2-**
line 3-***
line 4-****
line 5-*****

How can I fix this?

CodePudding user response:

It's helpful to figure out what type of value your function should return. It seems like you could return a list of maybe a string. Then the one thing you want to do is take input and make that type of thing.

For example, maybe we want to return a string. This makes sense considering you want to just print the value. That string would need to include a newline character for each line ("\n"). A nice way to do that is to use "\n".join() which takes a iterable and joins then into a string. That makes the problem super-succinct:

def filastotal(n):
    '''Take an integer n and returns a string with n lines'''
    ast = "*"
    return "\n".join(ast * n for n in range(1, n 1))

cant = int(input("Ingrese la cantidad de filas: "))

total = filastotal(cant)

print(total)

Which runs:

Ingrese la cantidad de filas: 5
*
**
***
****
*****

Note the expression: ast * n will make a string with n ast strings (i.e. "$" * 5 gives '$$$$$'). Also, we use range(1, n 1) here because ranges start at zero and don't include the last number. But when n is 5 we want 1 through 5 inclusive.

  • Related