Le ripetizioni for e while sono interscambiali se utilizzate per
- contare quante volte viene eseguito un blocco
- generare un elenco di numeri interi
Osserva
- In 1° colonna: il codice Python
- In 2° colonna: la sequenza generata.
- In 3° colonna: il codice equivalente C, C++, Java, Javascript, …
1
for i in range(10):
print(i)
i = 0
while(i < 10):
print(i)
i = i+1
i = 0
while(i <= 9):
print(i)
i = i+1
0
1
2
3
4
5
6
7
8
9
for(i=0; i < 10; i=i+1)
{
xxxxx;
}
for(i=0; i <= 9; i=i+1)
{
xxxxx;
}
i=0;
while(i < 10)
{
xxxxx;
i=i+1;
}
i=0;
while(i <= 9)
{
xxxxx;
i=i+1;
}
2
for i in range(5, 10):
print(i)
i = 5
while(i < 10):
print(i)
i = i+1
i = 5
while(i <= 9):
print(i)
i = i+1
5
6
7
8
9
for(i=5; i < 10; i=i+1)
{
xxxxx;
}
for(i=5; i <= 9; i=i+1)
{
xxxxx;
}
i=5;
while(i < 10)
{
xxxxx;
i=i+1;
}
i=5;
while(i <= 9)
{
xxxxx;
i=i+1;
}
3
for i in range(0, 10, 2):
print(i)
i = 0
while(i < 10):
print(i)
i = i+2
i = 0
while(i <= 9):
print(i)
i = i+2
0
2
4
6
8
for(i=0; i < 10; i=i+2)
{
xxxxx;
}
for(i=0; i <= 9; i=i+2)
{
xxxxx;
}
i=0;
while(i < 10)
{
xxxxx;
i=i+2;
}
i=0;
while(i <= 9)
{
xxxxx;
i=i+2;
}
4
for i in range(9, -1, -1):
print(i)
i = 9
while(i > -1):
print(i)
i = i-1
i = 9
while(i >= 0):
print(i)
i = i-1
9
8
7
6
5
4
3
2
1
0
for(i=9; i > -1; i=i-1)
{
xxxxx;
}
for(i=9; i >= 0; i=i-1)
{
xxxxx;
}
i=9;
while(i > -1)
{
xxxxx;
i=i-1;
}
i=9;
while(i >= 0)
{
xxxxx;
i=i-1;
}
5
for i in range(9, -1, -2):
print(i)
i = 9
while(i > -1):
print(i)
i = i-2
i = 9
while(i >= 0):
print(i)
i = i-2
9
7
5
3
1
0
for(i=9; i > -1; i=i-2)
{
xxxxx;
}
for(i=9; i >= 0; i=i-2)
{
xxxxx;
}
i=9;
while(i > -1)
{
xxxxx;
i=i-2;
}
i=9;
while(i >= 0)
{
xxxxx;
i=i-2;
}
Osserva
- Il costrutto for di Python è il più sintetico…
- Il codice si può semplificare ulteriormente utilizzando le istruzioni
i+=1, i+=2, ...
i-=1, i-=2, ...
i++, ++i, i--, --i
(No Python))