¿Hay alguna diferencia entre` continuar `y` pasar ' en un bucle for en python?


¿Hay alguna diferencia significativa entre las dos palabras clave de python continue y pass como en los ejemplos

for element in some_list:
    if not element:
        pass

Y

for element in some_list:
    if not element:
        continue

Debo ser consciente de?

Author: voo_doo, 2012-02-28

9 answers

Sí, hacen cosas completamente diferentes. pass simplemente no hace nada, mientras que continue continúa con la siguiente iteración del bucle. En su ejemplo, la diferencia se haría evidente si agregara otra instrucción después de if: Después de ejecutar pass, esta instrucción adicional se ejecutaría. Después de continue, no lo haría.

>>> a = [0, 1, 2]
>>> for element in a:
...     if not element:
...         pass
...     print element
... 
0
1
2
>>> for element in a:
...     if not element:
...         continue
...     print element
... 
1
2
 257
Author: Sven Marnach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-27 02:50:59

Sí, hay una diferencia. continue obliga al bucle a comenzar en la siguiente iteración mientras que pass significa "no hay código que ejecutar aquí" y continuará a través del resto o el cuerpo del bucle.

Ejecutar estos y ver la diferencia:

for element in some_list:
    if not element:
        pass
    print 1 # will print after pass

for element in some_list:
   if not element:
       continue
   print 1 # will not print after continue
 50
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 14:45:57

continue saltará de nuevo a la parte superior del bucle. pass continuará procesando.

Si al final del bucle, la diferencia es insignificante, ya que el flujo de vuelta a la parte superior del bucle de todos modos.

 10
Author: tMC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 14:44:45

En su ejemplo, no habrá diferencia, ya que ambas sentencias aparecen al final del bucle. pass es simplemente un marcador de posición, ya que no hace nada ( pasa la ejecución a la siguiente instrucción). continue, por otro lado, tiene un propósito definido: le dice al bucle que continúe como si se hubiera reiniciado.

for element in some_list:
    if not element:
        pass
    print element  

Es muy diferente de

for element in some_list:
    if not element:
        continue
    print element
 7
Author: multipleinterfaces,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 14:45:50

Sí, hay una diferencia. Continue en realidad se salta el resto de la iteración actual del bucle (volviendo al principio). Pass es una declaración en blanco que no hace nada.

Ver los documentos de python

 4
Author: froadie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 14:46:02

En esos ejemplos, no. Si la sentencia es no la última en el bucle, entonces tienen muy efectos diferentes.

 3
Author: Ignacio Vazquez-Abrams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 14:44:40

Hay una diferencia entre ellos,
continue omite la iteración actual del bucle y ejecuta la siguiente iteración.
pass no hace nada. Es un marcador de posición de declaración vacío.
Prefiero darles un ejemplo que lo aclare mejor.

>>> for element in some_list:
...     if element == 1:
...         print "Pass executed"
...         pass
...     print element
... 
0
Pass executed
1
2

>>> for element in some_list:
...     if element == 1:
...         print "Continue executed"
...         continue
...     print element
... 
0
Continue executed
2
 1
Author: Walk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-30 08:10:36
x = [1,2,3,4] 
for i in x:
    if i==2:
         pass  #Pass actually does nothing. It continues to execute statements below it.
         print "This statement is from pass."
for i in x:
    if i==2:
         continue #Continue gets back to top of the loop.And statements below continue are executed.
         print "This statement is from continue."

La salida es

>>> This statement is from pass.

De nuevo, vamos a ejecutar el mismo código con cambios menores.

x = [1,2,3,4]
for i in x:
    if i==2:
       pass  #Pass actually does nothing. It continues to execute statements below it.
    print "This statement is from pass."
for i in x:
    if i==2:
        continue #Continue gets back to top of the loop.And statements below continue are executed.
    print "This statement is from continue."

La salida es -

>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.

Pass no hace nada. La computación no se ve afectada. Pero continuar vuelve a la parte superior del bucle a procced con el siguiente cómputo.

 1
Author: Raviteja Ainampudi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-07 16:19:59

Considéralo de esta manera:

Pass: Python funciona puramente en sangría! No hay llaves vacías, a diferencia de otros idiomas.

Por lo tanto, si no desea hacer nada en caso de que una condición sea verdadera, no hay otra opción que pasar.

Continue: Esto es útil solo en el caso de bucles. En caso de que, para un rango de valores, no desee ejecutar las sentencias restantes del bucle después de que la condición sea verdadera para ese paso en particular, entonces tendrá que utilice continuar.

 0
Author: Vaishali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 10:23:07