How do I use the for command to solve the same problem?

Asked

Viewed 80 times

1

In this case, the objective of the program was to make a half pyramid, as many floors as the user wanted to build, however, he wanted to use the 'for' command to accomplish this goal.

quant = int(input('Quantos andares você quer que tenha a meia pirâmide? '))
while quant >= 1:
  print('* ' * quant, end ='')
  print('')
  quant -= 1

>>> Quantos andares você quer que tenha a meia pirâmide? 4
* * * * 
* * * 
* * 
* 

2 answers

2


The for exists to go through data collections, so you have to generate a collection of numbers starting in quantity, going up to 0, with the step of each variation of the number being negative to go down the value. This is done with the function range().

I took the opportunity to simplify the code. But do not treat error if the person does not enter a numerical value, which would cause the application to break.

You can even do it with a line, but I don’t like it, it doesn’t increase readability, it just makes it shorter, which are different things.

quant = int(input('Quantos andares você quer que tenha a meia pirâmide? '))
print('')
for n in range(quant, 0, -1):
    print('* ' * n)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

0

You can add another variable to make the base turn.

quant = int(input('Quantos andares você quer que tenha a meia pirâmide? '))
p = quant

for x in range(quant):
  print('* ' * p, end ='')
  print('')
  p -= 1

The pyramide standing is simpler

quant = int(input('Quantos andares você quer que tenha a meia pirâmide? '))

for x in range(quant):
  print('* ' * x, end ='')
  print('')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.