Monday, March 4, 2024

Filter Function

 Takes input a function which returns True/False and keeps the items which return True.

passwords = ['72tK3', '6zW5P3', '1P3=it3?', 'i"u7/auX{m']


def strong_password(password):
return len(password) >= 8


allowed_passwords = list(filter(strong_password, passwords))
print(allowed_passwords)

Output:
['1P3=it3?', 'i"u7/auX{m']

Sunday, March 3, 2024

Map function

 def names(firstname, lastname):

    """returns full name, inputs: first name and last name"""
return firstname + ' ' + lastname

fname = 'Priyanka'
lname = 'Chakraborti'
name = names(fname,lname)
print(name)
Output:
Priyanka Chakraborti

# I want to apply the same function over list

list_of_firstnames = ['Andy', 'Sam', 'Jim', 'Micheal']
list_of_surnames = ['Smith', 'Doe', 'Baker', 'Hendrix']

result = map(names,list_of_firstnames,list_of_surnames)
list_of_names = list(result)
print(list_of_names)
Output:
['Andy Smith', 'Sam Doe', 'Jim Baker', 'Micheal Hendrix']

Saturday, March 2, 2024

How to remove duplicates from list?

 Use set().


list_of_subjects= ['Physics', 'English', 'Statistics', 'English','Computer Science']
print(list(set(list_of_subjects)))

Output:
['Computer Science', 'English', 'Physics', 'Statistics']

Thursday, February 29, 2024

Slice Object in Python

Built-in type that represents a range of indices. It's commonly used with sequences (like lists, strings, and tuples) to extract portions of the sequence.


list_of_students = [(1,"Joe"), (2,"John"), (3,"Jacob"), (4,"Jack"),
 (5,"Karan"), (6, "Kavya"), (7,"Kamal")]

odd_slice = slice(0,len(list_of_students),2)
even_slice = slice(1,len(list_of_students),2)
list_of_group_one = list_of_students[odd_slice]
list_of_group_two = list_of_students[even_slice]
print(list_of_group_one)
print(list_of_group_two)

Output:

[(1, 'Joe'), (3, 'Jacob'), (5, 'Karan'), (7, 'Kamal')]
[(2, 'John'), (4, 'Jack'), (6, 'Kavya')]

Wednesday, February 28, 2024

Python Decorator

 In Python, a decorator is a design pattern that allows you to extend or modify the behavior of functions or methods without modifying their actual code. Decorators are applied using the @decorator syntax and are a concise way to wrap a function or method with additional functionality.

It helps you to off/on some functionality.


def log_function_call(func):
def wrapper(*args):
print(f"Calling {func.__name__} with arguments {args}")
result = func(*args)
print(f"{func.__name__} execution completed.")
return result
return wrapper

@log_function_call
def add_numbers(a, b):
return a + b

@log_function_call
def multiply_numbers(x, y):
return x * y

# Calling decorated functions
result_add = add_numbers(3, 5)
print(result_add)
result_multiply = multiply_numbers(
4, 6)
print(result_multiply)

Output:
Calling add_numbers with arguments (3, 5)
add_numbers execution completed.
8
Calling multiply_numbers with arguments (4, 6)
multiply_numbers execution completed.
24

Now if we comment out the decorator,
def log_function_call(func):
def wrapper(*args):
print(f"Calling {func.__name__} with arguments {args}")
result = func(*args)
print(f"{func.__name__} execution completed.")
return result
return wrapper

# @log_function_call
def add_numbers(a, b):
return a + b

# @log_function_call
def multiply_numbers(x, y):
return x * y

# Calling decorated functions
result_add = add_numbers(3, 5)
print(result_add)
result_multiply = multiply_numbers(
4, 6)
print(result_multiply)

Output:
8
24

Slice vs Split

Slicing is a broader concept applicable to sequences like lists, tuples, and strings. It involves extracting a portion, or a "slice," of a sequence based on indices. It is not an in-built function, it is a concept.

 art_board = "ArtBoard1"

list_of_shapes = ["Square", "Triangle", "Circle"]
tuple_of_colors = ('59D5E0', 'F5DD61', 'FAA300', 'F4538A')
# Slice works on both string and Iterables
# Get first 3 characters
print(art_board[:3])
# Reverse the list
print(list_of_shapes[::-1])
print(tuple_of_colors[1::2])


Output:
Art
['Circle', 'Triangle', 'Square']
('F5DD61', 'F4538A')

Split is used to divide a string into a list of substrings based
on a specified delimiter. 
By default, the delimiter is a space. 
# Split only works on String and create a list as outcome
my_name = "Priyanka Chakraborti"
my_first_name = my_name.split()[0]
my_last_name = my_name.split()[
1]
print(my_first_name, my_last_name, sep=',')
print(my_name.split())
# Change list to Tuple
print(tuple(my_name.split()))
Output:
Priyanka,Chakraborti
['Priyanka', 'Chakraborti']
('Priyanka', 'Chakraborti')

Understanding the Purpose of if name == 'main' in Python Scripts

 The __name__ == "__main__" construct in Python is a common pattern used to determine whether a Python script is being run as the main program or if it is being imported as a module into another script. This check is often used to control the execution of code that should only run when the script is executed directly.


We have two .py files.

File 1: sample.py


print('This is sample.py code')


def print_sample_text():
print('This is a sample text')


# __name__ is in-built variable
if __name__ == "__main__":
print('Sample.py is executed directly')
else:
print('Sample.py is imported')
print(f"Its name is: {__name__}")

File 2: demo.py
import sample
sample.print_sample_text()

if __name__ == "__main__":
print('demo.py is executed directly')
else:
print('demo.py is imported')
print(f"Its name is: {__name__}")

Now, if we run sample.py, output will be like:

This is sample.py code
Sample.py is executed directly

If we run demo.py, output will be like:
This is sample.py code
Sample.py is imported
Its name is: sample
This is a sample text
demo.py is executed directly

Now, notice the highlighted line. It should be executed 
only when we are running sample.py. But it is getting executed 
while import. Lets move this to the if block.

# print('This is sample.py code')


def print_sample_text():
print('This is a sample text')


# __name__ is in-built variable
if __name__ == "__main__":
print('Sample.py is executed directly')
print('This is sample.py code')
else:
print('Sample.py is imported')
print(f"Its name is: {__name__}")

Now, the output is:
Sample.py is imported
Its name is: sample
This is a sample text
demo.py is executed directly