Click here to view and download handwritten notes
Click here to view and download notes given by Professor
In [3]:
#creating an list
lst=[1,3,4,5,]
print("int data type in list:",lst)
lst1=["sahil","sahani","boy"]
print("string data type in list:",lst1)
lst2=["sahil",19,23.2,True,False]
print("mixed data type in list:",lst2)
int data type in list: [1, 3, 4, 5] string data type in list: ['sahil', 'sahani', 'boy'] mixed data type in list: ['sahil', 19, 23.2, True, False]
A) List Function and Methods¶
In [7]:
lis1=[2,4,6,8,10,12,14,16,18]
print("this is an length of list:",len(lis1))
print("this is an minimum value of a list:",min(lis1))
print("this is an maximum value of a list:",max(lis1))
print("this is the sum of all elements:",sum(lis1))
this is an length of list: 9 this is an minimum value of a list: 2 this is an maximum value of a list: 18 this is the sum of all elements: 90
In [13]:
lis2=[1,3,4,5,1,3,1,6,85,1,1]
lis2.count(1)
#Counts the number of occurrences of a specific element in a list.
Out[13]:
5
In [19]:
print("this an sorted form of list:",sorted(lis2))
# Returns a sorted version of a list.
this an sorted form of list: [1, 1, 1, 1, 1, 3, 3, 4, 5, 6, 85]
In [31]:
lis3=[2,4,6,8]
lis3.index(8)
#Returns the index of the first occurrence of a value in a list.
Out[31]:
3
In [40]:
lis4=["sahil","sahani",12,43,3]
lis4.append(12)
#Adds an element to the end of a list.
print(lis4)
['sahil', 'sahani', 12, 43, 3, 12]
In [41]:
lis4.remove("sahil")
print(lis4)
# Removes the first occurrence of a specified element from the list.
['sahani', 12, 43, 3, 12]
In [46]:
lis5=[12,3,5,23,440]
lis5.pop(2) #5 is on 2 indexed there for its removed from list
print(lis5)
# Removes and returns the element at the specified index.
[12, 3, 23, 440]
In [51]:
lis6=["sahil","vicky","sahani"]
lis6.insert(1,"boy") #insert(index, value)
# Inserts an element at a specified position in the list.
print(lis6)
['sahil', 'boy', 'vicky', 'sahani']
In [12]:
lis8=[12,23,12,3]
lis9=[23,33,12,2]
lis8.extend(lis9)
# Appends the elements of another list to the end of the current list.
lis9.extend(lis8)
print(lis9)
print(lis8)
[23, 33, 12, 2, 12, 23, 12, 3, 23, 33, 12, 2] [12, 23, 12, 3, 23, 33, 12, 2]
In [63]:
def square(x):
return x**2
list1=[2,4,5,6]
sa=map(square,list1) #map(function,iterable)
# Applies a function to all the items in a list.
print(list(sa))
[4, 16, 25, 36]
In [66]:
my_list=[1,2,3,4]
for index, value in enumerate(my_list):
print(index,value)
# Returns both the index and value of items in a list
0 1 1 2 2 3 3 4
In [65]:
list3=[222,232,2223]
print(list(enumerate(list3)))
# Returns both the index and value of items in a list
[(0, 222), (1, 232), (2, 2223)]
In [68]:
# Creates a list of elements for which a function returns true.
def even_num(x):
return x%2==0
numbers=[1,2,3,4,5,6,7,8,9,10,12,14]
y=filter(even_num,numbers)
print("this are the even numbers:",list(y))
this are the even numbers: [2, 4, 6, 8, 10, 12, 14]
In [69]:
def odd_num(x):
return x%2!=0
numbers=[1,2,3,4,5,6,7,8,9,10,12,14]
y=filter(odd_num,numbers)
print("this are the odd numbers:",list(y))
this are the odd numbers: [1, 3, 5, 7, 9]
In [70]:
numbers=[1,2,3,43,5,65,7,8,9,10,12,14]
numbers.reverse() #Reverses the order of elements in the list.
print("numbers after reversing:",numbers)
numbers after reversing: [14, 12, 10, 9, 8, 7, 65, 5, 43, 3, 2, 1]
In [71]:
#Creating an dictionary
dict1={"name":"sahil",
"age":19,
"std":"fybsc",
"rollno":38
}
print(dict1)
{'name': 'sahil', 'age': 19, 'std': 'fybsc', 'rollno': 38}
In [75]:
dict1["name"]
Out[75]:
'sahil'
In [77]:
dict1["age"]=89
print(dict1)
{'name': 'sahil', 'age': 89, 'std': 'fybsc', 'rollno': 38}
In [79]:
print(type(dict1))
<class 'dict'>
A) Operators in Dictionary¶
In [83]:
dict2={"name":"vicky",
"rollno":30,
"age":18
}
dict2["name"]
Out[83]:
'vicky'
In [85]:
dict2["name"]="chiku"
print(dict2)
{'name': 'chiku', 'rollno': 30, 'age': 18}
In [90]:
dict3={"name":"aman",
"rollno":39,
"age":19
}
del dict3["rollno"]
print(dict3)
{'name': 'aman', 'age': 19}
B) Dictinaries Methods¶
In [93]:
#copy() method is used to create a shallow copy of a dictionary.
# If the objects within the dictionary are mutable (e.g., lists or other dictionaries),
# changes to those mutable objects will be reflected in both the original and copied dictionaries.
dict5={"name":"sahil sahani",
"rollno":38,
"class":10,
"hobby":"cricket"
}
print("copyed dict:",dict5.copy())
print("original dict:",dict5)
copyed dict: {'name': 'sahil sahani', 'rollno': 38, 'class': 10, 'hobby': 'cricket'} original dict: {'name': 'sahil sahani', 'rollno': 38, 'class': 10, 'hobby': 'cricket'}
In [96]:
# In Python, dictionaries have a clear() method that is used to remove all items (key-value pairs) from a dictionary.
# After calling clear(), the dictionary becomes empty
dict6={1:"sahil",
2:"sahani"
}
dict6.clear()
print(dict6)
{}
In [98]:
print(dict5)
{'name': 'sahil sahani', 'rollno': 38, 'class': 10, 'hobby': 'cricket'}
In [100]:
#Used to retrieve the value for a given key. It allows you to specify a default value if the key is not present.
dict5.get("name")
Out[100]:
'sahil sahani'
In [102]:
dict5.keys()
# Returns a view of all the keys in the dictionary.
Out[102]:
dict_keys(['name', 'rollno', 'class', 'hobby'])
In [103]:
# Returns a view of all the values in the dictionary
dict5.values()
Out[103]:
dict_values(['sahil sahani', 38, 10, 'cricket'])
In [104]:
# Returns a view of all key-value pairs as tuples.
dict5.items()
Out[104]:
dict_items([('name', 'sahil sahani'), ('rollno', 38), ('class', 10), ('hobby', 'cricket')])
In [106]:
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Remove and return the value associated with 'key2'
removed_value = my_dict.pop('key2')
# Display the removed value and the updated dictionary
print("Removed Value:", removed_value)
print("Updated Dictionary:", my_dict)
Removed Value: value2 Updated Dictionary: {'key1': 'value1', 'key3': 'value3'}
In [107]:
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
# Dictionary to update with
update_dict = {'key2': 'new_value', 'key3': 'value3'}
# Update the original dictionary with elements from the update dictionary
my_dict.update(update_dict)
# Display the updated dictionary
print("Updated Dictionary:", my_dict)
Updated Dictionary: {'key1': 'value1', 'key2': 'new_value', 'key3': 'value3'}
C) Using for loop with Dictionaries¶
In [108]:
# Iterating over Keys:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Iterate over keys
for key in my_dict:
print(key)
key1 key2 key3
In [109]:
# Iterating over Values:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Iterate over values
for value in my_dict.values():
print(value)
value1 value2 value3
In [110]:
# Iterating over Key-Value Pairs:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Iterate over key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")
key1: value1 key2: value2 key3: value3
3) Regular Expersions¶
In [51]:
#extracting all email ids from RE file
import re
f=open("RE.txt","r")
rea=f.read()
email=re.findall( r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',rea)
# r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
for i in email:
print(i)
alice@example.com bob123@gmail.com charlie_doe@hotmail.com david.smith@yahoo.com JohnDoe@gmail.com AliceSmith@yahoo.com BobJohnson@hotmail.com EmilyBrown@example.com ChrisWilson@gmail.com
In [52]:
#extracting the mobile numbers from RE file
f=open("RE.txt","r")
rea=f.read()
numbers=re.findall(r"\b\d{3}-\d{4}\b",rea)
for i in numbers:
print(i)
555-1234 555-5678 555-8765 555-4321
In [50]:
#extracting the date from RE file
f=open("RE.txt","r")
rea=f.read()
date=re.findall(r"\b\d{4}-\d{2}-\d{2}\b",rea)
for i in date:
print(i)
2023-01-15 2023-02-28 2023-12-05
In [66]:
# extracting indian mobile numbers
f=open("RE.txt","r")
rea=f.read()
ind_num=re.findall(r'\b(\w+): (\d{10})\b'
,rea)
for i in ind_num:
print(list(i))
['sahil', '9137368385'] ['vicky', '8828507228']
4) Date and Time¶
In [78]:
from datetime import datetime
print(datetime.now())
2023-11-19 23:26:09.519874
In [79]:
print(datetime.today())
2023-11-19 23:26:30.153900
In [80]:
print(datetime(2023,4,9))
2023-04-09 00:00:00
In [86]:
#time class
from datetime import date
print(date.today())
2023-11-19
In [85]:
print(date(2023,4,23))
2023-04-23
In [91]:
# time class
from datetime import time
print(time(22,30,48))
22:30:48
A) combining date and time¶
In [92]:
#combining date and time
from datetime import datetime, date, time
# Create a date object
my_date = date(2023, 11, 19)
# Create a time object
my_time = time(14, 30, 0) # 2:30:00 PM
# Combine date and time into a datetime object
combined_datetime = datetime.combine(my_date, my_time)
# Print the result
print("Combined Date and Time:", combined_datetime)
Combined Date and Time: 2023-11-19 14:30:00
B) comparing two dates¶
In [95]:
#comparing two dates
d1=date(2023,4,25)
d2=date(2023,3,29)
print(d1==d2)
print(d1!=d2)
print(d1<d2)
print(d1>d2)
print(d1<=d2)
print(d1>=d2)
False True False True False True
In [96]:
print(d2==d1)
print(d2!=d1)
print(d2<d1)
print(d2>d1)
print(d2<=d1)
print(d2>=d1)
False True True False True False
c) Formatting dates and times¶
In [2]:
# Import the datetime module
from datetime import datetime
# Get the current date and time
current_datetime = datetime.now()
# Format the date
formatted_date = current_datetime.strftime("%B %d, %Y")
print("Formatted Date:", formatted_date)
# Format the time
formatted_time = current_datetime.strftime("%I:%M %p")
print("Formatted Time:", formatted_time)
Formatted Date: November 20, 2023 Formatted Time: 04:12 PM
In [5]:
birthdate=datetime(2003,4,9,9,00)
str1=birthdate.strftime("%B,%d %Y %I:%M %p")
print(str1)
April,09 2003 09:00 AM
C) finding duration using timedelta¶
In [8]:
from datetime import datetime,date,timedelta
# Get the current date and time
start_date = date(2022, 1, 1) # Replace with your start date and time
end_date = date(2023, 11, 20,) # Replace with your end date and time
# Calculate the duration
duration = end_date - start_date
print("duration between start date and end date:",duration)
duration between start date and end date: 688 days, 0:00:00
D) stopping excuation temporarily¶
In [9]:
#By using sleep() function we can stop excuation temporarily for specific time
import time
for i in range(10):
print(i)
if i==5:
time.sleep(2) #its takes 2 sec break then print remaining..
0 1 2 3 4 5 6 7 8 9
E) working with calendar module¶
In [16]:
import calendar
print(calendar.calendar(2024,3))
2024 January February March Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 1 2 3 4 1 2 3 8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10 15 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17 22 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24 29 30 31 26 27 28 29 25 26 27 28 29 30 31 April May June Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 1 2 3 4 5 1 2 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 29 30 27 28 29 30 31 24 25 26 27 28 29 30 July August September Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 1 2 3 4 1 8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8 15 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15 22 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22 29 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29 30 October November December Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 1 2 3 1 7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8 14 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15 21 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22 28 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29 30 31
In [15]:
#to print specific months calendar
print(calendar.month(2003,4,3))
April 2003 Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
In [22]:
#to get all the months name
month_name=calendar.month_name
for i in month_name:
print(i)
January February March April May June July August September October November December
In [24]:
# to get all the days from the calendar
days_name=calendar.day_name
for i in days_name:
print(i)
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
In [25]:
#when we want to change the week header of calendar like when we want monday as a first
# (0) reprsent monday similary (1) presents tuesday and so on..
calendar.setfirstweekday(0)
print(calendar.month(2023,11))
November 2023 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
In [33]:
# to get the header of calendar
header=calendar.weekheader(3)
print(header)
Mon Tue Wed Thu Fri Sat Sun
In [1]:
#python program to get isleep year
import calendar
year=calendar.isleap(2020)
if year is True:
print("yes,it is a leap year")
else:
print("no,its not a leap year")
yes,it is a leap year
In [5]:
#python program to get leap days
import calendar
leap_days=calendar.leapdays(2000,2050)
print(f"leapdays from 2000 to 2050 are: {leap_days}")
leapdays from 2000 to 2050 are: 13
In [7]:
#to find day on that specific yearn and month
import calendar
day=calendar.weekday(2003,4,9)
print(day) # 0=monday,1=tuesday,2=wednesday..and so on
2
In [ ]: