Python prevede solo due tipi di ripetizioni (cicli, iterazioni)
- for …
- while …
In altri linguaggi sono presenti molte più strutture di controllo (repeat…until, do…while, …)
Nei prossimi esempi
- In 1° colonna: il codice Python
- In 2° colonna: il codice equivalente C, C++, Java, Javascript, …
- In 3° colonna: la sequenza generata
1
for i in range(10):
print(i, end=" ")
for(i=0; i < 10; i+=1)
...;
0 1 2 3 4 5 6 7 8 9
for(i=0; i <= 9; i+=1)
...;
i=0
while(i < 10):
print(i, end=" ")
i+=1
i=0;
while(i < 10)
{
...;
i+=1;
}
i=0
while(i <= 9):
print(i, end=" ")
i+=1
i=0;
while(i <= 9)
{
...;
i+=1;
}
2
for i in range(5, 10):
print(i, end=" ")
for(i=5; i < 10; i+=1)
...;
5 6 7 8 9
for(i=5; i <= 9; i+=1)
...;
i=5
while(i < 10):
print(i, end=" ")
i+=1
i=5;
while(i < 10)
{
...;
i+=1;
}
i=5
while(i <= 9):
print(i, end=" ")
i+=1
i=5;
while(i <= 9)
{
...;
i+=1;
}
3
for i in range(0, 10, 2):
print(i, end=" ")
for(i=0; i < 10; i+=2)
...;
0 2 4 6 8
for(i=0; i <= 9; i+=2)
...;
i=0
while(i < 10):
print(i, end=" ")
i+=2
i=0;
while(i < 10)
{
...;
i+=2;
}
i=0
while(i <= 9):
print(i, end=" ")
i+=2
i=0;
while(i <= 9)
{
...;
i+=2;
}
4
for i in range(9, -1, -1):
print(i, end=" ")
for(i=9; i > -1; i-=1)
...;
9 8 7 6 5 4 3 2 1 0
for(i=9; i >= 0; i-=1)
...;
i=9
while(i > -1):
print(i, end=" ")
i-=1
i=9;
while(i > -1)
{
...;
i-=1;
}
i=9
while(i >= 0):
print(i, end=" ")
i-=1
i=9;
while(i >= 0)
{
...;
i-=1;
}
5
for i in range(9, -1, -2):
print(i, end=" ")
for(i=9; i > -1; i-=2)
...;
9 7 5 3 1
for(i=9; i >= 0; i-=2)
...;
i=9
while(i > -1):
print(i, end=" ")
i-=2
i=9;
while(i > -1)
{
...;
i-=2;
}
i=9
while(i >= 0):
print(i, end=" ")
i-=2
i=9;
while(i >= 0)
{
...;
i-=2;
}
Nei linguaggi che derivano dal C si riduce ulteriormente il codice con
- i++ (oppure ++i) invece di i+=1
- i-- (oppure --i) invece di i-=1