Python Unit 3
Python Unit 3
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)
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