how to make a triangle with this symbol in python (*)?

2

1) My first problem is how to apply the math with the symbol (*) in str form.

2) My second problem is how do I make a triangle like this

*
**
***
****
*****

This is my code so far

def triangulo():

    simbolo='*'

      for i in range(5):

         simbolo+=simbolo

         print(simbolo)

triangulo()

OUTPUT:

**

****

********

****************

********************************
    
asked by juan 05.10.2018 в 06:14
source

2 answers

2

First by following your example but I without using a function, you declare the variable symbol that will contain a *, then print it with print, you create the cycle and here is the important thing to achieve what you want: to the variable symbol concatenas another * with the operator + and print it in each iteration of the for cycle.

simbolo = '*'
print(simbolo)
for i in range(5):
   simbolo = simbolo + '*'
   print(simbolo)
    
answered by 05.10.2018 / 06:37
source
2

What happens is that in this line of your code

simbolo += simbolo

For each iteration you are concatenating the previous value that the symbol variable had and then it is replaced by the new value. What causes this effect of characters in powers of a 2. That is, you start with a single character of '*' (2 ^ 0), in the first iteration they are 2 (2 ^ 1), in the second iteration 4 (2 ^ 2), in the third they are 8 (2 ^ 3) and so on.

My suggestion is that you take advantage of the multiplication operation between text strings and a number like this:

simbolo = '*'
for i in range(6):
    print(simbolo * i)
    
answered by 05.10.2018 в 06:55