Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/Functions.ipynb
3074 views
Kernel: Python 3
#Function Without Arguments def EmpID(): x=input("Enter your Emp ID") EmpID()
Enter your Emp ID1234
def details (name, age): print(name,age,sep="\t") details("SAI",34)
SAI 34
#Create a funtion named cali , add,sub,mul,div choice=+(add),-(sub),mul(*),div(/)
#Functions with Arguments x=int(input("input 1= ")) y=int(input("input 2= ")) def cal(x,y): choice=input("Enter your choice") if choice=="+": print("sum=",x+y) elif choice=="-": print("sub=",x-y) elif choice=="*": print("prod=",x*y) else: print("option not aviliable") cal(x,y)
input 1= 2 input 2= 34 Enter your choice* prod= 68

Return() is not mandatory in Python

  • To let a function return a value, use the return statement:

def te(x,y): s=x+y return x/y te(8,7)
1.1428571428571428

Different variable class can be passed within a function

def Emp(name,age,f): print(name,age,f,sep="\t") Emp("Ashi",2,6) Emp(1,2,3)
def dex(*emp): print("The oldest employee is: " + emp[-1]) dex("Abc","ab12","er3") dex("A","B") dex ("ram","sam","lam","man")
The oldest employee is: er3 The oldest employee is: B The oldest employee is: man
# create a function to return largest member from a list(names)
def food(fruit): for i in fruit: print(i) fruits=["kiwi","apple","pie","abc"] food(fruits)
kiwi apple pie abc

lambda - one line function which can take any number of argumnets:

z= lambda a,b,c:a*b/c z(8,9,3)
24.0
## Create a lamba function that returns cube of a number. z = lambda s:s*s*s z(9)
729
a=[2,4,-9,4,6,8,44,20,33] even_list = list(filter(lambda x:(x%2 == 0),a)) even_list
[2, 4, 4, 6, 8, 44, 20]
## Date Time Module import time

Write a Python script to display the various Date Time formats.

  • a) Current date and time

  • b) Current year

  • c) Month of year

  • d) Week number of the year

  • e) Weekday of the week

  • f) Day of year

  • g) Day of the month

  • h) Day of week

import datetime as d print("Current date and time: " , d.datetime.now())
Current date and time: 2021-02-01 16:53:32.344239
import time ## Provide delay in a program print("Hi") time.sleep(2) print("Welcome")
Hi Welcome

Python code to check time of execution of a program

# starting time start = time.time() # program body starts for i in range(10): print(i) # sleeping for 1 sec to get 10 sec runtime time.sleep(1) # program body ends # end time end = time.time() # total time taken print(f"Runtime of the program is {end - start}")

- Q Write a Python function to sum all the numbers in a list.

def sum(numbers): total = 0 for x in numbers: total += x return total #print(sum((12,34,55))) sum((12,12))

- Q Write a Python funtion to check whether a given number is the given range?

def test_range(n): if n in range(12,50): print( " %s is in the range"%str(n)) else : print("The number is outside the given range.") test_range(13)

- Q Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters

def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0,"SPACES_":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print ("Original String : ", s) print ("No. of Upper case characters : ", d["UPPER_CASE"]) print ("No. of Lower case Characters : ", d["LOWER_CASE"]) string_test("PRACTICE More")

Lamba Function

ambda function

  • The lambda keyword is used to create anonymous functions - This function can have any number of arguments but only one expression, which is evaluated and returned. - One is free to use lambda functions wherever function objects are required. - You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.

z=[1,2,3,4] x=list(map(lambda y:(y+2),z)) print(x)
x=lambda a : a**3 print(x(3))
a=[1,3,4,6,23,44,56,78,90,54,60] list_div6= list(filter(lambda x:(x %6==0),a)) print(list_div6)
##Lambda functions can take any number of arguments x = lambda a, b,c : a**2+b*3+c print(x(5, 6,7))

Write a Python program to sort a list of tuples using Lambda

subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)] print("Original list of tuples:") print(subject_marks) subject_marks.sort(key = lambda x: x[1]) print("\nSorting the List of Tuples:") print(subject_marks)

The power of lambda is better shown when you use them as an anonymous function inside another function.

def my(r): print(4*r) my(3)
def myfunc(n): print("The number:",n) return lambda a : n**a r = myfunc(6) print(r(4))
def mydata(n): return lambda a,b:(a+b)*n var = mydata(4) print(var(2,3))

Classes in Python &OO programming

class Program1: "HI" print(Program1)#Tell about status of class. print(60*"*")
class Program1: name="RAM" age = 29 print("NAME is %s and age is %d"%(Program1.name,Program1.age)) print(60*"*")
# Create a class name mobile store, Price=0.0,Type="",Brand, Three class Program1: name="RAM" age = 29 Emp1= Program1() Emp2 = Program1() Emp3 = Program1() Emp1.name ="A" Emp1.age = 9 Emp2.name = "B" Emp2.age = 32 Emp3.name= "C" Emp3.age = 47 #print(" %s %d "%(Emp1.name,Emp1.age)) #print(" %s %d "%(Emp2.name,Emp2.age)) #print(" %s %d "%(Emp3.name,Emp3.age)) for x in range(1,4): print(eval("Emp%d.name"%(x)), eval("Emp%d.age"%(x)))
x=6 eval("x**x*x+98+x")
#Class &Objects class Phone: Color=" " Price =00 Type=" " ob1=Phone()#Creation of objects and assinging it to class phone. ob2=Phone() ob1.Color="RED" ob1.Price=10000 ob1.Type="Smart" ob2.Color="Black" ob2.Price=12000 ob2.Type="Smart" print("This is a %s phone of %s color and its price is %drs"%(ob1.Type,ob1.Color,ob1.Price)) print("This is a %s phone of %s color and its price is %drs"%(ob2.Type,ob2.Color,ob2.Price)) print(50*"*")

- self is used to represent the instance of the class. With this keyword, you can access the attributes and methods class in python. it helps to bind attributes with the given arguments.

- In Python we have methods that make the intance to be passed automatically, but not received automatically.

class X: "Classses and functions" myroll= 9 def student(self): print('This is Science Class') ob = X() print(X.student) print(ob.student) ob.student() print(8*"*")

Class name calci , compute sum, sub, divsion using a fucntion called finalo/p.

class Y: a = 9 b = 3.3 c = 23.4 d = 0.0 def details(r): r.c= r.a * r.b r.d = r.a/r.b t=round(r.d,3) print(r.c,t,sep=",") cal1=Y() cal2= Y() cal1.a=5 cal1.b=4.7 cal1.details()
### Class and Function class Shop: "Things in MYshop" Quantity = 10 Type = "" price=500.00 def bill(self): print("your bill for % s dress of %d quantity is %drs:"%(self.Type,self.Quantity,self.price)) coustmer1=Shop() coustmer1.Quantity=5 coustmer1.Type="saree" coustmer1.price=20000 coustmer1.bill() print(50*"*")
# dictionary from an class's fields. class dObj(): def __init__(self): self.x = 'age' self.y = 'name' self.z = 'Gender' def do(self): pass d = dObj() print(d.__dict__)