You are on page 1of 27

Week 3

Lecture 3.2

Coding a quiz program :-

Code:-

In this code, the user is getting two chances to answer a question.

Output 1 :-
Output 2 :-

In output 1 the user fails in both the attempts and in output 2 he/she gets the correct answer in
the first attempt itself.

Let's write a piece of code, which lets the user attempt as many times as he/she wants.
The code will end only when the user gets the right answer.

Code :-

Output :-
Difference between if and while loop :-

if —>
Only if the condition is true, then only the statements in the if block will execute.
Example - If it doesn't rain I will go and play.

while —>
If the condition in while is true, the statements in the while loop will keep on executing
until or unless the condition becomes false.
Example - while it doesn't rain I will keep playing.

Lecture 3.3

Computing Factorial of a Number :-

Code :-

Output :-
Explanation of the code :-

n=5 (This is the input)

i=1 (i<n i.e 1<5)


answer = 1 (answer = answer *1 i.e answer = 1*1)

i=2 (2<5)
answer = 2 (1*2)

i=3 (3<5)
answer = 6 (2*6)

i = 4 (4<5)
answer = 24 (6*4)

i = 5 (5<=5)
answer =120 (24*5)

i=6 (6 is not less than 5)


So, line 8 will execute

Lecture 3.4

Tutorials :-
1. Find the factorial of the given number :-

Code :-
Output :-

2. Find the number of digits in the given number :-

Code:-

Output:-
3. Reverse the digit :-

Code:-

Output 1 :-

Output 2 :-
4. Find whether the entered number is a palindrome or not :-

Code :-

Output 1 :-

Output 2 :-
Lecture 3.5

For loop and range :-

range(5) represents the following sequence: 0, 1, 2, 3, 4. In general, range(n) represents


the sequence: 0, 1, ..., n - 1.

Understanding more about for loop :-


Code :-
Output :-

Lecture 3.6

Adding first n positive integers :-

Code :-

Output :-
Lecture 3.7

Loop for multiplication tables :-

Table of 2 -

Code :-

Output :-

Writing the code for printing the table of the entered number -

Code :-
Output :-

Lecture 3.8

More on range and for loop without range :-

Print odd numbers from 1 to 10 -

Range -

range(start, stop, step)

1. range(1,11) in this, default step is 1


2. range(10) in this, default value for start is 0 and step is 1
3. Start and step are optional but writing the value for stop is mandatory
Reverse counting -

Iterating through the strings :-

This particular loop goes through the entire string, character by character, which is stored in the
variable country.

It is similar to the code given below :


Lecture 3.9

Formatted printing :-

Printing numbers 0-9 in the same line in for loop -


end parameter -

Code 1

In code 1,
(end) is used to print in the same line.
The default value of the end parameter of print is \n(new line) but in this case we are telling the
computer to override the default value and consider the ‘space’ as a new value.

Now, while iterating it will print x and add space.

Sep parameter -

Code 2

In code 2
‘sep parameter’ has a default value as a ‘space’ , we can override the value of sep parameter
explicitly mentioning some value.
Here, we mentioned (sep = '\')
But here is a small error : slash between is and 10.

Code 3

But it's in next line , we want to print it in same line


Code 4

Code 4 is completely correct!

F-string :-

Code -

Output -

The ‘f’ in front of the string differentiates f-strings from normal strings. f-string is an
object which when evaluated results in a string. The value of the variable num, i and
num*i is inserted in place of {num} {i} {num*i} in the f-string. Two things are important
for f-strings to do our bidding:

● The f in front of the string.


● The curly braces enclosing the variable.
format() :-

Code -

Output :-

There are three pairs of curly braces. The values that go into these three positions are
given as three arguments in the ‘format function’. Starting from the left, the first pair of
curly braces in the string is replaced by the first argument in ‘format’ , the second pair
by the second argument and so on.

The integer inside the curly braces gives the index of the argument in the format
function. The arguments of the format function are indexed from 0 and start from the
left. Changing the order of arguments will change the output.
Format specifiers :-

Code -

Output -

What if we want the answer up-to 2 decimals only?

Code -

Let us look at the content inside the curly braces: {pi:.2f}. The first part before the : is the
variable. Nothing new here. The part after : is called a format specifier. .2f means the
following:

● . - this signifies the decimal point.


● 2 - since this comes after the decimal point, it stipulates that there should be
exactly two numbers after the decimal point. In other words, the value (pi_approx)
should be rounded off to two decimal places.
● f - this signifies that we are dealing with a float value.
Output -

For a better understanding of this concept, let us turn to printing integers with a specific
formatting. This time, we will use the format function:

Points to note in the code:

● The d stands for integer.


● First three print statements have the index of the argument — 0 in this case —
before the :. Last three statements do not have the index of the argument. In fact
there is nothing before the :. Both representations are valid.
● The 5d after the : means that the width of the column used for printing must be at
least 5.
● Lines 1 to 4 have spaces before them as the integer being printed has fewer than
five characters.
Lecture 3.10

Tutorial on for loop and difference between while loop


and for loop :-

1. Find the factorial of the given number -

Code -

Output -

What are the factors we should consider before deciding whether to use while loop or
for loop?

Do we know the range of the loop in advance or not?


If yes we should use ‘for loop’.

if we don't know how many times the particular loop is going to execute we should use
‘while poop’.
2. Find the number of digits in the given number -

Here we don't know how many times the loop is going to execute.
The digit can have n number of digits so it is not possible to convert it into a for loop.

But we can use ‘for each’.

Code-

Output -

3. Reverse the digit -

Code-
Output -

4 Find whether the digit is a palindrome or not -

Code-

Output -

Here, we used ‘for each’ loop for the questions but this is not the best method.
Let’s see what is the most convenient way of using loops for different questions -

Lecture 3.11

Nested for loop :-


There are two brothers who wear t-shirts of either of the colors in VIB(Violet, Indigo,
Blue) . Can we tell what are the possible combinations they can wear?
Code -

Output -
Lecture 3.13

Break , continue and pass :-

Break -

The break statement is used to exit out of a loop without executing any code that comes
below it.

Continue -
The continue statement is used to move to the next iteration of the loop, skipping
whatever code comes below it.

Pass -

In Python, pass is a null statement. The interpreter does not ignore a pass statement,
but nothing happens and the statement results in no operation.
Lecture 3.12

Codes of tutorials on nested loops :-

1 Find all prime numbers less than the entered number -

num = int(input('Enter a number'))


if(num>2):
print(2,end=' ')
for i in range (3,num):
flag = False
for j in range(2,i):
if(i%j==0):
flag = False
break
else:
flag =True
if(flag):
print(i,end=' ')

2 Find the total profit/loss for each trader in the trading firm

emp_id = input('Enter the employee Id: ')


while emp_id != -1:
trade = int(input('Enter the trade amount:'))
profit_loss= 0
while trade!=0:
profit_loss += trade
trade = int(input('Enter the trade amount: '))
print(f'Profit/loss for employee {emp_id} is {profit_loss}')
emp_id = input('\n Enter employee Id')
3 Find the day wise total rainfall for the entered duration of time eg week month,etc

days = int(input('Enter the number of days: '))


for i in range(1,days+1):
total = 0
rainfall=int(input('Enter rainfall : '))
while rainfall != -1:
total = total +1
rainfall = int(input('Enter rainfall'))
print('Total rainfall for day {0} is {1}' .format(i,total))

4 Find the length of the longest word from the set of words entered

word = input('Enter the word: ')


maxLen = 0
while word != '-1':
count= 0
for letter in word:
count = count +1
if (count>maxLen):
maxLen = count
word = input('Enter a word: ')
print('Length of the longest word is', maxLen)

You might also like