Unit2l4 and l5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

UNIT-2(L4 and L5)

While and For loops


while loop
A while statement is used to execute some block of code repeatedly as long as a condition evaluates
to True.
Following are some features of while loop:
 In the While loop, the value of the expression is evaluated first.
 The body of the loop is entered only when the expression evaluates to true.
 After one iteration, the expression is checked again.
 This process continues until the expression evaluates to False.
 The body of the loop is identified using the indentation with the expression condition as the first
statement.
Examples

It will display Programming is fun! 100 times

Make sure that the loop-continuation-condition eventually becomes false so that the loop will
terminate. Otherwise infinite loops could be there (i.e., the loop runs forever). If your program
takes an unusual long time to run and does not stop, it may have an infinite loop
Practice Question 1
Take an integer num as input from the user. Write a code to find sum of all even numbers up to num
using while construct, print the result to the console as shown in the example.
Solution
num=int(input("num: "))
sum=0
i=1
while(i<=num):
if(i%2==0):
sum=sum+i
i=i+1
print("sum:",sum)
else with while-loop
While loop with else:
 We can have an optional else block with while loop as well.
 The else part is executed if the condition in the while loop evaluates to False.
 The while loop can be terminated with a break statement. In such a case, the else part is ignored.
 Hence, a while loop's else part runs if no break occurs and the condition is False.
Examples
i=100
Output:
while(i>100): Printing message on false condition
print("Printing message on true condition")
else:
print("Printing message on false condition")
---------------------------------------------------------------------------------------------------------------------------------------------------

i=1
while(i<=10): Output:
if(i==2): 1
break
print(i) break statement is there so, else part will not work
i=i+1
else:
print("Printing message on false condition")
Practice Question 2
Take an integer num as input from the console using input() function. Write a
program to find the sum of all integers between 0 and num, both inclusive. Print
the result to the console as shown in the examples.
Solution
# Python program to find the sum of integers between 0 and n where n is provided by
user

num=int(input("num: "))
i=0
sum=0
while(i<=num):
sum=sum+i
i=i+1
else:
while(num<=0):
sum=sum+num
num=num+1
print("sum:",sum)
Practice question 2 : use range() function
Solution:
#Program to illustrate simple range function

# take the input num from the user


num=int(input("num: "))

for i in range(1, num + 1, 2):


print(i)
Practice Question 3
Fill in the missing code in the program below to print a multiplication table up to a maximum of 20 rows. Even
if the number of rows asked by the user is more than 20, we should limit up to 20 rows and print an error
message as shown in the Sample Input Output 2.
Solution
# Multiplication table
x = int(input("x: "))
y = int(input("y: "))

# Fill in the missing code below to print a multiplication table for x upto y rows.
# If y is more than 20, print the relevant message as per instructions and limit the number of
rows to 20
if y>20:
for i in range(1, 21):
print(x, "*", i, "=", x * i)
else:
print("rows is limited to 20")
else:
for i in range(1, y + 1):
print(x, "*", i, "=", x * i)
Miscellaneous Practice Questions
Solution
n=int(input("n: "))
l1=list()
sum1 = 0
for i in range(1, n):
if n % i == 0:
l1.append(i)
sum1=sum1+i
print("factors:",l1)
if sum1 == n:
print("perfect number")
else:
print("not perfect number")
Practice Question
Solution
#Program to print value of pi 1 to 25 decimals
import math
pi = math.pi

# write your code here


n=int(input("n: "))
for i in range(1,n+1):
print('{:.{}f}'.format(pi, i))
Practice Question
Solution:

str1=input("str: ")
x=0
y=0
length=len(str1)
for i in range(0,length):
if(str1[i]=='('):
x=x+1
elif(str1[i]==')'):
y=y+1
if(x==y):
print("valid and depth:",x)
elif y>x:
print("not valid and errors:",y-x)
else:
print("not valid and errors:",x-y)
More Questions to do:
WAP to display the sum of digits of a number
WAP to count digits of a number
WAP to display reverse of a number
WAP to check whether the given number is palindrome or not?
WAP to check whether the given number is armstrong or not( or narcissistic number)?

WAP to check whether the given number is prime or composite?


WAP to display factorial of a number
WAP to display n terms of Fibonacci series
Nested loops
A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner
loops are reentered and started again.
Example:
print(" Multiplication Table")
# Display the number title
print(" |", end='')
for j in range(1, 11):
print(" ", j, end='')
print() # Jump to the new line
print("——————————————————————————————————————————")
# Display table body
for i in range(1, 11):
print(i, "|", end='')
for j in range(1, 11):
print(format(i * j, "4d"), end='')
print() # Jump to the new line
for i in range(1,6): n=int(input("Enter no. of rows:"))
for j in range(1,6): for i in range(1,n+1):
print("*",end='') for j in range(1,i+1):
print() print("*",end='')
print()
n=int(input("Enter no. of rows:")) n=int(input("Enter no. of rows:"))
for i in range(n,0,-1): for i in range(n,0,-1):
for j in range(1,i+1): for j in range(1,i+1):
print("*",end='') print(j,end='')
print() print()
val=65 val=97
n=int(input("Enter no. of rows:")) n=int(input("Enter no. of rows:"))
for i in range(1,n+1): for i in range(n,0,-1):
for j in range(1,i+1): for j in range(1,i+1):
print(chr(val),end='') print(chr(val),end='')
val=val+1 val=val+1
val=65 val=97
print() print()
Display all prime number from n to m
flag = 0
n = int(input("Enter n(>=2):"))
m = int(input("Enter m(>=2):"))
print("List of prime numbers are:")
for i in range(n, m + 1):
for j in range(2, (i // 2)+1):
if i % j == 0:
flag = 1
if flag == 0:
print(i)
flag = 0
Solution:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
matrix1=[[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
print("matrix:",matrix)

# find the transpose of the matrix and print the result as shown in the
example above
for i in range(3):
for j in range(4):
matrix1[j][i]=matrix[i][j]
print("transposed:",matrix1)
More Questions to do:
WAP to display all palindromic numbers from n to m
WAP to display reverse of all even numbers from n to m
WAP to display all perfect numbers from n to m
WAP to display all even list elements from the following list:
list1=[[1,2,3],[4,5,6],[7,8,9]]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy