Repeat a print certain times in a while

1
numero1 = 1

print("Desde el")

while True:

    print("Número {}".format( numero1 ))
    numero1 = numero1 + 1

    print("hasta el")

    if numero1 == 11:
        break

the result is:

Desde el
Número 1
hasta el
Número 2
hasta el
Número 3
hasta el
Número 4
hasta el
Número 5
hasta el
Número 6
hasta el
Número 7
hasta el
Número 8
hasta el
Número 9
hasta el
Número 10
hasta el

and I would like it to be:

Desde el número 1
2 
3
4
5
6
7
8
9
hasta el número 10
    
asked by JGUser 24.02.2018 в 21:22
source

2 answers

3

If you just want to print the value of the variable numero1 , I do not see it necessary to use format just print the variable

numero1 = 1
#Imprimimos el número
print "Desde el numero " , numero1
#Incrementamos para iniciar en 2
numero1 = numero1 + 1

while True:
    # si es igual a 10 matamos el ciclo
    if numero1 == 10:
      print "hasta el numero ", numero1
      break

    #caso contrario imprimimos el número e 
    #incrementamos la variable
    print numero1 
    numero1 = numero1 + 1

Although to improve the reading a bit and not change much and work with any start or end, could have declared 2 variables, inicio and final and iterate through a for , with range(inicio,final): that is, it will start with the start value and end when it reaches the end value, this is similar to the typical i < n of the classic for , for this case it would be inicio < final

inicio = 1
final = 10
#Imprimimos el número
print "Desde el numero " , inicio
#Incrementamos para iniciar en 2
inicio+=1
for x in range(inicio,final):
  print x

print "Hasta el numero " , final
    
answered by 24.02.2018 / 21:44
source
2

Another very simple option for the output you want using while is to dispense conditional and break and use variable numero1 as a control variable of the cycle directly (this avoids checking two conditions in each iteration):

numero1 = 1

print("Desde el número", numero1)

while numero1 < 10:
    numero1 += 1
    print(numero1)

print("hasta el número", numero1)

In Python 3, where print is a function, you can use a generator with for directly in the print :

inicio = 1
final = 10

print("Desde el número", inicio)
print(*(n for n in range(inicio+1, final)), sep='\n')
print("hasta el número", final)
    
answered by 24.02.2018 в 22:06