0% found this document useful (0 votes)
9 views19 pages

Unit_II

PYTHON2

Uploaded by

Tanushree
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)
9 views19 pages

Unit_II

PYTHON2

Uploaded by

Tanushree
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/ 19

Unit-II

Conditionals

Conditional & Alternative Execution:----------------------------------------------------


In Python, conditional execution refers to running a certain block of code only when a specific condition is
met, while alternative execution refers to executing different code based on whether a condition is true or
false.

These concepts are mainly implemented using if, elif, and else statements.

1. Conditional Execution:

Conditional execution allows us to control the flow of our program depending on whether a condition
evaluates to True or False.

Example of Conditional Execution:


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

In this example:

 The condition x > 5 is checked.


 If the condition is True (since x = 10), the code inside the if block is executed.

2. Alternative Execution:

Alternative execution allows us to execute one block of code when a condition is True and another block
when the condition is False. This is done using the else keyword.

Example of Alternative Execution:


x=3
if x > 5:
print("x is greater than 5.")
else:
print("x is not greater than 5.")

In this example:

 The condition x > 5 is checked.


 Since x = 3, the condition is False, so the else block is executed.

3. Using elif for Multiple Conditions:

If we have multiple conditions to check, we can use elif (short for "else if") to handle them.

Example of if, elif, and else:


x=7
if x > 10:
print("x is greater than 10.")
elif x > 5:
print("x is greater than 5 but less than or equal to 10.")
else:
print("x is less than or equal to 5.")

In this example:

 The first if checks if x > 10 (False in this case).


 The elif checks if x > 5 (True since x = 7), so the corresponding block is executed.
 If none of the conditions were true, the else block would have been executed.

4. Using Nested Conditionals for Complex Logic:

We can also nest if statements inside each other for more complex conditional logic.

Example of Nested Conditionals:


x = 10
y=5
if x > 5:
if y < 10:
print("x is greater than 5 and y is less than 10.")
else:
print("x is greater than 5 and y is not less than 10.")
else:
print("x is not greater than 5.")

Here:

 The outer if checks if x > 5 (True in this case).


 The inner if checks if y < 10 (True in this case), so the corresponding block is executed.

5. Using if in Expressions (Ternary Conditional):

Python supports conditional expressions, often called the ternary operator, to execute one of two expressions
based on a condition.(shorthand of if else)

Example of Ternary Conditional:


x=4
result = "x is greater than 5" if x > 5 else "x is less than or equal to 5"
print(result)

In this example:

 If x > 5, the string "x is greater than 5" is assigned to result.


 Otherwise, "x is less than or equal to 5" is assigned to result.
Chained and Nested Conditions:-----------------------------------------------------------
In Python, chained and nested conditions refer to ways of combining multiple conditions for decision-
making.

1. Chained Conditions:

Chained conditions refer to combining multiple conditions using logical operators like and, or, and not in a
single statement. This allows you to evaluate more than one condition in a single if statement.

Example of Chained Conditions:


x = 10
y = 20

if x > 5 and y < 30:


print("Both conditions are true.")
else:
print("One or both conditions are false.")

In this case:

 The condition x > 5 checks if x is greater than 5.


 The condition y < 30 checks if y is less than 30.
 The and operator means both conditions must be true for the block to execute.

2. Nested Conditions:

Nested conditions involve placing one if statement inside another. This allows for more fine-grained control
over decision-making.

Example of Nested Conditions:


x = 10
y = 20

if x > 5:
if y < 30:
print("x is greater than 5 and y is less than 30.")
else:
print("x is greater than 5, but y is not less than 30.")
else:
print("x is not greater than 5.")

Here:

 The outer if checks if x > 5.


 The inner if checks if y < 30, which is evaluated only if x > 5 is true.

More Complex Nested Example:


age = 25
is_student = False

if age > 18:


if is_student:
print("You are an adult and a student.")
else:
print("You are an adult, but not a student.")
else:
print("You are a minor.")

Iterations:-------------------------------------------------------------------------------------
In Python, iterations refer to the process of repeatedly executing a block of code for a certain number of
times or until a condition is met. The two most common types of iterations in Python are for loops and while
loops. Unlike many other languages there is no do-while loop in python.

1. for Loop (Iterating over sequences)

The for loop in Python is used to iterate over sequences like lists, tuples, strings, or ranges. It
automatically loops through each element in the sequence. Use for loop when we know exactly how many
times we want to execute the loop.

Basic Syntax:
for var in sequence:
# Execute code with var
During each iteration var is assigned the next value from the list.

Or

for var in sequence:


# Execute code with var
else:
# Execute else code
else block is optional. If present, it is executed if loop is not terminated abruptly using break

Example 1: Iterating through a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

Example 2: Iterating through a string


word = "Python"
for char in word:
print(char)

Output:

P
y
t
h
o
n
Example 3: Using range( ) with a for loop

The range() function generates a sequence of numbers, which can be useful for looping a specific number of
times.

for i in range(5): # Iterates from 0 to 4


print(i)

Output:

0
1
2
3
4

 range(start, stop) generates a sequence starting at start and ending at stop - 1.


 range(start, stop, step) generates a sequence from start to stop - 1, incrementing by step.(in reverse order:-
reversed)

Example with range:


for i in range(2, 10, 2): # Iterates from 2 to 8 with step size of 2
print(i)

Output:

2
4
6
8

2. while Loop (Iterating while a condition is True)

The while loop is used to repeats execute a block of code as long as a given condition is True. It is used when
we don’t know beforehand how much iteration are needed.

Basic Syntax:
while condition:
# Execute code

Example 1: Basic while loop


count = 0
while count < 5:
print(count)
count += 1 # Increment count to avoid infinite loop

Output:

0
1
2
3
4
Or
str="Shiv"
index=0
while index<len(str):
print(str)
index+=1

Output:

Shiv
Shiv
Shiv
Shiv

Or
list1=[1,2,3]
while list1:
print(list1)

Output:

[1,2,3]

In the case of a while loop, the else block will be executed if the loop condition becomes False (not if the
loop was exited with break).

list1=[1,2,3]
while list1:
print(list1)
list1.pop()
break
else:
print("loop exit")

Or
c=1
while c<1:
print(c)
c+=1
else:
print("out from loop")

Output:
out from loop

Example 2: Infinite while loop (with a break condition)

An infinite loop can be useful in certain cases, but you should use a break statement to exit the loop when a
condition is met.

count = 0
while True: # Infinite loop
print(count)
count += 1
if count == 5:
break # Exit the loop when count reaches 5
Output:

0
1
2
3
4

Or
c=int(input("press less than negative 1 to stop"))
while c!=-1:
print(c)
c=int(input("press less than negative 1 to stop"))
else:
print("out from loop")

Or
sum=0
c=int(input("press less than 0 to stop"))
while c!=0:
print(c)
sum=sum+c
c=int(input("press less than 0 to stop"))

else:
print(sum)
print("out from loop")

3. break, continue, and else with Loops

 break: Exits the loop prematurely when a specific condition is met.


 continue: Skips the current iteration and moves to the next iteration.
 else: An optional block that runs after the loop finishes, unless the loop is terminated by break. Means It
should be used in situations where we wish to execute some statements if the loop is terminated normally and
not if it is terminated abruptly.
 pass: no-op statement in Python, meaning it does nothing. It can be used inside a loop or if statement to
represent no operation. Pass is used when we need statement syntactically correct but we do not want to do
any operation.
 end=’ ’ in print( ) prints a space after printing in each iteration.

Example of break:
for i in range(10):
if i == 5:
break # Exits the loop when i equals 5
print(i)

Output:

0
1
2
3
4

Name=input( )
for i in Name:
if i == ‘ ’:
break # Exits the loop when i equals 5
print(i)

Example of continue:
for i in range(5):
if i == 3:
continue # Skips the iteration when i equals 3
print(i)

Output:

0
1
2
4

Example of else with loops:


for i in range(5):
print(i)
else:
print("Loop finished.")

Output:

0
1
2
3
4
Loop finished.

Example of pass with if:


age = 18
if age >= 18:
pass #No operation perform
else:
print("You are under 18")

Output:
"You are under 18"

Example of pass with while:

count = 0
while count < 5:
count += 1
if count == 3:
pass #at count== 3 no Operation perform
else:
print(count)

Outpout:
1
2
4
5
Example of pass with for:
for i in range(5):
if i == 2:
pass # at i==2,do nothing
else:
print(i)
Outpout:
0
1
3
4

Reassignment and Updating:---------------------------------------------------------------


In Python, reassignment and updating variables refer to modifying the value of a variable during the
execution of a program. These two concepts are often used interchangeably, but there are subtle differences
depending on how the variable is being modified.

1. Reassignment of a Variable

Reassigning a variable means assigning a new value to an existing variable. This overwrites the previous
value of the variable with the new one.

Example of Reassigning a Variable:


x = 10 # Initial assignment
print(x) # Output: 10

x = 20 # Reassigning x to a new value


print(x) # Output: 20

In the above example, the variable x initially holds the value 10, but after reassignment, it holds the value 20.

2. Updating a Variable

Updating a variable usually refers to modifying its value based on its current value, rather than completely
replacing it. This often involves operators that perform calculations on the variable.

Example of Updating a Variable:


x = 10
x += 5 # Updating x by adding 5 to it
print(x) # Output: 15

x *= 2 # Updating x by multiplying it by 2
print(x) # Output: 30

Here, x += 5 means "add 5 to the current value of x," and x *= 2 means "multiply the current value of x by 2."
These are examples of in-place updates where the value of the variable changes based on its previous
value.

3. Common Update Operations

Python provides several shorthand operators for updating variables. These operators modify the variable in-
place without needing to fully rewrite the expression.
Arithmetic Updates:

 +=: Adds a value to the variable.


 -=: Subtracts a value from the variable.
 *=: Multiplies the variable by a value.
 /=: Divides the variable by a value.
 **=: Raises the variable to a power.
 //=: Performs floor division.
 %=: Takes the modulus.

Examples:
x = 10

x += 3 # x = x + 3
print(x) # Output: 13

x -= 5 # x = x - 5
print(x) # Output: 8

x *= 2 # x = x * 2
print(x) # Output: 16

x /= 4 # x = x / 4
print(x) # Output: 4.0

x **= 2 # x = x ** 2 (x squared)
print(x) # Output: 16.0

x //= 3 # x = x // 3 (floor division)


print(x) # Output: 5.0

x %= 4 # x = x % 4 (modulus)
print(x) # Output: 1.0

4. Reassignment vs Updating with Lists and Mutable Types

When working with mutable types (like lists, dictionaries, or sets), the distinction between reassignment
and updating can be a bit more nuanced.

 Reassignment creates a new reference to a new object.


 Updating modifies the object in-place without changing its reference.

Reassignment Example with a List:


lst = [1, 2, 3]
print(id(lst)) # Prints the memory address of lst

lst = [4, 5, 6] # Reassigns lst to a new list


print(id(lst)) # Prints the memory address of the new list

In the above case, the variable lst is reassigned to a new list [4, 5, 6], so it points to a different memory
location.

Updating Example with a List:


lst = [1, 2, 3]
print(id(lst)) # Prints the memory address of lst

lst[0] = 10 # Update the first element of the list


print(lst) # Output: [10, 2, 3]
print(id(lst)) # The memory address remains the same
Here, the list itself is updated by changing its first element, but the reference (memory address) of the list
remains unchanged.

5. Reassignment vs Updating with Strings (Immutable Type)

Strings are immutable in Python, meaning you cannot modify them in place. When you try to "update" a
string, you're actually reassigning it to a new string object.

Example of String "Reassignment" (actually creating a new string):


s = "Hello"
s = s + " World" # Reassigning s to a new string
print(s) # Output: Hello World

In this case, the variable s is reassigned to a new string, "Hello World". Although it looks like the string was
"updated," it was actually a reassignment because strings are immutable.

Traversing with a for loop:-----------------------------------------------------------------


Traversal with a for loop in Python refers to iterating over a collection or sequence (such as a list, string,
tuple, dictionary, etc.) and performing operations on each element in that collection.

1. Traversing a List

A list is a common data structure in Python, and you can traverse it with a for loop to access each item in the
list.

Example: Traversing a List


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

for fruit in fruits:


print(fruit)

Output:

bash
Copy
apple
banana
cherry
date

Here, the for loop iterates over each element in the fruits list and prints each one.

2. Traversing a String

Strings in Python are also iterable, and you can use a for loop to traverse through each character.

Example: Traversing a String


word = "Python"
for char in word:
print(char)
Output:

P
y
t
h
o
n

In this example, each character of the string word is printed one by one.

3. Traversing a Tuple

A tuple is similar to a list but immutable. You can traverse a tuple using a for loop just like you do with a
list.

Example: Traversing a Tuple


numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number)

Output:

Copy
1
2
3
4
5

4. Traversing a Dictionary

In Python, a dictionary stores key-value pairs. You can traverse a dictionary using a for loop to access keys,
values, or both.

Example: Traversing Keys in a Dictionary


student_scores = {
"Alice": 85,
"Bob": 90,
"Charlie": 78
}

for student in student_scores:


print(student) # Prints only the keys (student names)

Output:

Alice
Bob
Charlie

Example: Traversing Values in a Dictionary


for score in student_scores.values():
print(score) # Prints only the values (scores)
Output:

85
90
78

Example: Traversing Both Keys and Values


for student, score in student_scores.items():
print(f"{student}: {score}")

Output:

Alice: 85
Bob: 90
Charlie: 78

Here, student_scores.items() returns a tuple of key-value pairs, which you can unpack into student and score in
each iteration.

5. Traversing a Set

A set is an unordered collection of unique elements. You can traverse a set with a for loop, but remember,
the order in which elements are traversed is not guaranteed.

Example: Traversing a Set


colors = {"red", "green", "blue", "yellow"}
for color in colors:
print(color)

Output:

red
green
blue
yellow

(The order of items may vary each time because sets are unordered.)

6. Traversing with an Index (Using range() and len())

Sometimes, you might need both the index and the element while traversing a sequence (like a list or string).
You can achieve this using the range() function with len().

Example: Traversing with Index (List)


fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

Here, range(len(fruits)) generates a sequence of indices that correspond to the elements in the list fruits. You
can use these indices to access elements by their position in the list.
Searching:-------------------------------------------------------------------------------------
In Python, searching refers to the process of looking for a specific element or value within a collection
(such as a list, string, dictionary, or set). Depending on the data structure, there are different ways to
perform searches.

Here are some of the most common methods for searching in Python:

1. Searching in a List

Lists are ordered collections in Python, and you can use different techniques to search for elements in a list.

a. Using in Keyword (Membership Test)

The in keyword allows you to check if a specific element is present in a list.

Example:
fruits = ["apple", "banana", "cherry", "date"]
# Check if 'banana' is in the list
if "banana" in fruits:
print("Banana is in the list.")
else:
print("Banana is not in the list.")

Output:

Banana is in the list.

b. Using index() Method

The index() method returns the index of the first occurrence of the specified value. If the value is not found, it
raises a ValueError.

Example:
l=[1,2,3]
x=l.index(3)
print(x)

Output:
2

c. Using for Loop

You can also search through a list using a for loop, especially when you want to perform more complex
conditions or actions.

Ex:-
l=[1,2,3]
for i in l:
if i==7:
l_e=True
print("yes")
break
else:
l_e=False
print("no")
break

Output:
No

Example:
fruits = ["apple", "banana", "cherry", "date"]
found = False
for fruit in fruits:
if fruit == "cherry":
found = True
break
if found:
print("Cherry is in the list.")
else:
print("Cherry is not in the list.")

Output:

Cherry is in the list.

2. Searching in a String

Strings are also sequences in Python, and similar techniques can be used to search for substrings or
characters within a string.

a. Using in Keyword

We can check if a substring exists within a string using the in keyword.

Example:
sentence = "The quick brown fox jumps over the lazy dog."
if "quick" in sentence:
print("Found 'quick' in the sentence.")
else:
print("Didn't find 'quick' in the sentence.")

Output:

Found 'quick' in the sentence.

b. Using find() Method

The find() method returns the index of the first occurrence of the substring, or -1 if the substring is not found.

Example:
sentence = "The quick brown fox jumps over the lazy dog."

# Find the index of the word 'fox'


index = sentence.find("fox")
if index != -1:
print(f"'fox' found at index {index}.")
else:
print("Word 'fox' not found.")

Output:

'fox' found at index 16.


c. Using index() Method

The index() method works similarly to find(), but it raises a ValueError if the substring is not found.

sentence = "The quick brown fox jumps over the lazy dog."
# Get the index of 'jumps'
index = sentence.index("jumps")
print(f"'jumps' found at index {index}.")

Output:

'jumps' found at index 20.

3. Searching in a Dictionary

Dictionaries are key-value pairs, and you can search for keys, values, or both.

a. Searching for a Key Using in

You can check if a specific key exists in a dictionary using the in keyword.

Example:
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
# Check if 'Bob' is a key in the dictionary
if "Bob" in student_scores:
print("Bob's score is in the dictionary.")
else:
print("Bob's score is not in the dictionary.")

Output:

Bob's score is in the dictionary.

b. Searching for a Value Using in (on values() method)

You can check if a specific value exists in the dictionary by using in on the dictionary's values() method.

Example:
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
# Check if the score 90 exists as a value
if 90 in student_scores.values():
print("A student has a score of 90.")
else:
print("No student has a score of 90.")

Output:

A student has a score of 90.

c. Using get() Method

The get() method retrieves the value for a given key if it exists, or returns None (or a default value) if the key
is not found.
Example:
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
# Get Bob's score
score = student_scores.get("Bob")
if score:
print(f"Bob's score is {score}.")
else:
print("Bob's score not found.")

Output:

Bob's score is 90.

4. Searching in a Set

Since sets are unordered collections, the search operation in a set is similar to searching in a list, but without
worrying about the order.

a. Using in Keyword

We can check if an element exists in a set using the in keyword.

Example:
colors = {"red", "green", "blue", "yellow"}
# Check if 'blue' is in the set
if "blue" in colors:
print("Blue is in the set.")
else:
print("Blue is not in the set.")

Output:

Blue is in the set.

5. Searching with filter() Function (for Complex Conditions)

The filter() function is used to filter elements based on a condition (like a custom search).

Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Find all even numbers in the list
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert to list and print the result


print(list(even_numbers))

Output:

[2, 4, 6, 8]

String Comparison:--------------------------------------------------------------------------
String comparison in python is the process of comparing two strings to check if they are equal or not. In
python we can compare two strings using the == operator. If the strings are the same, the comparison
returns True. If the strings are different the comparison returns False.
Example using == operator(Equality Comparison)
Str1="Shiva"
Str2="Rang"
if Str1==Str2:
print("Strings are equal")
else:
print("Strings are not equal")

Output:- "Strings are not equal"

Example using != operator(Inequality Comparison)


Str1="Shiva"
Str2="Rang"
if Str1!=Str2:
print("Strings are not equal")
else:
print("Strings are equal")

Output:- "Strings are not equal"

Example using <,>,<=,>= operator(Lexicographical Comparison)


1. "< "
str1='Shiva'
str2='Rang'
print(str1<str2)# False

2. "> "
str1='Shiva'
str2='Rang'
print(str1>str2)# True

3. "<= "
str1='Shiva'
str2='Rang'
print(str1<=str2)# False

4. ">= "
str1='Shiva'
str2='Rang'
print(str1>=str2)# True

Example for Case-insensitive-Comparison


1. " lower()"
str1='Shiva'
str2='shiva'
print(str1.lower()==str2.lower())#True

2. " upper()"
str1='Shiva'
str2='shiva'
print(str1.upper()==str2.upper())#True
Example using in and not in operator
1. " in"
str1='shiva'
str2='shiva'
print(str1 in str2) #True

2. " not in"


str1='shiva'
str2='shiva'
print(str1 not in str2) #False

You might also like