0% found this document useful (0 votes)
10 views

Python unit-2 notes (1)

This document provides an overview of flow control in Python, focusing on conditional blocks (if, elif, else) and loop control statements (for, while). It includes examples of nested if statements, the use of break and continue statements, and various programming exercises to illustrate these concepts. Additionally, it discusses the pass statement and includes examples of patterns created using loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python unit-2 notes (1)

This document provides an overview of flow control in Python, focusing on conditional blocks (if, elif, else) and loop control statements (for, while). It includes examples of nested if statements, the use of break and continue statements, and various programming exercises to illustrate these concepts. Additionally, it discusses the pass statement and includes examples of patterns created using loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

unit-2

Flow Control of Conditional blocks:


In Python, conditional blocks are used to control the flow of a program based
on certain conditions. The primary constructs for creating conditional blocks in
Python are if, elif , and else. These constructs allow you to execute different
code blocks depending on whether specific conditions are true or false.
if Statement: if statement is used to execute a block of code if a specified
condition is True. If the condition is False, the block is skipped.
elif Statement: The elif statement is used in conjunction with if to test multiple
conditions sequentially. It allows you to check additional conditions if the
previous if or elif conditions are False. You can have multiple elif blocks.
else Statement: The else statement is used to specify a block of code that
should be executed when none of the preceding if or elif conditions are True.
Structure :
if condition1:
# Code will execute if condition1 is True
elif condition2:
# Code will execute if condition1 is False and condition2 is True
elif condition3:
# Code will execute if condition1 and condition2 are False, and condition3 is
True
else # Code will execute if condition1 2 and 3 are False

FLOWCHART:
Example-1:
Q.What message will be printed if the temperature is 25 degrees Celsius?
temperature = 25
if temperature >50:
print("It is hot outside.")
elif temperature >30:
print("It is a normal day.")
else:
print("It is cool outside.")
=>Since the temperature variable (25) does not satisfy the conditions of the if
or elif statements, the code will execute the else block. Therefore, the output
will be.
It is cool outside.
example-2:
Q.2 Create a simple authentication system in Python where the user is asked
to enter a username and password. If the username is "admin" and the
password is "password123", print "Access granted." Otherwise, print "Access
denied."?
ANS: # Define the correct username and password
correct_username = "admin"
correct_password = "password123"
username = input("Enter your username: ")
password = input("Enter your password: ")
# Check if the entered username and password match the correct ones
If username == correct_username and password == correct_password:
print("Access granted.")
else:
print("Access denied.")

nested if statements:
you can use nested if statements to create multiple levels of conditional
statements. Nested if statements allow you to check conditions within
conditions. You can have as many levels of nesting as needed, but it's
important to maintain proper indentation to indicate the level of nesting.

Example-1
Q. Write a java program that uses nested if statements to check if x is greater
than 5 and if y is greater than 2. If both conditions are met, print 'x is greater
than 5, and y is also greater than 2.' If x is not greater than 5, print 'x is not
greater than 5.?
x = 10
y=5
if x > 5:
print("x is greater than 5")
if y > 2:
print("y is also greater than 2")
else:
print("y is not greater than 2")
else:
print("x is not greater than 5")
# Output:
# x is greater than 5
# y is also greater than 2
Example -2
Q.Write a Python program that checks whether a person is eligible for a loan
or not based on two variables: age and income. If the age is 18 or older and
the income is 30000 or higher, the program should print 'You are eligible for a
loan.' Otherwise, it should print 'You are not eligible for a loan.' Provide the
code for this program.
age = 25
income = 50000
if age >= 18:
if income >= 30000:
print("You are eligible for a loan.")
else:
print("Your income is too low for a loan.")
else:
print("You are underage for a loan.")
# Output:# You are eligible for a loan.

Loop Control Statements:

A loop in Python is a control structure that allows you to repeatedly


execute a block of code as long as a certain condition is true (in the case
of a while loop) or for each item in a sequence or iterable (in the case of
a for loop). Loops are used for automating repetitive tasks and iterating
through collections of data. There are two main types of loops in Python:
for loops and while loops.

for Loop:

A for loop in Python is used to iterate over a sequence or an iterable


object, such as a list, tuple, string, or range. It allows you to execute a
block of code for each item in the sequence. The loop continues until all
the elements in the sequence have been processed.

Example:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)
o/p
apple
banana
cherry
FLOWCHART:
while Loop:

A while loop in Python is used to repeatedly execute a block of code as


long as a specified condition is true. It continues to execute the code
block until the condition becomes false. Be careful when using while
loops to avoid infinite loops, which can lead to your program running
indefinitely.

Flowchart definition:
A flowchart is a visual representation of a process or system using
symbols and connecting lines. It helps illustrate the sequence of steps,
decisions, and inputs in a clear and organized manner.

Example:

Question: w.a.p to print number 1 to 5

count = 1
while count <= 5:
print(count)
count += 1
o/p
1
2
3
4
5
Question: Write a Python program (WAP) to print the numbers from 1 to 20 using a loop.
Please provide the code for your program.

for num in range(1, 21):


print(num)
Question: Write a Python program (WAP) to print even numbers from 1 to 20 using a loop.
Please provide the code for your program.

for num in range(1, 21):


if num % 2 == 0:
print(num)
Question: Write a Python program (WAP) to calculate the sum of the digits of a given
number. The program should accept a positive integer as input and then compute and
display the sum of its digits

number = int(input("Enter a positive integer: ")


sum = 0
while number!= 0:
digit = number % 10
sum = sum+digit
number = number//10
print("The sum of the digits is:", sum)
Question: Write a Python program (WAP) to reverse the digits of a given positive integer.
The program should accept a positive integer as input and then compute and display the
reverse of its digits.

number = int(input("Enter a positive integer: "))


sum = 0
while number != 0:
digit = number % 10
sum = sum * 10 + digit
number = number // 10
print("The reversed number is:", sum)
Question: Write a Python program (WAP) to convert a binary number to its decimal
equivalent. The program should accept a binary number as input and then compute and
display its decimal equivalent

# binary to decimal
num=int(input("enter a number"))
sum=0
i=0
while num!=0:
rem=num%10
sum=sum+rem*(2**i)
i=i+1
num=num//10
print("decimal number is ",sum)
Question: Write a Python program (WAP) to convert a decimal number to its binary
equivalent. The program should accept a decimal number as input ?

# decimal to binary
num=int(input("enter a decimal number"))
sum=0
i=0
while num!=0:
rem=num%2
sum=sum+rem*(10**i)
i=i+1
num=num//2
print("binary number is ",sum)

Example: Using for Loop with List, Set, and Dictionary


# List example :
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Set example :
colors = {"red", "green", "blue"}
for color in colors:
print(color)

nested loops:
In Python, you can create nested loops by placing one loop inside another.
Nested loops are often used for tasks that require iterating through multiple
dimensions, such as two-dimensional arrays or nested data structures.
Example:
Q. W.A.P to print this pattern in python?

***
***
***
for i in range(0,3):
for j in range(0,3):
print("*", end=" ")
print()

Q. W.A.P to print this pattern in python?


*

**

***

for i in range(0,3):
for j in range(0,i):
print("*", end=" ")
print()

break statement:
• The break statement is used to exit the current loop prematurely.
• When a break statement is encountered, it immediately terminates the
loop, and control is transferred to the next statement after the loop.
• It is often used when you want to stop a loop early based on a certain
condition.
Example of break:
for i in range(10):
if i == 5:
break
print(i)

In this example, the loop will terminate when i becomes 5, and the
numbers 0 to 4 will be printed.
continue statement:
•The continue statement is used to skip the rest of the current
iteration and move to the next iteration of the loop.
• When a continue statement is encountered, it skips the remaining
code within the current iteration and starts the next iteration of
the loop.
• It is often used to bypass certain iterations based on specific
conditions.
Example of continue:

for i in range(10):
if i % 2 == 0:
continue
print(i)
o/p
1
3
5
7
9
In this example, the continue statement is used to skip even numbers, so
only odd numbers from 1 to 9 will be printed.

Both break and continue are powerful tools for controlling the flow of
loops in Python and can be used to make your code more efficient and
flexible

Example 1: Using break to exit a loop when a condition is met:

while True:
user_input = input("Enter a number or 'q' to quit ")
if user_input == 'q':
break # Exit the loop if the user enters 'q'
number = int(user_input)
print(“your number was ”,number)

In this example, the break statement is used to exit the while loop when
the user enters 'q'.

Example 2: Using continue to skip processing in a loop:


for i in range(1, 11):
if i % 3 == 0:
continue # Skip this iteration if i is divisible by 3
print(i)

In this example, the continue statement is used to skip printing numbers


that are divisible by 3.

Example 3: Using break in a nested loop:


for i in range(0,3):
for j in range(0,3):
if j == 2:
break # Exit the inner loop when j is 3
print(f"({i}, {j})")
#Output
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

in this example, the break statement is used to exit the inner loop when
j is equal to 3. The outer loop continues running.

Example 4: Using continue in a nested loop:


for i in range(0,3):
for j in range(0,3):
if j == 1:
continue # Skip this iteration of the inner loop when j is 3
print(f"({i}, {j})")
#output
(0, 0)
(0, 2)
(1, 0)
(1, 2)
(2, 0)
(2, 2)

pass statement
in Python, the pass statement is a null operation or a no-op. It does
nothing when it is executed. You can use the pass statement as a
placeholder when you need a statement syntactically but don't want to
perform any action. This can be particularly useful in situations where
you are designing code structure or leaving a function, class, or loop
body empty for later implementation.

Empty Loop: You can use pass to create a loop that doesn't execute any
specific code but is used as a placeholder for a loop body.
for item in some_list:
pass # Placeholder, no action

Empty Function: You can use pass to define a function that doesn't
perform any action initially, but you might plan to add code to it later.
def some_function():
pass # Placeholder for future code

Empty Class: Similarly, you can use pass in a class definition when you
are creating the structure of a class but don't have the implementation
details yet
class SomeClass:
pass # Placeholder for class structure

Conditional Statements: You can use pass in conditional statements to


have a branch that does nothing.
if condition:
pass # Placeholder for future code
else:
print("Else block executed")
#Code based on pattern#
Q.w.a.p to print pattern given below in
python?
n=5
for i in range(0,n):
for j in range(0,i):
print(i,end="")
print()

-
1
22
333
4444
################################################################
n=5
for i in range(0,n):
for j in range(0,i):
print(j,end="")
print()
0
01
012
0123
################################################################

################################################################
n=5
for i in range(0,n):
for j in range(0,n-i):
print(" ",end="")
for j in range(0,i):
print("*",end="")
print()
*
**
***

n=5
for i in range(0,n):

for j in range(0,n-i):
print(" ",end="")
for j in range(0,2*i-1):
print("*",end="")
print()
*
***
*****

n=5
for i in range(0,n):

for j in range(0,n-i):
print(" ",end="")
for j in range(0,2*i-1):
print(j,end="")
print()
0
012
01234
0123456
################################################################
n=5
c=65
for i in range(0,n):
for j in range(0,n):
print(chr(c),end="")
c=c+1
print()
print(" Z")
ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
Z

################################################################
n=5
c=65
for i in range(0,n):
for j in range(0,n):
print(chr(c),end="")
c=c+1
print()
AAAAA
BBBBB
CCCCC
DDDDD
EEEEE
################################################################
for i in range(65,91):
print(chr(i),end="")
ABCDEFGHIJKLMNOPQRSTUVWXYZ
################################################################
n=7
for i in range(1,n):
print("PASS",i," - ",end="")
for j in range(1,n):
print(j,end=" ")
print()

PASS 1 - 1 2 3 4 5 6
PASS 2 - 1 2 3 4 5 6
PASS 3 - 1 2 3 4 5 6
PASS 4 - 1 2 3 4 5 6
PASS 5 - 1 2 3 4 5 6
PASS 6 - 1 2 3 4 5 6
################################################################
1
121
12321
1234321
n=6
for i in range(1,n):
for j in range(1,n-i):
print(" ",end="")
for j in range(1,i):
print(j,end="")
for j in range(i-2,0,-1):
print(j,end="")
print()

Problems on loops
Q.W.A.P TO PRINT THIS?
0123
n=4
for i in range(0,n,1):
print(i,end=" ")
################################################################
0 2 4 6 8 10 12 14
n=15
for i in range(0,n,2):
print(i,end=" ")
################################################################
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
n=15
for i in range(n,0,-1):
print(i,end=" ")
################################################################
15 13 11 9 7 5 3 1
n=15
for i in range(n,0,-2):
print(i,end=" ")
################################################################
Q. "W.A.P in Python to calculate the sum of natural numbers up to a given
value 'n' ?

n = int(input("Enter a value for 'n'"))


sum = 0
for i in range(1, n + 1):
sum = sum+i
print("The sum of natural numbers", sum)
Q.Write a Python program to calculate the average of natural numbers up to a given value 'n'

n = int(input("Enter a value for 'n'"))


sum = 0
count=0
for i in range(1, n + 1):
sum = sum+i
count=count+1
avg=sum/count
print("The avg of natural numbers", avg)
Q."Write a Python program that generates a table of numbers for a given integer 'n'. ?

n = int(input("Enter a value for 'n': "))


for i in range(1, 11):
print(n*i)
Q.Write a Python program to calculate the factorial of a given positive integer 'n'

n = int(input("Enter a value for 'n': "))


fact=1
for i in range(1, n+1):
fact=fact*i
print("factorial is ",fact)
Q."Write a Python program that determines whether a given positive integer 'n' is prime or
composite.

n = int(input("Enter a positive integer: "))


divisor_count = 0
for i in range(1, n + 1):
if n % i == 0:
divisor_count += 1
# if divisor_count is more than 2 that means it's composite number
if divisor_count == 2:
print(f"{n} is a prime number.")
else:
print(f"{n} is a composite number.")
Q.Write a Python program to count the total number of composite and prime numbers
within a specified range, such as from 'start' to 'end'.

# Input the range


start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
prime_count = 0
composite_count = 0
# Iterate through the range
for num in range(start, end + 1):
if num > 1:
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
prime_count += 1
else:
composite_count += 1
print("Total prime numbers in the range:", prime_count)
print("Total composite numbers in the range:", composite_count)
Q."Write a Python program to calculate the result of 'a' raised to the power of 'b', denoted as
'a^b'

a = int(input("Enter the base 'a': "))


b = int(input("Enter the exponent 'b': "))
result = 1
for i in range(1, b+1):
result =result* a
print("result is ",result)
Q.Write a Python program to calculate the sum of the series 1 + 1/2 + 1/3 + ... + 1/n for a
given positive integer 'n'

# Input a positive integer 'n'


n = int(input("Enter a positive integer 'n' ”)
sum = 0
for i in range(1, n + 1):
sum = sum+1/i
print("The sum of the series is:", sum)
Q."Write a Python program to calculate the sum of the series 1 + 1/2^2 + 1/3^2 + ... +
1/n^2 for a given positive integer 'n'.

# Input a positive integer 'n'


n = int(input("Enter a positive integer 'n': "))
sum = 0
for i in range(1, n + 1):
sum = sum+1 / (i**2)

print("The sum of the series is:", sum)


Q.W.A.P to print Fibonacci sequence using a for loop
0,1,1 2 3 5 8 13 21 34 55 89
n = int(input("Enter the number of Fibonacci terms to generate: "))
a=0
b=1
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Fibonacci sequence with 1 term:", a)
else:
print("Fibonacci sequence with", n, "terms:")
print(a, end=" ")
for i in range(2, n+1):
c=a+b
print(b, end=" ")
a=b
b=c

Q. W.A.P to Searching an element in a list/array in python


?
arr=[1,2,3,5,6]
x=int(input("enter a key value"))
flag=0
for i in range(len(arr)):
if arr[i] == x:
print("element found")
flag=1
if flag==0:
print("element is not found")

Q W.A.P to print this diamond pattern given below ?


*
***
*****
*******
*********
*******
*****
***
*
n=5
for i in range(0,n):
for j in range(0,n-i):
print(" ",end="")
for j in range(0,2*i-1):
print("*",end="")
print()
for i in range(n,0,-1):
for j in range(n-i,0,-1):
print(" ",end="")
for j in range(2*i-1,0,-1):
print("*",end="")
print()
Q. W.A.P to print pattern given below ?
*
**
***
****
*****
****
***
**
*
n=5
for i in range(0,n):
for j in range(0,n-i):
print(" ",end="")
for j in range(0,i):
print("*",end="")
print()
for i in range(n,0,-1):
for j in range(n-i,0,-1):
print(" ",end="")
for j in range(i,0,-1):
print("*",end="")
print()

You might also like