. Python Functions
[1]:
12345
# Defining a function
def my_function():
print("Hello from a function")
# Calling a function
my_function()stdout
Hello from a function
[2]:
1234
# adding argument
def my_func(a):
print(a)
my_func('hello')stdout
hello
[4]:
1234
# multiple arguments
def my_func(a,b):
print(a+b)
my_func(1,2)stdout
3
[5]:
1234567
# return statement in a function
def my_func(a,b):
return a+b
var1=1
var2=2
total=my_func(var1,var2)
print(total)stdout
3
[8]:
12345678
# what if the number of arguemts are not fixed
def my_func(*args):
return sum(args)
print(my_func(1,2,3))
print(my_func(1,2,3,4))
print(my_func(1,2,3,5,6))
Out[8]:
tuple
[10]:
1234567
# keyword argument - you can also send named arguments to the function
def my_func(val1,val2,val3):
print(f"val1 is {val1}")
print(f"val2 is {val2}")
print(f"val3 is {val3}")
my_func(val1=1,val3=3,val2=2) # notice that i am passing val3 first and val2 at the last because this is a keyword argument
stdout
val1 is 1
val2 is 2
val3 is 3
[11]:
12345
# Artibitary keyword argument
def myfunc(**keyword):
print("my name is ",keyword['name'])
print("my occupation is ",keyword['occ'])
myfunc(name='pranjal',occ='DS')stdout
my name is pranjal
my occupation is DS
[13]:
1234
# Default value of a parameter
def myfunc(a,b=2):
return a/b
myfunc(2,1)Out[13]:
2.0
[14]:
123456
# Passing sequence data types in function
def myfunc(l):
for i in l:
print(i)
lst=[1,2,3,2,1]
myfunc(lst) stdout
1
2
3
2
1
[15]:
1234567
# recursive functions - finding factoricla
def factorical(n):
if n==0:
return 1
else:
return n*factorical(n-1)
factorical(5)Out[15]:
120
[16]:
12
add = lambda x,y:x+y
add(3,4)Out[16]:
7
[17]:
1234567
# It is used to create another function
def myfunc(n):
return lambda x:x*n
doubler=myfunc(2)
tripler=myfunc(3)
print(doubler(5))
print(tripler(5))stdout
10
15
[18]:
1
# write a function to check if a number is a prime number or not[19]:
1
# write a function to count the number of vowels in a sentence [ ]:
1
# write a function that returns the sum of a list[20]:
1
import os [21]:
12
# get current working directory
os.getcwd()Out[21]:
'C:\\Users\\pranjal.p.bhatt.INTKYV\\Documents\\python projects\\Training'
[ ]:
12
# make a directory
os.mkdir("directory_path")[24]:
1234
# join file and folder names
folder_path=r"C:\Users\pranjal.p.bhatt.INTKYV\Documents\python projects\Training"
file_name="Test Data.csv"
os.path.join(folder_path,file_name)Out[24]:
'C:\\Users\\pranjal.p.bhatt.INTKYV\\Documents\\python projects\\Training\\Test Data.csv'
[25]:
12
# list of all files in a folder
os.listdir(folder_path)Out[25]:
['.ipynb_checkpoints',
'2. Operators in python.ipynb',
'3. Loops & Control Statement in python.ipynb',
'4. String Operations.ipynb',
'5. list, sets, tuple & dictionary operations.ipynb',
'6. Python Functions.ipynb',
'6.Assignement - functions.ipynb',
'Assignment 2 - Operators.ipynb',
'Assignment 3 - Loops & Control Statement.ipynb',
'Assignment 4 - list ,tuple,sets & dict operations.ipynb',
'imputer_mean_02.pkl',
'imputer_mean_910.pkl',
'imputer_most_frequent_38.pkl',
'labelEncoder_3.pkl',
'labelEncoder_4.pkl',
'labelEncoder_5.pkl',
'labelEncoder_6.pkl',
'labelEncoder_7.pkl',
'labelEncoder_8.pkl',
'myModel.pkl',
'onehotencoder.pkl',
'scaler.pkl',
'Statistics',
'Test Data.csv',
'Training Data.csv',
'Use Case.ipynb']
[26]:
123
# remove file or directory
# os.remove(file_full_path)
# os.rmdir(folder_path)[28]:
12
# check if a path exist or not
os.path.exists("file_path")Out[28]:
False
[29]:
1
import datetime as dt[31]:
123
# get current time
print(dt.datetime.now())
print(type(dt.datetime.now()))stdout
2024-05-31 16:19:55.803702
<class 'datetime.datetime'>
[35]:
123
# converting current time to string
print(str(dt.datetime.now()))
stdout
2024-05-31 16:20:56.426767
[38]:
123
# extract only current date
print(dt.datetime.now().date())
stdout
2024-05-31
[42]:
1234
# convert string to datetime type object
time_str='2020-01-31 00:21:30'
datetime_object=dt.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')
datetime_objectOut[42]:
datetime.datetime(2020, 1, 31, 0, 21, 30)
[44]:
123456
# extracting year ,month etc from datetime types object
print(datetime_object.year)
print(datetime_object.month)
print(datetime_object.day)
print(datetime_object.hour)
stdout
2020
1
31
0
[47]:
123456
# convert datetime to string format
time_str='2020-01-31 00:21:30'
datetime_object=dt.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')
str_object=dt.datetime.strftime(datetime_object,'%m-%d-%Y %H:%M:%S')
str_objectOut[47]:
'01-31-2020 00:21:30'
[52]:
12345
# difference between 2 date object
start=dt.datetime.now()
[x**2 for x in range(10000000)]
delta=dt.datetime.now()-start
delta.total_seconds()Out[52]:
2.975802
[53]:
1
import random[54]:
12
# generate random number between a range
random.randint(1,100)Out[54]:
34
[58]:
12
# generate random decimal number
random.uniform(a=100,b=1000) # random decimal number between 100 and 1000Out[58]:
247.97584647445072
[62]:
123
# get random value from a list
sample_list=[1,2,3,4,5,6,6,7,8]
print(random.choice(sample_list))stdout
7