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

Python Unit 3

Uploaded by

shainnshutup
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 views

Python Unit 3

Uploaded by

shainnshutup
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/ 4

Author : DSALGO

string list
 A string is a sequence of characters in Python.  list is a mutable, ordered collection of element.
 Formed by enclosing characters in quotes.  Lists are one of the most versatile & widely used data types in
 Python treats single and double quotes equally. Python.
 Strings are literal or scalar, treated as a single value in Python
 Python treats strings as a single data type. Here are some key characteristics of lists:
 Allows easy access and manipulation of string parts.
:
 Example :
my_list = [1, 2, 3, "hello", True]
str1 = 'Hello World'
str2 = "My name is khan"
String manipulation in Python
1.Concatenation: Joining two or more strings together. first_element = my_list[0] # Accessing the first elementssing the first
result = str1 + " " + str2 element
print(result) # Output: "Hello World My name is khan"

2.String Formatting: Creating formatted strings with placeholders or sublist = my_list[1:4] # Extracting elements from index 1 to 3
f-strings.
fstr = f"{str1} and {str2}"
print(fstr) my_list[0] = 100 # Modifying an element
3.String Methods: Using built-in string methods to manipulate strings. my_list.append(5) # Adding an element to the end
u_str = str1.upper() #HELLO WORLD my_list.remove("hello") # Removing an element
l_str = str1.lower() # hello world
r_str =str2.replace("khan ", "singh")#my name is singh
length_of_list = len(my_list)
4.Splitting and Joining: Splitting a string into a list of substrings based
on a delimiter, and joining a list of strings into a single string.
splitlist = str1.split("") #['Hello','World'] my_list.sort() # Sorts the list in ascending order
joinlist = "-".join(splitlist) # Hello – World my_list.reverse() # Reverses the list
5.Stripping: Removing leading and trailing whitespace characters
from a string.
my_string = " Hello World " copy() method in list :
stripped_str = my_string.strip() original_list = [1, 2, 3, 4, 5]
print(stripped_str) # Output: "Hello World" copied_list1 = original_list.copy() #method 1
print(copied_list1)
6.Searching: Finding substrings within a string. copied_list2 = list(original_list) # method 2
string = "the quick brown fox jumps over the lazy dog" print(copied_list2)
is_dog = "dog" in string #bool:true or false copied_list3 = original_list[:] # method 3
index =string.find("fox") #return first occurance index print(copied_list3)

Delete element in list


slicing string manipulation : my_list = [1, 2, 3, 4, 5]
 string slicing is a technique used to extract a portion of a string del my_list[2] # Removes the element at index 2
by specifying a range of indices. print(my_list) #[1, 2, 4, 5]
 Syntax : my_list = [1, 2, 3, 4, 5]
string[start:stop:step]
my_list.remove(3) # Removes the first occurrence of the value 3
 Example:
print(my_list) #[1, 2, 4, 5]
# Basic slicing
my_list = [1, 2, 3, 4, 5]
substring1 = text[7:10] # Extracts "is"
popped_element = my_list.pop(2) # Removes and returns the
substring2 = text[0:6] # Extracts "Python"
element at index 2
# Omitting start or stop
print(my_list) # [1, 2, 4, 5]
substring3 = text[:6] # Extracts "Python"
my_list = [1, 2, 3, 4, 5]
substring4 = text[7:] # Extracts "is amazing"
my_list[1:3] = [] # Deletes elements at indices 1 and 2
# Using negative indices
print(my_list) #[1, 4, 5]
substring5 = text[-7:-1] # Extracts "amazin"
my_list = [1, 2, 3, 4, 5]
# Slicing with step
my_list.clear() # Removes all elements from the list
substring6 = text[0:15:2] # Extracts "Pto saa"
print(my_list) # []
# Reverse a string
substring7 = text[::-1] # Extracts "gnizama si nohtyP"
Built-in operator in python :  Program :
# Defining sets
list1 = [1, 2, 3] set1 = set([1, 2, 4, 1, 2, 8, 5, 4])
set2 = set([1, 9, 3, 2, 5])
list2 = [4, 5, 6]
# Printing sets
result_list = list1 + list2 # Concatenates the lists
print(set1) # Output: {1, 2, 4, 5, 8}
print(set2) # Output: {1, 2, 3, 5, 9}
repeated_string = "abc" * 3 # Repeats the string three times # Intersection of set1 and set2
repeated_list = [1, 2] * 4 # Repeats the list four times intersection = set1 & set2
print(intersection) # Output: {1, 2, 5}
string_check = "lo" in "Hello" # Checks if "lo" is in "Hello" (True)
# Union of set1 and set2
list_check = 3 in [1, 2, 3, 4] # Checks if 3 is in the list (True)
union = set1 | set2
tuple print(union) # Output: {1, 2, 3, 4, 5, 8, 9}
 tuple is an ordered, immutable collection of elements.
 once a tuple is created, its elements cannot be modified or # Difference of set1 and set2
changed. difference = set1 - set2
 Tuples are defined using parentheses () and can contain print(difference) # Output: {4, 8}
elements of different data types.
 Program :
# Symmetric difference of set1 and set2
my_tuple = (1, 2, 3, 'hello', True) # tuple creation
symm_diff = set1 ^ set2
first_element = my_tuple[0] #Accessing Elements
print(symm_diff) # Output: {3, 4, 8, 9}
my_tuple[0] = 100 # This will raise an error
packed_tuple = 1, 'apple', 3.14 #Tuple Packing
x, y, z = packed_tuple #Unpacking
Functions
 Functions are self-contained units designed for specific tasks.
length = len(my_tuple) Length of Tuple  Once created, functions can be called as needed.
combined_tuple = (1, 2, 3) + ('a', 'b', 'c') #Tuple Concatenation  Functions have names and may or may not return values.
count_of_2 = my_tuple.count(2) #output : 1  Python offers built-in functions like dir(), len(), abs(), etc.
index_of_hello = my_tuple.index('hello') #output: 3  Users can define custom functions for specific requirements.
 We will use the def keyword to define functions

Dictionary
 dictionary is a mutable, unordered collection of key-value pairs. Why do we use functions :(advantges)
 Each key in a dictionary must be unique, and it is associated with 1.Reusability 2. Readability,
a specific value. 3.Maintainability 4. Scoping
 Dictionaries are defined using curly braces {} and consist of key-
value pairs separated by commas. Syntax:
 Here are some key points about dictionaries:
 Creating a Dictionary: # define the function_name
 my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} def function_name():
 Accessing Values:
# Code inside the function
name = my_dict['name']
age = my_dict['age'] # Optionally, return a value
 Modifying Values:
my_dict['age'] = 26 #call the function_name
 Adding New Key-Value Pairs: Function_name()
my_dict['gender'] = 'Male'
 Removing Key-Value Pairs: Example function without parameters
del my_dict['city']
def greet():
 Checking Key Existence:
print("Hello, World!")
is_name_present = 'name' in my_dict
 Dictionary Methods: greet() # Calling the greet function
keys = my_dict.keys() Example function with parameters
values = my_dict.values() def add_numbers(a, b):
items = my_dict.items() return a + b
Set
 set is an unordered and mutable collection of unique elements. # Calling the add_numbers function
 Sets are defined using curly braces {} and can contain various result = add_numbers(5, 7)
data types, such as numbers, strings, and other sets. print("Sum:", result)
 Operations performed on sets are union , intersection ,
difference , symmetric difference

Elements of the function
 Keyword: def for function header. #Make a table for selection operation
 Function Name: Identifies uniquely. print("Select operation:")
 Colon: Ends function header. print("1. Add")
 Parameters: Values passed at a defining time , e.g., x and y.
print("2. Subtract")
 Arguments: Values passed at a calling time , e.g., a and b.
 Function Body: Processes arguments. print("3. Multiply")
 Return Statement: Optionally returns a value. print("4. Divide")
 Function Call: Executes the function, e.g., a = max(8, 6). choice = input("Enter choice (1/2/3/4): ")
 Keyword Arguments:Pass values to function by associating num1 = float(input("Enter first number: "))
them with parameter names. num2 = float(input("Enter second number: "))
Syntax : function_name(p1=val1 , p2 =val2)
if choice == '1':
 Default Values: can have default values, making them optional
during function calls.
print(num1, "+", num2, "=", add(num1, num2))
Syntax: def function_name(param1=default_value1, elif choice == '2':
param2=default_value2): print(num1, "-", num2, "=", sub(num1, num2))
scope rules in Python [LEGB rule ] elif choice == '3':
Local: Variables within a function; accessible only within that function. print(num1, "*", num2, "=", mult(num1, num2))
Enclosing: Scope for nested functions; refers to the enclosing elif choice == '4':
function's scope. print(num1, "/", num2, "=", div(num1, num2))
Global: Variables at the top level of a module or declared global else:
within a function; accessible throughout the module.
print("Invalid input. Please enter a valid choice.")
Builtin: Outermost scope containing built-in names like print(), sum(),
etc.; available everywhere.
Q. Write a function in find the HCF of given numbers
# Global scope
global_variable = "I am global" def HCF(num1, num2):
def outer_function(): while num2:
# Enclosing scope num1, num2 = num2, num1 % num2
enclosing_variable = "I am in the enclosing scope" return abs(num1)
def inner_function(): # Example usage:
# Local scope number1 = 24
local_variable = "I am in the local scope" number2 = 36
print(local_variable) result = HCF (number1, number2)
print(enclosing_variable) print(f"The HCF of {number1} and {number2} is {result}")
print(global_variable)
print(len(global_variable)) # Using a built-in function
inner_function()
outer_function()

Output :
I am in the local scope
I am in the enclosing scope
I am global
10

Q . make a calculator using function inpython like sub, add, mult ,


div
# four basic Functions for calculator sub, sum , divide, multiply
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def div(x, y):
if y != 0:
return x / y
else:
return "Error! Division by zero."

You might also like