FP Ta 04
FP Ta 04
December 6, 2024
1 TA Session 4
1.1 For Loops and Nested Loops
prepared by Mohsen Mirzaei
A for loop is used for executing a block of code a predetermined number of times for specific values.
Nested Loops are two or more loops written inside of each other.
for i in range(a, b, c):
The range function in the above example generates integers from a to b (including a but excluding
b) with an increment value of c.
0
1
2
3
4
5
6
7
8
9
0
2
4
1
6
8
num = int(input())
a = int(input())
b = int(input())
3
2
10
2
5
8
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
m
o
2
h
z
e
n
[6]: # for a given integer n, print the sum of integers 1 to j, for every 1 <= j <=␣
↪n.
n = int(input())
s = 0
for i in range(1, n + 1):
for j in range(1, i + 1):
s += j
print(s)
5
1
4
10
20
35
n = int(input())
print(s)
5
1
3
6
10
15
print a triangle using a given string. (WITHOUT MULTIPLYING A STRING BY AN INTEGER)
hint: print(‘a’, end=””)
3
example:
input: abcd
output: a bb ccc dddd
[8]: input_string = input()
character_count = 1
abcd
a
bb
ccc
dddd
n = int(input())
is_found = False
current_num = 1
if sum_of_digits == n:
is_found = True
else:
current_num += 1
print(current_num)
23
599
[2]: # write a program to count the number of prime numbers in a given interval [a,␣
↪b]
4
a = int(input())
b = int(input())
count = 0
if is_prime and i != 1:
count += 1
print(count)
2
13
6
����� ����� ���� �� ����� �������� ��� ���� ��� ��� �� �� ���� ������ ��� ��� .����
[13]: # write a program to count the number of prime numbers whose sum of digits is␣
↪also prime in a given interval [a, b]
a = int(input())
b = int(input())
count = 0
sum_of_digits = 0
for j in str(i):
sum_of_digits += int(j)
5
if is_prime and i != 1:
if is_sum_of_digits_prime and sum_of_digits != 1:
count += 1
print(count)
1
13
5
[14]: # given two integers n and d, find the smallest multiple of n whose largest␣
↪digit is less than or equal to d.
n = int(input())
d = int(input())
current_number = n
while True:
largest_digit = current_number % 10
if largest_digit <= d:
break
current_number += n
print(current_number)
25
1
100