For & while Flashcards
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
k many times
int(input(‘k: ‘)
n = 1
for i in range(int(input(‘k:’))):
print(list(i for i in range(0, n)))
n += 1
Print:[0,1,4,9,16] with while loop (predefined variable)
n = int(input(“Provide an integer: “))
i = 0
while i < n :
print(i**2)
i += 1
Print:[0,1,4,9,16] with while loop (predefined variable + result)
n = int(input(“Provide an integer”))
i = 0
while i < n:
result =i **2
print(result)
i += 1
Print:[0,1,4,9,16] with for loop
number = (int(input(“Provide an integer”))
for i in range(1, number + 1):
square = i ** 2
print(square)
Print: [25] as 5 to the 5th with while loop
n = 6
i = 1
while i <= n:
result =i **2
i += 1
print(result)
Print:[49] as 7 to the 7th with for loop
n = 7
for i in range(1, n + 1):
square = i ** 2
print(square)
Print: while loop
The sum of the numbers starting from 1 to n is: 1
The sum of the numbers starting from 1 to n is: 3
The sum of the numbers starting from 1 to n is: 6
The sum of the numbers starting from 1 to n is: 10
The sum of the numbers starting from 1 to n is: 15
The sum of the numbers starting from 1 to n is: 21
The sum of the numbers starting from 1 to n is: 28
The sum of the numbers starting from 1 to n is: 36
The sum of the numbers starting from 1 to n is: 45
n = 9
result = 0
i = 1
while i <= n:
result += i
i += 1
print(f"The sum of the numbers starting from 1 to n is: {result} ")
Print:
The sum of the numbers starting from 1 to n is: 45
n = 9
result = 0
i = 1
while i <= n:
result += i
i += 1
print(f”The sum of the numbers starting from 1 to n is: {result} “)
Print: while : FACTORIAL
The sum of the numbers starting from 1 to n is: 120
n = 5
result = 1
i = 1
while i <= n:
result *= i
i += 1
print(f”The sum of the numbers starting from 1 to n is: {result} “)
Print: row = 5
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
row = 5
for i in range(1, row + 1, 1):
for j in range(1, i + 1):
print(j)
Print: row = 5
1
1 2
1 2 3
1 2 3 4
12 3 4 5
row = 5
for i in range(1, row + 1, 1):
for j in range(1, i + 1):
print(j, end=’ ‘)
print(“”)
Print: row = 5
1 1 2 1 2 3 1 2 3 4 1 2 3 45
row = 5
for i in range(1, row + 1, 1):
for j in range(1, i + 1):
print(j, end=’ ‘)
Print: row = 5
5
4
3
2
1
4
3
2
1
3
2
1
2
1
1
row = 5
for i in range(0, row + 1):
for j in range(row-i, 0, -1):
print(j, end=’ ‘)
print(‘ ‘)
Print: row = 5
5 4 3 21
4 3 2 1
3 2 1
2 1
1
row = 5
for i in range(0, row + 1):
for j in range(row-i, 0, -1):
print(j, end=’ ‘)
print(‘ ‘)
Print: row = 5
5 4 3 2 1 4 3 2 1 3 2 1 2 11
row = 5
for i in range(0, row + 1):
for j in range(row-i, 0, -1):
print(j, end=’ ‘)
Print:
1
22
333
4444
55555
666666
7777777
88888888
999999999
for i in range(1, 10):
for j in range(0, i):
print(i, end=’ ‘)
print(‘ ‘)