How to repeat a code snippet given times?

Asked

Viewed 75 times

0

How to repeat a code snippet as many times as the user informs?

That’s what I tried:

#Só um exemplo

import random    

gerar= int(input("digite quantos números deseja gerar,o limite máximo é 20"))

   c=("+55119")

   while        
    print(c,(random.randrange(1,100000001)))
  • 2

    for _ in range(gerar): print(c,(random.randrange(1,100000001)))

2 answers

3


You started well, using a while loop. Missed adding condition to repeat code only the amount reported in variable gerar.

There are a few ways to do this. The way I’ll show you is to subtract 1 from each repeat, and stop the loop until it reaches zero. For example:

>>> quantidade_de_repeticoes = 3
>>> while quantidade_de_repeticoes > 0:
...   print("oi")
...   quantidade_de_repeticoes -= 1
... 
oi
oi
oi

In your case, it would look like:

import random    

gerar = int(input("digite quantos números deseja gerar,o limite máximo é 20"))

c=("+55119")

while gerar != 0:     
    print(c, (random.randrange(1,100000001)))
    gerar -= 1

2

Python has two commands for loop for repetition of suites: for and while.


LOOP FOR

For the lasso for, it will be necessary to use the function range (which takes as its initial parameter the amount of times it will repeat a suite code):

repeticoes = 5
for contador in range(repeticoes):
    print(contador)

This suite will print the output below on console:

0
1
2
3
4

LOOP WHILE

For the lasso while it will be necessary to create a variable that will be incremented with each repetition of the suite.

As long as the condition assessed results in True, the suite will be repeated:

contador = 0
repeticoes = 5

while contador < repeticoes:
    print(contador)
    contador += 1  # a cada repetição, soma 1 no valor da variável contador

This suite will print the output below on console:

0
1
2
3
4

USING HIS EXAMPLE

Based on your example, the following implementations would be possible:

WHILE
import random    

gerar = int(input('Digite quantos números deseja gerar (o limite máximo é 20): '))
c = ('+55119')
contador = 0

while contador < gerar:
    print(c, random.randrange(1, 100000001))
    contador += 1
FOR
import random    

gerar = int(input('Digite quantos números deseja gerar (o limite máximo é 20): '))
c = ('+55119')

for contador in range(gerar):
    print(c, random.randrange(1, 100000001))

Browser other questions tagged

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