[go: up one dir, main page]

0% found this document useful (0 votes)
3 views18 pages

Unit2 Python

The document provides an overview of conditional statements and loops in Python, including syntax and examples for if, elif, and else statements, as well as for and while loops. It explains nested if statements, expression evaluation, float representation, and controlling loops with break and continue. Additionally, it discusses the use of nested loops and mixed loops for handling multi-dimensional data.

Uploaded by

akhilverma9580
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)
3 views18 pages

Unit2 Python

The document provides an overview of conditional statements and loops in Python, including syntax and examples for if, elif, and else statements, as well as for and while loops. It explains nested if statements, expression evaluation, float representation, and controlling loops with break and continue. Additionally, it discusses the use of nested loops and mixed loops for handling multi-dimensional data.

Uploaded by

akhilverma9580
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/ 18

Unit -2 Conditionals :-

Conditional statement in Python:-


1. - In Python, a conditional statement allows you to execute code based on
certain conditions. The most common conditional statements in Python
are if, elif, and else.

2. -the if-else statement is a basic form of conditional logic. It allows a


block of code to execute when a condition is true (if block) and another
block of code to execute when the condition is false (else block).

Syntax of Conditional Statements


if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True and condition1 is False
else:
# Code to execute if both condition1 and condition2 are False

Example 1: Simple if statement:-

x = 10
if x > 5:
print("x is greater than 5")

Example 2: if-elif-else statement

x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")

Example 3: Nested if statement

x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")

Example 4: Using Logical Operators


You can combine conditions using logical operators (and, or, not).

x = 10
y = 20

if x > 5 and y > 15:


print("Both conditions are true")
Nested if Statement in Python

 A nested if statement is an if statement that is inside another if or else


statement. It allows you to test multiple conditions sequentially.
 We use nested if statements when we need to check secondary conditions
only if the fist condition executes as true

Syntex:-

if condition1:
if condition2:
# Code block to execute if both condition1 and condition2 are True
else:
# Code block to execute if condition1 is True but condition2 is False
else:
# Code block to execute if condition1 is False

Example1:-

x = 10
y = 20

if x > 5:
print("x is greater than 5")
if y > 15:
print("y is greater than 15")
else:
print("y is not greater than 15")
else:
print("x is not greater than 5")
elif Statement in Python:-

The elif statement is short for "else if." It allows you to check multiple
conditions sequentially and execute a block of code when the first matching
condition is found. The elif statement must always follow an if, and you can
have multiple elif blocks.

Syntax:-

if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is True
elif condition3:
# Code block to execute if condition1 and condition2 are False and
condition3 is True
else:
# Code block to execute if all conditions are False

Example1 :-

marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Difference Between elif and Nested if:-

1. elif is used to check multiple conditions sequentially, ensuring only one


block is executed.
2. Nested if allows you to check multiple conditions but within each other,
which can result in multiple blocks being executed.

Nested if Example with Multiple Conditions:


age = 25
income = 50000
if age >= 18:
if income > 40000:
print("Eligible for a loan")
else:
print("Not enough income for a loan")
else:
print("Not eligible due to age")

Expression Evaluation in Python:- Expression evaluation refers to the


process where Python evaluates and simplifies an expression to produce a
result. Python follows operator precedence (like in mathematics) to evaluate
expressions

Basic Rules of Expression Evaluation:


1. Operator Precedence: Operators with higher precedence are evaluated
first.
2. Associativity: Operators with the same precedence level are evaluated
based on their associativity (left to right or right to left).

Example of Expression Evaluation:

result = 10 + 5 * 2
print(result) # Output: 20

Float Representation in Python:-

In Python, floating-point numbers (floats) are used to represent decimal


numbers. Python follows the IEEE 754 standard to represent floating-point
numbers, which can lead to precision issues due to the way numbers are stored
in binary format.

Example:-

x = 0.1 + 0.2
print(x) # Output: 0.30000000000000004

Converting Floats to Integers:


If you want to convert a float to an integer, you can use the int() function, but
this truncates the decimal part:

y = 5.7
print(int(y)) # Output: 5

Purpose Loops:-

In programming, loops allow us to repeatedly execute a block of code multiple


times without needing to manually write the same statements again and again.
Loops help in automating repetitive tasks, reducing redundancy, and making
code easier to maintain.

In Python, there are two main types of loop:-

1. for loop
2. while loop

For Loops:-
 A for loop is used to iterate over a sequence (like a list, tuple, string, or
range) and execute a block of code for each element in that sequence
 Used when the number of iterations is known or you are iterating over a
sequence.
Syntax:-
for variable in sequence:
# Code block to execute

Example
numbers = [1, 2, 3, 4, 5]

for num in numbers:


print(num)

Example 2

num=int(input("enter the row:"))


for i in range (num):
for j in range(1,i+2):
print("*",end=" ")
print()

Output :

*
**
***
****
*****

Example 3
Question N.1:-

Write a program to generate the following pattern in python

*
***
*****
*******
*********
The Number of rows would be entered by the user.

Programs:-

num = int(input("enter the number of rows"))

for i in range(num):
for j in range(0, (num-i-1)):
print(' ' , end="")
for k in range(0, 2*i+1):
print('*', end="")
print()

Question N.2:-

Write a program to generate the following pattern in python


0
111
22222
3333333
444444444
The Number of rows would be entered by the user.
Program:-

num = int(input("enter the number of rows"))

for i in range(num):
for j in range(0, (num-i-1)):
print(' ' , end="")
for k in range(0, 2*i+1):
print(i, end="")
print()

Question N.3:-

Write a program to generate the following pattern in python


1
222
33333
4444444
555555555

The Number of rows would be entered by the user.

Program:-

num = int(input("enter the number of rows"))

for i in range(num):
for j in range(0, (num-i-1)):
print(' ' , end="")
for k in range(0, 2*i+1):
print(i+1, end="")
print()

Question N.4:-

Write a program to generate the following pattern in python


1
23
456
7 8 9 10
The Number of rows would be entered by the user.

Program:-

num = int(input("enter the number of rows"))


k =1
for i in range(num):
for j in range(1, i+2):
print(k,' ' , end="")
k =k+1
print()

while Loop:-

 A while loop runs as long as a given condition is true. The condition is


checked before each iteration, and if the condition becomes false, the
loop stops.
 Used when you want the loop to continue based on a condition.
Syntax:-

while condition:
# Code block to execute

Example

count = 1
while count <= 5:
print(count)
count += 1

Output:-
1
2
3
4
5

Example:-
Question1. Ask the user to enter a number and calculate its factorial numbers.
Program:-
num = int(input("Enter the number whose factorial is required"))
fact = 1
i =1
while i <= num:
fact = fact *i
i =i +1
print('\ factorial of '+str(num)+'is '+str(fact))

Output:-

 Enter the number whose factorial is required 6


 Factorial of 6is 720

Example3:-
Question1. Ask the user to enter two number ‘a’ and ‘b’ and calculate ‘a’ to the
power of ‘b’.

Program:-
a = int(input("Enter the first number"))
b = int(input("Enter the Second number"))
power =1
i =1
while i<=b:
power = power *a
i = i+1
else:
print(str(a)+' to the power of '+str(b)+' is '+str(power))

Output:-

 Enter the first number4


 Enter the Second number5
 4 to the power of 5 is 1024

Example4:-
Write a Python program to display the Fibonacci sequence for n terms.

Program:-
number = int (input ("Enter the value for x (where x > 2) ?"))
x1=0
x2 = 1
count = 2
if number <= 0 :
print("Please enter positive integer")
elif number == 1 :
print("Fibonacci sequence is :")
print(x1)
else :
print("Fibonacci sequence is :")
print(x1," ", x2)
while count < number :
xth = x1 + x2
print (xth)
x1 = x2
x2 = xth
count += 1

Output:
Enter the value for x (where x > 2) ?10
Fibonacci sequence is :
0
1
1
2
3
5
8
13
21
34

Controlling Loops:-

Python provides several statements to control the behavior of loops:

 break: Exits the loop immediately, even if the condition has not yet been
met.
 continue: Skips the current iteration and moves to the next iteration of the
loop.
 pass: Does nothing; used as a placeholder for future code.
Example of break:

for i in range(10):
if i == 5:
break
print(i)

Example of continue:

for i in range(5):
if i == 2:
continue
print(i)

Output:-

0
1
3
4

Infinite Loop:-

If the condition in a while loop is always True, it creates an infinite loop, which
continues running forever (unless interrupted).
Example of an Infinite Loop:-

while True:
print("This loop will run forever")

Output:-

This loop will run forever


This loop will run forever
This loop will run forever
This loop will run forever
This loop will run forever
This loop will run forever
…………
…………
…………
…………
…………
…………
…………
…………
…………
…………
This loop will run forever

When to Use Which Loop?:-

1. Use for loop: When you know in advance how many iterations you need,
or when iterating over a sequence like a list or a string.
2. Use while loop: When the number of iterations is not known in
advance and depends on some condition being True or False.

Nested Loops in Python:-

A nested loop is when one loop is placed inside another loop. In Python, this
allows for the execution of repeated actions within each iteration of an outer
loop. Each time the outer loop runs, the inner loop runs completely, creating a
loop within a loop.

Syntax of Nested Loops:-


for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Code block to execute for each combination of outer and inner loops

Types of Nested Loops:-

1. Nested for loops: When a for loop is inside another for loop.
2. Nested while loops: When a while loop is inside another while loop.
3. Mixed loops: When a for loop is inside a while loop or vice versa.

Nested for Loops:-

Nested for loops are useful when you need to work with multi-dimensional data
like matrices, grids, or lists of lists.

Example: Printing a 3x3 Matrix:-

for i in range(3): # Outer loop runs 3 times


for j in range(3): # Inner loop runs 3 times for each outer iteration
print(f"({i}, {j})", end=" ")
print() # Move to the next line after the inner loop finishes

Output:-

(0, 0) (0, 1) (0, 2)


(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1) (2, 2)

Example: Multiplication Table:-

for i in range(1, 6): # Outer loop for the first number


for j in range(1, 6): # Inner loop for the second number
print(i * j, end="\t") # Print multiplication result
print() # Move to the next line after the inner loop finishes

Output:-

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Nested while Loops:-

Nested while loops can be used when both loops depend on certain conditions,
and both conditions must be met for the inner loop to execute.

Example: Counting with Nested while Loops

i=1
while i <= 3: # Outer loop
j=1
while j <= 3: # Inner loop
print(f"i = {i}, j = {j}")
j += 1 # Increment inner loop counter
i += 1 # Increment outer loop counter

Output:-
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

Mixed Loops (for inside while or vice versa):-

You can mix for and while loops, depending on the problem's requirements.

Example: for Loop Inside a while Loop:-

i=1
while i <= 3: # Outer `while` loop
for j in range(1, 4): # Inner `for` loop
print(f"i = {i}, j = {j}")
i += 1 # Increment outer loop counter
Output:-

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

You might also like