Unit_II
Unit_II
Conditionals
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.
In this example:
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.
In this example:
If we have multiple conditions to check, we can use elif (short for "else if") to handle them.
In this example:
We can also nest if statements inside each other for more complex conditional logic.
Here:
Python supports conditional expressions, often called the ternary operator, to execute one of two expressions
based on a condition.(shorthand of if else)
In this example:
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.
In this case:
2. Nested Conditions:
Nested conditions involve placing one if statement inside another. This allows for more fine-grained control
over decision-making.
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:
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.
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
Output:
apple
banana
cherry
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.
Output:
0
1
2
3
4
Output:
2
4
6
8
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
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
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")
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
Output:
0
1
2
3
4
Loop finished.
Output:
"You are under 18"
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
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.
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.
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.
Python provides several shorthand operators for updating variables. These operators modify the variable in-
place without needing to fully rewrite the expression.
Arithmetic Updates:
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 %= 4 # x = x % 4 (modulus)
print(x) # Output: 1.0
When working with mutable types (like lists, dictionaries, or sets), the distinction between reassignment
and updating can be a bit more nuanced.
In the above case, the variable lst is reassigned to a new list [4, 5, 6], so it points to a different memory
location.
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.
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.
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.
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.
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.
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.
Output:
Alice
Bob
Charlie
85
90
78
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.
Output:
red
green
blue
yellow
(The order of items may vary each time because sets are unordered.)
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().
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.
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:
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
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:
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
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:
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."
Output:
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:
3. Searching in a Dictionary
Dictionaries are key-value pairs, and you can search for keys, values, or both.
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:
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:
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:
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
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:
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)
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")
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
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