0% found this document useful (0 votes)
10 views29 pages

Python Unit 3

This document provides an overview of strings and lists in Python, detailing their creation, properties, methods, and operations. It covers string manipulation techniques such as concatenation, slicing, and formatting, as well as list operations like accessing, modifying, and concatenating elements. Additionally, it includes examples of functions for reversing strings, checking for palindromes, and counting characters.

Uploaded by

raunak106singh
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)
10 views29 pages

Python Unit 3

This document provides an overview of strings and lists in Python, detailing their creation, properties, methods, and operations. It covers string manipulation techniques such as concatenation, slicing, and formatting, as well as list operations like accessing, modifying, and concatenating elements. Additionally, it includes examples of functions for reversing strings, checking for palindromes, and counting characters.

Uploaded by

raunak106singh
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/ 29

PYTHON UNIT-3

String
A string is a sequence of characters, and it is one of the fundamental data types
used to represent text. Strings are enclosed in either single quotes (' '), double
quotes (" "), or triple quotes (''' ''', or """ """), and you can choose the style
that best fits your needs.

1. Creating Strings:

In Python, you can create strings using single quotes (' '), double quotes (" "), or
triple quotes (''' ' ''', or """ """). The choice of quotation style is flexible and
depends on your specific needs.

examples:

single_quoted_string = 'Hello, World!'

double_quoted_string = "Hello, World!"

triple_quoted_string = '''Hello, World!''’

2. String Concatenation:

String concatenation is the process of combining two or more strings


into a single string. You can use the + operator to concatenate strings.
For example:

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

print(result) # Output: Hello World

You can also use the += operator to update an existing string with the
concatenated value.
,

3.Properties of strings :

strings are immutable, meaning they cannot be changed after they are
created. Once a string is created, you cannot modify its contents.
However, you can create new strings based on the original string

my_string = "Hello"

# my_string[0] = 'J'

# This will cause an error because strings are immutable

# Instead, you can create a new string

new_string = 'J' + my_string

print(new_string) # Output: "JHello"

4. String Length: You can find the length of a string using the len()
function. The len() function returns the number of characters in the
string, including spaces and special characters.

text = "Hello, World!"


length = len(text)
print(length) # Output: 13

5. Accessing Characters in a String: strings are indexed, and you can


access individual characters by specifying the index (position) of the
character within the string. Indexing starts from 0.

text = "Hello, World!"


first_char = text[0] # 'H'
third_char = text[2] # 'l'
str1 = text[-1] # !

You can use both positive and negative indexing, with negative indexing
counting from the end of the string.
6. Slicing Strings: String slicing allows you to extract a portion of a
string by specifying a start index, stop index (exclusive), and an optional
step value. The format for slicing is [start:stop:step].

text = "Hello, World!"


substring = text[7:12]
print(substring) # World

substring2 = text[7:12:2]
print(substring2) # Wrd
You can omit the start and stop values to slice from the beginning or to
the end of the string. The step value determines how the slice progresses
through the string.

String Methods:

Python provides numerous built-in methods for working with strings.


These methods allow you to manipulate, modify, and analyze strings.
there are a few commonly used string methods

 strip(): Removes leading and trailing whitespace (including


spaces, tabs, and newlines) from a string.
 upper(): Converts all characters in a string to uppercase.
 lower(): Converts all characters in a string to lowercase.

For example :

text = " Hello, World! "

stripped_text = text.strip() # Removes leading and trailing whitespace

print(stripped_text)

upper_text = text.upper() # Converts to uppercase

print(upper_text)

lower_text = text.lower() # Converts to lowercase


print(lower_text)

# output
Hello, World!
HELLO, WORLD!
hello, world!

split(): Splits a string into a list of substrings based on a specified


delimiter.

# Splitting a string:
sentence = "This is a sample sentence."
words = sentence.split(' ')

print(words)

# Output:

['This', 'is', 'a', 'sample', 'sentence.']

isupper():

isupper(): method is used to check if all the characters in a string are


uppercase. It returns True if all characters in the string are uppercase
letters; otherwise, it returns False

text = "HELLO"

result = text.isupper()

print(result) # True

isalpha(): It checks whether all the characters in a string are


alphabetic, meaning they consist only of letters and are not empty. It
returns True if all characters are alphabetic, and False otherwise.

text = "Hello"
result = text.isalpha()

print(result) # True

isdigit():isdigit() method is used to check if all the characters in


a string are digits (0-9). It returns True if all characters in the string are
numeric digits, and the string is not empty; otherwise, it returns False

number = "12345"

result = number.isdigit()

print(result) # True

endswith(): method in Python checks whether a string ends with a


specified suffix. It returns True if the string ends with the specified suffix
and False otherwise.

Example-1:

my_string = "Hello, World!"

# Check if the string ends with a specific suffix

result = my_string.endswith("World!")

print(result) # Output will be True

example-2 :# Checking if the string ends with "World" starting from


index 7 up to index 12

result = text.endswith("World!", 7, 13)

print(result) # This will output True

startswith(): startswith() method in Python is used to check if


a string starts with a specified prefix. It returns True if the string starts
with the specified prefix, and False otherwise.
text = "Hello, World!"# Checking if the string starts with "Hello" starting
#from index 0 up to index 5

result = text.startswith("Hello,", 0, 6)

print(result) # True

ord() : ord() function is used to get the Unicode code point of a


character. It takes a single character as an argument and returns an
integer representing the Unicode code point of that character.

char = 'A'

unicode_value = ord(char)

print(unicode_value) # Output: 65

chr() : chr() function in Python is used to get the character that


corresponds to a specified Unicode code point. It takes an integer
representing a Unicode code point as an argument and returns the
character associated with that code point.

unicode_value = 65

character = chr(unicode_value)

print(character) # Output: 'A'

find() : find() method is commonly used to determine the index or


position of a substring within a string. It helps to locate the starting index
of the first occurrence of a substring within the given string.
my_string = "Hello, World!"
position = my_string.find("World")
print(position) # Output: 7

replace(): replace() method is used to substitute occurrences of a


specified substring within a string with another substring. This helps in
modifying strings by replacing specific parts.
my_string = "Hello, World!"

# Replace a substring

new_string = my_string.replace("World", "Universe")

print(new_string) # Output: Hello, Universe!

String Formatting:

String formatting allows you to construct strings that include variable


values.

#code

n1=45
n2=46
print("first value is ",n1," and IInd is ",n2)

#output
first value is 45 and IInd is 46

There are two common ways to format strings in Python.


1.Using f-strings (Python 3.6 and later):
F-strings provide a concise and convenient way to format strings by
embedding variables directly within the string using curly braces {}. You
can include variables and expressions inside f-strings, and they are
evaluated at runtime.

name = "Alice"
age = 30

formatted_string = f"My name is {name} and I am {age} years old"


print(formatted_string)

My name is Bob and I am 25 years old

2.Using .format() method:


The .format() method allows you to insert variables and values into a
string by using placeholders enclosed in curly braces {}. You can specify
the values for these placeholders using the .format() method.

name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old ".format(name,
age)
print(formatted_string)
# output

My name is Bob and I am 25 years old

Both methods provide flexibility in constructing formatted strings and


are commonly used in Python for text processing and manipulation.

Q. give output to given below code ?


st="abc"
st1=list(st)
print(st)
print(st1)
# output
abc
['a', 'b', 'c']
Q. W.A.P to reverse a given string in python ?
# method-1
def reverse_string(arr):
left = 0
right = len(arr) - 1
while left < right:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left += 1
right -= 1
return “”.join(arr) # it will convert into string
original_string = "rohan"
arr = list(original_string)
reversed_string = reverse_string(arr)
print("Original string ", original_string)
print("Reversed string ", reversed_string)
# method-2
def reverse_string(s):
new_str = ""
i = len(s) - 1
while i >= 0:
new_str = new_str+s[i]
i = i-1
return new_str
my_string = "Hello"
reversed_str = reverse_string(my_string)
print("after Reversing a string result is ", reversed_str)
# after Reversing a string result is olleH
Q.W.A.P to check if a given string is a palindrome or not.?
def is_palindrome(arr):
left = 0
right = len(arr) - 1
while left < right:
if arr[left] != arr[right]:
return False
left += 1
right -= 1

return True

test_string = "madam"
arr = list(test_string)

if is_palindrome(arr):
print("The string is a palindrome!")
else:
print("The string is not a palindrome.")
Q.W.A.P to Create a function to count the number of vowels and consonants
also number of digit in a given string. ?
def count_vowels_consonants(arr):
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
d="0123456789"
arr = arr.lower()
vowel_count = 0
consonant_count = 0
digit_count=0
c=0
index = 0
while index < len(arr):
char = arr[index]
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
elif char in d:
digit_count+=1
else:
c+=1
index += 1
return vowel_count, consonant_count,digit_count,c
test_arr = "Hello82*World&&"
result = count_vowels_consonants(test_arr)
print("actual string was ", test_arr)
print("Number of vowels:", result[0])
print("Number of consonants:", result[1])
print("Number of digit ", result[2])
print("Number of other symbols ", result[3])
# output
Test string: Hello82*World&&
Number of vowels: 3
Number of consonants: 7
Number of digit 2
Number of other symbols 3

String repetition:

String repetition in Python involves creating a new string by duplicating an


existing string multiple times. This is achieved by using the multiplication
(*) operator with a string and an integer value to specify how many times
the string should be repeated.
original_string = "Hello"
repeated_string = original_string * 3
print(repeated_string)
# output
HelloHelloHello

List:
In Python, a list is a versatile data structure , allowing for ordered and
indexed storage. It's denoted by square brackets [ ] .
Lists are a fundamental data structure used in programming to store
collections of items. They are mutable, meaning their elements can be
modified after the list is created. Lists can contain elements of different
data types (e.g., integers, strings, other lists, etc.) and allow for various
operations like addition, removal, and modification of elements.

Creating a list:

# Creating a list of integers


numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "orange", "grape"]
# Creating a list of mixed data types
mixed_list = [10, "twenty", True, 3.14]

Accessing elements in a list:

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange", "grape"]
mixed_list = [10, "twenty", True, 3.14]
# Accessing elements by index (indexing starts at 0)
print(numbers[0]) # Output: 1
print(fruits[2]) # Output: orange
print(mixed_list[1]) # Output: twenty
# Negative indexing - accessing elements from the end of the list
print(numbers[-1]) # Output: 5 (last element)

Modifying elements in a list:

fruits = ["apple", "banana", "orange", "grape"]


fruits[1] = "kiwi" # Modifying an element
print(fruits) # Output: ["apple", "kiwi", "orange", "grape"]
# Appending elements to the end of the list
fruits.append("melon")
print(fruits) # Output: ["apple", "kiwi", "orange", "grape", "melon"]
example-2
my_list = [1, 2, 3, 4]
element_to_insert = 5
index_to_insert = 2
my_list.insert(index_to_insert, element_to_insert)
print(my_list) # Output will be [1, 2, 5, 3, 4]
Removing elements from a list:
my_list = [1, 2, 3, 4,5]
numbers.remove(3) # Removes the first occurrence of 3
print(numbers) # Output: [1, 2, 4, 5]

List operations:

Concatenating lists :

In Python, you can concatenate lists using the + operator or the


extend() method. Both methods combine two or more lists into a
single list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2 # Concatenates list1 and list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
example-2 :
original_list = [1, 2, 3]
another_list = [4, 5, 6]
original_list.extend(another_list)
print(original_list) # Output would be [1, 2, 3, 4, 5, 6]
Length of a list :

In Python, you can determine the length of a list—the number of


elements it contains—using the len() function.
my_list = [1, 2, 3, 4, 5]
length_of_list = len(my_list) # length_of_list would be 5
List slicing :

List slicing is a powerful feature that allows you to extract a portion of a list by
specifying a range. The syntax for slicing is list[start:stop:step].

 start: The starting index of the slice. It's inclusive, meaning the element
at this index is included in the slice.
 stop: The ending index of the slice. It's exclusive, so the element at this
index is not included in the slice.
 step: The increment between elements. This is an optional parameter
and defaults to 1 if not specified.
numbers = [1, 2, 3, 4, 5]
sliced_list = numbers[1:3] # Retrieves elements at index 1 and 2
print(sliced_list) # Output: [2, 3]
List methods:
join(): join() method in Python is used to concatenate elements of an
iterable (like a list) into a single string. It joins each element of the
iterable with a specified separator string.

separator = “”

my_list = ['apple', 'banana', 'orange']

result = separator.join(my_list)

print(result) # This will output: "applebananaorange"

example-2

separator = "_"

my_list = ["mango", 'banana', 'orange']

result = separator.join(my_list)

print(result) # mango_banana_orange

enumerate():

enumerate() function creates an enumerate object that pairs each


element in an iterable with its index.

my_list = ['apple', 'banana', 'orange']

enumerated_list = list(enumerate(my_list))

print(enumerated_list)

#output

[(0, 'apple'), (1, 'banana'), (2, 'orange')]

max() and min():


max() returns the maximum element of the list.
min() returns the minimum element of the list.
Example:
my_list = [3, 7, 1, 9, 4]
max_value = max(my_list) # Returns 9
min_value = min(my_list) # Returns 1
sum():
Returns the sum of all elements in the list.
Example:
my_list = [1, 2, 3, 4, 5]
total_sum = sum(my_list) # Returns 15
sort():
Sorts the elements of the list in place (ascending order by default).
Example:
my_list = [3, 1, 4, 2, 5]
my_list.sort() # Sorts the list: my_list becomes [1, 2, 3, 4, 5]
reverse():
Reverses the order of elements in the list in place.
Example:
my_list = [1, 2, 3, 4, 5]
my_list.reverse() # Reverses the list: my_list becomes [5, 4, 3, 2, 1]
del statement :
Deletes elements or slices from a list by index.
Example:
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes element at index 2: my_list becomes [1, 2,
4, 5]
index():
Returns the index of the first occurrence of a specified element.
Example:
my_list = [10, 20, 30, 20, 40]
index = my_list.index(20) # Returns the index of the first occurrence
of 20, which is 1
count():
Returns the number of occurrences of a specified element in the list.
Example:
my_list = [1, 2, 2, 3, 2, 4]
count_of_twos = my_list.count(2) # Returns 3

These operations provide further functionality such as finding maximum


and minimum values, calculating sums, sorting and reversing lists,
deleting elements, and obtaining information about elements within a
list.
in keyword :
In Python, the in keyword is used as a membership operator to check if
a value exists within a sequence (like a list, tuple, string, or dictionary).

The in keyword returns True if the value is found in the sequence and
False otherwise. It's a convenient way to check for membership and is
commonly used in conditional statements or loops for decision-making
based on the presence or absence of a particular element within a
sequence.

Example :

my_list = [1, 2, 3, 4, 5]

# Checking if 3 is in the list

is_in_list = 3 in my_list

print(is_in_list) # Output: True

# Checking if 10 is in the list

is_in_list = 10 in my_list

print(is_in_list) # Output: False

Example-1 using if :

my_list = [1, 2, 3, 4, 5]

if 3 in my_list:

print("3 is in the list")

Example-2 using if :

my_dict = {'a': 1, 'b': 2, 'c': 3}


if 'b' in my_dict:

print("'b' is a key in the dictionary")

Example-3 using if :

my_string = "Hello, world!"

if "world" in my_string:

print("Substring 'world' is in the string")

Example-4 using if :

my_tuple = (10, 20, 30)

if 20 in my_tuple:

print("20 is in the tuple")

Dictionary:
dictionaries are another fundamental data structure in programming
languages like Python. They are used to store data in the form of key-
value pairs, allowing efficient retrieval of values based on keys.
Dictionaries are mutable and versatile, providing a way to associate
unique keys with corresponding values.

Creating a dictionary:

# Creating a dictionary of key-value pairs (string keys)


person = {
"name": "Alice",
"age": 30,
"city": "New York",
"email": "[email protected]"}

# Creating a dictionary with mixed keys and values


mixed_dict = {
"key1": 10,
20: "value2",
"key3": [1, 2, 3]
}

Accessing elements in a dictionary:

person = {
"name": "Alice",
"age": 30,
"city": "New York",
"email": "[email protected]"}
# Accessing values using keys
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
# Using the get() method to access values with fallback option
print(person.get("city")) # Output: New York
print(person.get("job", "Not specified")) # Output: Not specified (fallback
value)

Modifying elements in a dictionary:

person = {
"name": "Alice",
"age": 30,
"city": "New York",
"email": [email protected]}
# Modifying values in a dictionary
person["age"] = 32 # Changing the value of the "age" key
print(person) # Output: Updated dictionary with modified age
# Adding new key-value pairs
person["job"] = "Engineer"
print(person) # Output: Updated dictionary with the new "job" key

Removing elements from a dictionary:

To remove an element from a dictionary in Python, you can use the del
keyword or the pop() method.

my_dict = {'a': 1, 'b': 2, 'c': 3}

del my_dict['b']

print(my_dict) # Output: {'a': 1, 'c': 3}

example-2

my_dict = {'a': 1, 'b': 2, 'c': 3}

my_dict.pop('b')

print(my_dict) # Output: {'a': 1, 'c': 3}

Dictionary Methods:

# Creating a sample dictionary


my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'email': '[email protected]'
}
# Printing keys
print("Keys:", list(my_dict.keys()))
# Printing values
print("Values:", list(my_dict.values()))
# Printing key-value pairs (items)
print("Key-Value Pairs:", list(my_dict.items()))
# output
Keys: ['name', 'age', 'city', 'email']
Values: ['Alice', 30, 'New York', '[email protected]']
Key-Value Pairs: [('name', 'Alice'), ('age', 30), ('city', 'New York'), ('email',
'[email protected]')]

How to use for loop in dictionary :


# Creating a sample dictionary
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'email': '[email protected]'
}
# Accessing keys
for key in my_dict.keys():
print(key)
# Accessing values
for value in my_dict.values():
print(value)
# Accessing key-value pairs (items)
for key, value in my_dict.items():
print(f"{key}: {value}")

tuple :
A tuple is a data structure in Python that is quite similar to a list, but with
one major difference: it's immutable. Once you create a tuple, you can
not change its elements. Tuples are created by enclosing comma-
separated values within parentheses.

Example :
my_tuple = (1, 2, 'hello', 3.14)
print(my_tuple[2]) # Accesses the third element ('hello')

Use Cases of tuple :

 Data Integrity: Tuples are used when you want to ensure that the data
remains constant throughout the program execution.
 Return Multiple Values: Functions can return multiple values as a tuple,
which can be unpacked by the caller.
 Dictionary Keys: Tuples are hashable and can be used as keys in
dictionaries, unlike lists which are mutable and thus cannot be used as
keys.

Methods of tuple :

count()
Counts the number of occurrences of a specified element in the tuple.
Example:
my_tuple = (1, 2, 2, 3, 2, 4)
count_of_twos = my_tuple.count(2) # Returns 3
index()
Finds the index of the first occurrence of a specified value in the tuple.
Example:
my_tuple = ('a', 'b', 'c', 'a')
index_of_a = my_tuple.index('a') # Returns 0 (index of first 'a')

len()
Returns the number of elements in the tuple.
Example:
my_tuple = (1, 2, 3, 4)
length = len(my_tuple) # Returns 4
sorted()
Returns a new list containing all elements from the tuple in sorted
order (does not modify the original tuple as tuples are immutable).
Example:
my_tuple = (4, 1, 3, 2)
sorted_tuple = sorted(my_tuple) # Returns [1, 2, 3, 4]
max() and min()
Returns the maximum or minimum element in the tuple.
Example:
my_tuple = (10, 30, 20, 5)
max_value = max(my_tuple) # Returns 30
min_value = min(my_tuple) # Returns 5

Iterating Through Tuples :

Tuples can be iterated over using loops just like lists.


Example:
for element in my_tuple:
print(element)

Empty and Singleton Tuples :


An empty tuple is represented by () with no elements inside.
A singleton tuple containing a single element requires a trailing comma to
distinguish it from parentheses in mathematical operations.
empty_tuple = ()
singleton_tuple = (42,) # Singleton tuple with one element
ASCII values :

ASCII (American Standard Code for Information Interchange) values are


numerical representations of characters. Here are some ASCII values for
common characters:

 Uppercase letters A-Z: 65-90


 Lowercase letters a-z: 97-122
 Digits 0-9: 48-57

For example:

 'A' has an ASCII value of 65


 'Z' has an ASCII value of 90
 'a' has an ASCII value of 97
 'z' has an ASCII value of 122
 '0' has an ASCII value of 48
 '9' has an ASCII value of 57

These values are often used in programming to represent characters


internally within computers.

Function:
A function is a named block of code that performs a specific task or a set of
tasks. Functions are a fundamental concept in programming and are used to
organize code into reusable and modular units.

code structure for function :


def function_name(parameters):

# Function body
# Code to perform the task

return result # Optional,


# if the function needs to return a value the components of a Python
function
1. def: This keyword is used to define a function.
2. function_name: Choose a meaningful name for your function
that describes what it does. Function names should follow the
same naming conventions as variable names.
3. parameters (optional): These are placeholders for values that
the function can accept as input. You can specify zero or more
parameters, separated by commas. Parameters are enclosed in
parentheses.
4. Function body: The indented block of code under the def
statement defines what the function does. This is where you
write the instructions for the task the function is supposed to
perform.
5. return statement (optional): If your function needs to return a
value, you can use the return statement to do so. Not all
functions need to return a value, but when they do, it allows you
to use the result of the function elsewhere in your code.

Example-1 of Python function:

def xyz(name):

return f" Hello, {name} "

message = xyz("ajay")

print(message) # Output: Hello, ajay

In this example, the xyz function takes a name as a parameter and returns a
value in message object .
Functions are a powerful way to make your code more organized, reusable, and
easier to, as they allow you to encapsulate specific functionality into separate
units.

Example-2 w.a.p to print even numbers ?

def even_numbers(num):

for i in range(0, num ):


if i%2==0:

print (i, end=" ")

even_numbers(10)

type of function in python:


In Python, there are several types of functions, each serving a different purpose.
Here are some common types of functions in Python:

1. Built-in Functions:
 These functions are part of the Python standard library and are
available for use without the need for additional imports.
 Examples include print(), len(), type(), int(), str(), and
list().
2. User-Defined Functions:
 These functions are defined by the programmer to perform specific
tasks.
 You create these functions using the def keyword.
Example:

def greet(name):
return f"Hello, {name}!"

message = greet("Alice")
print(message) # Output: Hello, Alice!
3. Lambda Functions (Anonymous Functions):
 Lambda functions are small, anonymous functions defined using the
lambda keyword.
 They are often used for simple, one-liner operations and can be
passed as arguments to other functions.
Example :
double = lambda x: x * 2
result = double(5)
print(result) # Output: 10

4. Recursive Functions:
 Recursive functions are functions that call themselves to solve a
problem.
 They are often used for tasks that can be broken down into smaller,
similar subtasks.
Example: A recursive function to calculate the factorial of a number.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

result = factorial(5)
print(result) # Output: 120
5. Higher-Order Functions:
 These functions take one or more functions as arguments or return
functions as results.
 Examples include map(), filter(), and reduce(), which operate
on iterable data structures and apply a given function to their
elements.
6. Pure Functions:
 Pure functions are functions that have no side effects and always
return the same output for the same input.
 They do not modify external variables or have other hidden effects.
 Pure functions are important in functional programming.
7. Generator Functions:
 Generator functions use the yield keyword to create iterable
sequences of values.
 They generate values on-the-fly and are memory-efficient for
handling large data sets.
 Example: Creating a generator with a yield statement.
8. Decorator Functions:
 Decorators are functions that modify the behavior of other functions
or methods.
 They are often used to add additional functionality to existing
functions without modifying their code.
 Example: Creating a custom decorator to log function calls.
9. Class Methods and Instance Methods:
 Functions defined within classes are called methods. There are two
main types:
 Class methods are defined using the @classmethod
decorator and work on the class itself.
 Instance methods are defined without any special decorator
and operate on instances of the class.
10. Special Methods (Magic Methods):
 Special methods are identified by double underscores (e.g.,
__init__, __str__, __add__) and are used to define how objects of
custom classes behave when certain operations are performed on
them.

import statement :
the import statement is used to include external modules or libraries, which
are collections of functions and variables in Python program. These modules
provide additional functionality that is not available in the Python standard
library.

Example 1: Using the math module for mathematical functions:

import math

x = math.sqrt(16)

print(x) # Output: 4.0

pi_value = math.pi

print(pi_value) # Output: 3.141592653589793

Example 2: Importing a module with a custom name (alias):

import math as m
# Calculate the square root of a number using the alias 'm'

x = m.sqrt(25)

print(x)

Example 3: Importing specific items from a module:


from math import sqrt, pi

# Calculate the square root of a number and use pi

x = sqrt(9)
print(x) # Output: 3.0

print(pi) # Output: 3.141592653589793


Example 4: Importing all items from a module (not recommended):

from math import *


x = sqrt(36)

print(x) # Output: 6.0

You might also like