Week 3: Python Loops (While,
For)
Graded Assignment Solutions
Python Programming
by Gen-Z IITian
About & Quick Links
n
Gen-Z IITian by Sriram
Topic: Python Loops - Graded Assignment Solutions
ia
YouTube: Gen-Z IITian
I IT
Personal YouTube: SriRam in
Instagram: @curious sri
Community: IITM BS Unofficial Community
Resources: IIT Pathshala Study Materials
Best Lecture: Foundation Term-1 Course
-Z
en
G
YouTube — Website — WhatsApp — Course
Question
Question 1: What is the output of the following snippet of code?
Python Code
1 for char in ' a1b2c3d4e5 ':
2 if char in ' abcde ':
3 print ( '| ' , end = '') # there is no space
between the quotes
4 continue
5 print ( char , end = ' ') # there is no space
between the quotes
n
6 print ( '| ')
ia
Options:
1. 12345
I IT
2. |||||
3. |1|2|3|4|5
4. 1|2|3|4|5|
5. |1|2|3|4|5|
Answer
-Z
Answer: |1|2|3|4|5|
en
G
YouTube — Website — WhatsApp — Course
Question
Question 2: Select the correct implementation of a program that
accepts a positive integer x as input and prints the maximum value of
the integer y such that 2y ≤ x.
Sample Test Cases:
• Input: 100, Output: 6
• Input: 256, Output: 8
Options:
Python Code
x = int ( input () )
n
1
2 y = 0
while x > 1:
ia
3
4 x = x // 2
5 y = y + 1
I IT
6 print ( y )
1.
Python Code
1 x = int ( input () )
y = 0
-Z
3 while x >= 1:
4 x = x // 2
y = y + 1
en
6 print ( y )
2.
G
Python Code
1 x = int ( input () )
2 y = 0
3 while x > 1:
4 x = x / 2
5 y = y + 1
6 print ( y )
3.
Python Code
1 x = input ()
2 y = 0
3 while x > 1:
4 x = x // 2
5 y = y + 1
6 print ( y )
4.
YouTube — Website — WhatsApp — Course
Answer
Answer: Option 1
Python Code
1 x = int ( input () )
2 y = 0
3 while x > 1:
4 x = x // 2
5 y = y + 1
6 print ( y )
n
ia
Question
Question 3: Consider the following snippet of code:
I IT
Python Code
1 x = int ( input () )
2 i = 0
3 while x % (10 ** i ) != x:
i = i + 1
-Z
5 print ( i )
en
What will the variable i represent at the end of execution where x is a
positive integer?
Options:
1. Number of zeros in x
G
2. Number of ones in x
3. Number of digits in x
4. Number of non-zero digits
Answer
Answer: Number of digits in x
YouTube — Website — WhatsApp — Course
Question
Question 4: What is the output of the following snippet of code?
Python Code
1 alpha = ' abcdefghijklmnopqrstuvwxyz '
2 shift = 5
3 word = ' python '
4 encoded_word = ' ' # there is no space between
quotes
5 for char in word :
6 shifted_index = ( alpha . index ( char ) + shift ) %
n
26
7 encoded_char = alpha [ shifted_index ]
ia
8 encoded_word += encoded_char
9 print ( encoded_word )
I IT
Options:
1. stmydu
2. tcxlsr
3. veznut
4. udymts
-Z
Answer
Answer: udymts
en
G
YouTube — Website — WhatsApp — Course
Question
Question 5: Consider the following snippet of code.
Python Code
1 name = input ()
2 nick = ' ' # there is no space between the
quotes
3 space = '␣ ' # there is one space between the
quotes
4 first_char = True
5 for char in name :
n
6 if first_char == True :
7 nick = nick + char
ia
8 first_char = False
9 if char == space :
first_char = True
I IT
10
11 print ( nick )
What is the output for the following input?
Albus Percival Brian Wulfric Dumbledore
Options:
-Z
1. Albus
2. Dumbledore
3. AP
en
4. APBWD
Answer
G
Answer: APBWD
YouTube — Website — WhatsApp — Course
Question
Common Data for Questions 6 and 7:
Consider the following snippet of code:
Python Code
1 word = input ()
2 valid = True
3 for i in range ( len ( word )) :
4 char = word [ i ]
5 if i % 2 == 0 and char not in ' aeiou ':
6 valid = False
n
7 print ( valid )
Question
ia
I IT
Question 6: Select all inputs for which the code prints True as the
output. (MSQ)
Options:
1. abet
2. enamel
-Z
3. eatery
4. onetime
en
Answer
Answer: abet, enamel, onetime
G
YouTube — Website — WhatsApp — Course
Question
Question 7: Assume that a ten letter word is passed as input to the
code. If the output is True, then which of the following statements
about the input word are true?
Options:
1. The word has exactly five vowels.
2. The word has have at least five vowels.
3. The letters at even indices are vowels. Assume that we use zero-
based indexing.
4. Every vowel in the word appears only at even indices. Assume
that we use zero-based indexing.
n
Answer
ia
Answer:
• The word has have at least five vowels.
I IT
• The letters at even indices are vowels. Assume that we use zero-
based indexing.
-Z
en
G
YouTube — Website — WhatsApp — Course
Question
Question 8: There is a collection of boxes, each box containing certain
number of coins. This information is represented as a string such as
this: ’|1|4|1|5|9|’. Here, there are five boxes. The first box has one
coin, second has four coins and so on. Assume that each box has at
least one coin and at most nine coins.
Select the correct implementation of a snippet of code that computes
the average number of coins across the boxes and stores it in a variable
named avg. Assume that the string boxes is already given to you and
that there is at least one box in the collection.
Options:
n
Python Code
ia
1 num = 0
2 total = 0
I IT
3 for i in range ( len ( boxes ) ) :
4 if i % 2 == 0:
5 continue
6 coins = boxes [ i ]
7 total += coins
8 num += 1
avg = total / num
-Z
1.
Python Code
en
1 num = 0
2 total = 0
G
3 for i in range ( len ( boxes ) ) :
4 if i % 2 == 0:
5 continue
6 coins = int ( boxes [ i ])
7 total += coins
8 num += 1
9 avg = total / num
2.
Python Code
1 num = 0
2 total = 0
3 for coins in boxes :
4 total += coins
5 num += 1
6 avg = total / num
3.
Python Code
YouTube — Website — WhatsApp — Course
Answer
Answer: Option 2
Python Code
1 num = 0
2 total = 0
3 for i in range ( len ( boxes ) ):
4 if i % 2 == 0:
5 continue
6 coins = int ( boxes [ i ])
7 total += coins
n
8 num += 1
9 avg = total / num
ia
I IT
-Z
en
G
YouTube — Website — WhatsApp — Course
Question
Question 9: The first five terms of the Fibonacci sequence is given
below.
F1 = 1, F2 = 1, F3 = 2, F4 = 3, F5 = 5
We wish to write a program that accepts a positive integer n as input
and prints Fn as the output. Select all correct implementations of this
program. (MSQ)
Options:
Python Code
n
1 n = int ( input () )
2 F_prev = 1
ia
3 F_curr = 1
4 count = 2
while count < n :
I IT
5
6 temp = F_prev + F_curr
7 F_prev = F_curr
8 F_curr = temp
9 count += 1
10 print ( F_curr )
1.
-Z
Python Code
en
1 n = int ( input () )
2 if n <= 2:
3 print (1)
4 else :
G
5 F_prev = 1
6 F_curr = 1
7 count = 2
8 while count < n :
9 temp = F_prev + F_curr
10 F_prev = F_curr
11 F_curr = temp
12 count += 1
13 print ( F_curr )
2.
Python Code
1 n = int ( input () )
2 F_prev = 1
3 F_curr = 1
4 for i in range ( n ) :
5 temp = F_prev + F_curr
6 F_prev = F_curr
7 F_curr = temp
8 print ( F_curr
YouTube — ) Website — WhatsApp — Course
Answer
Answer: Options 1, 2, and 4
Question
Common Data for Questions 10 and 11:
Consider the following snippet of code:
Python Code
1 for x in range (100) :
2 for y in range (100) :
n
3 if x != y :
4 print ( f '{ x } ,{ y } ')
ia
I IT
Question
Question 10: When the code given above is executed, how many lines
will the output have? (NAT)
Answer
-Z
Answer: 9900
en
G
YouTube — Website — WhatsApp — Course
Question
Question 11: Among the code blocks given below, select the correct
equivalent implementation of the code given in the common data.
Options:
Python Code
1 x, y = 0, 0
2 while x < 100:
3 while y < 100:
4 if x != y :
print ( f '{ x } ,{ y } ')
n
5
1.
ia
Python Code
I IT
1 x, y = 0, 0
2 while x < 100:
3 while y < 100:
4 if x != y :
5 print ( f '{ x } ,{ y } ')
6 x += 1
y += 1
-Z
2.
Python Code
en
1 x, y = 0, 0
2 while x < 100:
while y < 100:
G
4 if x != y :
5 print ( f '{ x } ,{ y } ')
6 y += 1
7 x += 1
3.
Python Code
1 x, y = 0, 0
2 while x < 100:
3 while y < 100:
4 if x != y :
5 print ( f '{ x } ,{ y } ')
6 y += 1
7 x += 1
4.
Python Code
1 x, y = 0, 0
YouTube — Website — WhatsApp — Course
2 while x < 100:
Answer
Answer: Option 5
Python Code
1 x, y = 0, 0
2 while x < 100:
3 y = 0
4 while y < 100:
5 if x != y :
6 print ( f '{ x } ,{ y } ')
7 y += 1
n
8 x += 1
ia
I IT
-Z
en
G
YouTube — Website — WhatsApp — Course
Week 3: Python Loops
GRPA Solutions
Python Programming
by Gen-Z IITian
About & Quick Links
Gen-Z IITian by Sriram
Topic: Python Loops - GRPA Solutions
n
YouTube: Gen-Z IITian
ia
Personal YouTube: SriRam in
Instagram: @curious sri
I IT
Community: IITM BS Unofficial Community
Resources: IIT Pathshala Study Materials
Best Lecture: Foundation Term-1 Course
-Z
en
G
YouTube — Website — WhatsApp — Course
GRPA 1: While Loops - Indefinite Iteration
Important Note on while loop:
Use while only when the number of iterations is indefinite.
If you can term the steps as ”do n times”, ”do once for each item”, etc. use
for loop instead.
If you can only term the steps as ”do until something happens”, use while
loop.
Question
Problem Statement:
Implement different parts of a multi-functional program based on an
n
initial input value. Each part of the program will handle various tasks
related to accumulation, filtering, mapping, and combinations of these
ia
operations. None of the tasks should use explicit loops for definite
repetitions, and the program should handle indefinite inputs gracefully.
I IT
Tasks:
• Accumulation - Accumulating a final result
• Filtering - Selecting based on a criterion
• Mapping - Applying the same operation to different items
• Filter and Map - Applying an operation to selected items
• Filter and Accumulate - Accumulating a result with selected
-Z
items
en
G
YouTube — Website — WhatsApp — Course
Template
Python Code
1 if task == sum_until_0 :
2 total = 0
3 n = int ( input () )
4 while ...: # the terminal condition
5 ... # add n to the total
6 ... # take the next n form the input
7 print ( total )
8
n
9 elif task == total_price :
10 total_price = 0
ia
11 while ...: # repeat forever since we are
breaking inside
12 line = input ()
I IT
13 if ...: # The terminal condition
14 break
15 quantity , price = line . split () # split
uses space by default
16 quantity , price = ... # convert to ints
17 ... # accumulate the total price
print ( total_price )
-Z
18
19 elif task == only_ed_or_ing :
20 ...
21
en
22 elif task == reverse_sum_palindrome :
23 ...
24
elif task == double_string :
G
25
26 ...
27
28 elif task == odd_char :
29 ...
30
31 elif task == only_even_squares :
32 ...
33
34 elif task == only_odd_lines :
35 ...
YouTube — Website — WhatsApp — Course
Answer
Python Code
1 # # Note this prefix code is to verify that you
are not using any for loops in this exercise .
This won 't affect any other functionality of
the program .
2 with open ( __file__ ) as f:
3 content = f . read () . split ( # ␣ <eoi > ) [2]
4 if for ␣ in content :
5 print ( You ␣ should ␣ not ␣ use ␣ for ␣ loop ␣ or ␣ the ␣
word ␣ for ␣ anywhere ␣ in ␣ this ␣ exercise )
n
6
# This is the first line of the exercise
ia
7
8 task = input ()
9 # <eoi >
I IT
10
11 if task == sum_until_0 :
12 total = 0
13 n = int ( input () )
14 while n != 0:
15 total += n
n = int ( input () )
-Z
16
17 print ( total )
18
19 elif task == total_price :
en
20 total_price = 0
21 while True :
22 line = input ()
if line == END :
G
23
24 break
25 quantity , price = line . split ()
26 quantity , price = int ( quantity ) , int (
price )
27 total_price += quantity * price
28 print ( total_price )
29
30 elif task == only_ed_or_ing :
31 result = []
32 while True :
33 word = input () . strip ()
34 if word . lower () == stop :
35 break
36 if word . endswith ( ed ) or word . endswith (
ing ) :
37 result . append ( word )
38 print ( \ n . join ( result ) )
39
40 elif task == reverse_sum_palindrome :
41 def is_palindrome (n ):
42 sYouTube
= str—
( n )Website — WhatsApp — Course
GRPA 2: For Loops - Definite Iteration
Bit of Wisdom : In context of general incremental definite loops the struc-
ture of while loop can be converted to a for loop using range.
Python Code
1 ## the while loop
2 i = 0 # initialization
3 while i < 10: # condition
4 print ( i ) # body
5 i += 2 # update
n
6
7 # same with for loop
for i in range (0 , 10 , 2) : # range combines
ia
8
initialization , termination and update
9 print ( i )
I IT
-Z
en
G
YouTube — Website — WhatsApp — Course
Question
Problem Statement:
Write a multi functional program that takes input task from standard
input and does the corresponding task accordingly. Note that the usage
of while loop is not allowed in this exercise.
Part 1 - while loop to for loop:
• factorial - print factorial of a given non-negative integer n (Type:
Accumulation)
• even numbers - Print the even numbers from 0 (including) till
the given input number n(including) in multiple lines (Type: Just
Iterating)
n
• power sequence - Print the sequence 1, 2, 4, 8, 16, ... n terms in
same line in multiple lines, where n is taken from the input(Type:
ia
Mapping)
Part 2 - for loop With range:
• sum not divisible - Print the sum of positive less that the given
I IT
number n and not divisible by 4 and 5. (Type: Filtered Accu-
mulation)
• from k - Starting from 100 and going in the decreasing order,
print the reverse(digits reversed) of first n numbers starting from
k which do not have the digit 5 and 9 and is odd number in
multiple lines.
-Z
Part 3 - for loop with iterables:
• string iter - Given a string s of digits print the numerical value
of the digit multiplied by the previous digit. Assume the previous
en
digit for the first element to be 1.
• list iter - Print the elements of a list l line by line in the format
{element} - type: {type} where the element is the current ele-
G
ment being iterated by the for loop and type is the type of the
element.
YouTube — Website — WhatsApp — Course
Template
Python Code
1 if task == ' factorial ':
2 n = int ( input () )
3 result = 1
4 i = 1
5 while i <= n :
6 result *= i
7 i +=1
8 print ( result )
n
9 elif task == ' even_numbers ':
10 n = ...
ia
11 while i < n +1:
12 print ( i )
13 i +=2
I IT
14
15 elif task == ' power_sequence ':
16 n = ...
17 result = 1
18 while i < n :
19 print ( result )
result *=2
-Z
20
21 i +=1
22
23 elif task == ' sum_not_divisible ':
en
24 ...
25
26 elif task == ' from_k ':
...
G
27
28
29 elif task == ' string_iter ':
30 ...
31
32 elif task == ' list_iter ':
33 lst = eval ( input () ) # this will load the list
from input
34
35 else :
36 print ( Invalid )
YouTube — Website — WhatsApp — Course
Answer
Python Code
1 # # Note this prefix code is to verify that you
are not using any for loops in this exercise .
This won 't affect any other functionality of
the program .
2 with open ( __file__ ) as f:
3 content = f . read () . split ( # ␣ <eoi > ) [2]
4 if while ␣ in content :
5 print ( You ␣ should ␣ not ␣ use ␣ while ␣ loop ␣ or ␣ the ␣
word ␣ while ␣ anywhere ␣ in ␣ this ␣ exercise )
n
6
# your code should not use more than 7 for loops
ia
7
8 # assuming one for loop per problem
9 if content . count ( for ␣ ) >7:
I IT
10 print ( You ␣ should ␣ not ␣ use ␣ more ␣ than ␣ 7␣ for ␣
loops )
11
12 # This is the first line of the exercise
13 task = input ()
14 # <eoi >
-Z
15
16 if task == ' factorial ':
17 n = int ( input () )
18 result = 1
en
19 for i in range (1 , n +1) :
20 result *= i
21 print ( result )
G
22
23 elif task == ' even_numbers ':
24 n = int ( input () )
25 for i in range (0 , n +1 , 2) :
26 print ( i )
27
28 elif task == ' power_sequence ':
29 n = int ( input () )
30 result = 1
31 for i in range (1 , n +1 , 1) :
32 print ( result )
33 result *= 2
34
35 elif task == ' sum_not_divisible ':
36 n = int ( input () )
37 sum = 0
38 for i in range (1 , n ):
39 if i % 4 != 0 and i % 5 != 0:
40 sum += i
41 print ( sum )
42
43 elif taskYouTube
== ' from_k ':
— Website — WhatsApp — Course
GRPA 3: Nested Loops - Patterns and Per-
mutations
Question
Problem Statement:
Create a multi-functional program that performs different tasks based
on the user input. The program should support the following tasks:
• Permutation (permutation): Given a string s, print all the
possible two-letter permutations(without repetition) of the let-
ters in the string.
• Sorted Permutation (sorted permutation): Given a string
n
s, print all the possible two-letter permutations(without repeti-
tion) of the letters in the string where the first character comes
ia
before the second one in alphabetical order.
• Repeat the Repeat (repeat the repeat): Given a number
I IT
n, print the numbers from 1 to n in the same line and repeat this
n times.
• Repeat Incrementally (repeat incrementally): Given a
number n, print a pattern where the k-th line contains the first
k numbers and there are n lines in total.
• Increment and Decrement (increment and decrement):
-Z
Given a number n, print a pattern where the k-th line should
have the numbers from 1 to k and then back down to 1.
en
G
YouTube — Website — WhatsApp — Course
Template
Python Code
1 task = input ()
2
3 if task == permutation :
4 ...
5 elif task == sorted_permutation :
6 ...
7 elif task == repeat_the_repeat :
8 ...
n
9 elif task == repeat_incrementally :
10 ...
ia
11 elif task == increment_and_decrement :
12 ...
13 else :
I IT
14 print ( invalid )
-Z
en
G
YouTube — Website — WhatsApp — Course
Answer
Python Code
1 task = input ()
2
3 if task == permutation :
4 word = input ()
5 for i in range ( len ( word )) :
6 for j in range ( len ( word )) :
7 if word [i ] != word [ j ]:
8 print ( f { word [i ]}{ word [j ]} )
n
9
10 elif task == sorted_permutation :
word = input ()
ia
11
12 for i in word :
13 for j in word :
I IT
14 if i < j :
15 print (i + j )
16
17 elif task == repeat_the_repeat :
18 n = int ( input () )
19 for i in range ( n) :
for j in range (1 , n +1) :
-Z
20
21 print (j , end = )
22 print ()
23
en
24 elif task == repeat_incrementally :
25 row = int ( input () )
26 for i in range (1 , row +1) :
for j in range (1 , i +1) :
G
27
28 print (j , end = )
29 print ()
30
31 elif task == increment_and_decrement :
32 n = int ( input () )
33 for i in range (1 , n +1) :
34 for j in range (1 , i +1) :
35 print (j , end = )
36 for j in range (i -1 , 0, -1) :
37 print (j , end = )
38 print ()
39
40 else :
41 print ( invalid )
YouTube — Website — WhatsApp — Course
GRPA 4: Loop Applications - Problem Solving
Question
Problem Statement:
You are tasked with writing a program that can handle various tasks
based on the input. The first line of the input represents the task to
be performed. The possible tasks are:
• factors - Find the factors of a number n (including 1 and itself)
in ascending order.
• find min - Take n numbers from the input and print the mini-
mum number.
• prime check - Check whether a given number is prime or not.
n
• is sorted - Check if all characters of the given string from input
ia
are in alphabetical order. Print the output as ”True” or ”False”
accordingly.
• any true - Take n numbers from input and check if any of the
I IT
numbers are divisible by 3. Print the output as ”True” or ”False”
accordingly.
• manhattan - Take inputs directions such as ”UP”, ”DOWN”,
”LEFT” and ”RIGHT” from the input until the input is
”STOP”. Assume you are starting from (0,0) in a cartesian coor-
dinate. Find the Manhattan distance between the starting point
-Z
and the ending point by following the steps in the cartesian plane.
en
G
YouTube — Website — WhatsApp — Course
Template
Python Code
1 # # this is to ensure that you cannot use the
built in any , all and min function for this
exercise but you can use it in the OPPEs .
2 any = None
3 all = None
4 min = None
5
6 task = input ()
n
7
8 if task == factors :
ia
9 ...
10 elif task == find_min :
11 ...
I IT
12 elif task == prime_check :
13 ...
14 elif task == is_sorted :
15 ...
16 elif task == any_true :
17 ...
elif task == manhattan :
-Z
18
19 ...
en
G
YouTube — Website — WhatsApp — Course
Answer
Python Code
1 # # this is to ensure that you cannot use the
built in any , all and min function for this
exercise but you can use it in the OPPEs .
2 any = None
3 all = None
4 min = None
5
6 task = input ()
n
7
8 if task == factors :
n = int ( input () )
ia
9
10 for i in range (1 , n +1) :
11 if n % i == 0:
I IT
12 print ( i)
13
14 elif task == find_min :
15 n = int ( input () )
16 min_ = 10000000000
17 for i in range ( n ):
num = int ( input () )
-Z
18
19 if min_ > num :
20 min_ = num
21 print ( min_ )
en
22
23 elif task == prime_check :
24 n = int ( input () )
flag = True
G
25
26 if n != 2:
27 for i in range (2 , n //2) :
28 if n % i == 0:
29 flag = False
30 break
31 if flag :
32 print ( True )
33 else :
34 print ( False )
35
36 elif task == is_sorted :
37 word = input ()
38 word_sorted = ''. join ( sorted ( word ))
39 if word == word_sorted :
40 print ( True )
41 else :
42 print ( False )
43
44 elif task == any_true :
45 flag = False
46 n = YouTube
int ( input
— () )
Website — WhatsApp — Course