I know two ways to declare a function (Examples below). Are there other ways?
#example 1
def f(x): return x
#example 2
f = lambda x: x
CodePudding user response:
You can create a function directly given a code object and a global namespace. This is not something you would ever use in almost any real code.
Here is a bare-bones example:
>>> import types
>>> code_obj = compile('print("hello world")', '', 'single')
>>> g = {'print': print}
>>> f = types.FunctionType(code_obj, g)
>>> f()
hello world
CodePudding user response:
//variable no of arguments
def add(*a):
sum =0
for x in a:
sum = x
return sum
a=add(10,20,30)
print(a)
//default arguments
def employdetails(eno,ename,gender="male",age="18"):
print("Employee Details:")
print("Employee No:",eno)
print("Employee Name:",ename)
print("Age:",age)
print("Gender:",gender)
print(employdetails(eno="1",ename="nagur",age="20"))
//keyword arguments
def employdetails(eno,ename,gender):
print("employee details:")
print("Employee No:",eno)
print("Employee Name:",ename)
print("Gender:",gender)
print(employdetails(eno="1",ename="nagur",gender="male"))
//lambda function
li=[1,2,3]
li2=[4,5,6]
li3=[7,8,9]
add = map(lambda a,b,c:a b c ,li,li3,li2)
for x in add:
print(x)
//positional arguments
def add(a,b):
return a b
a=int(input("enter the a value:"))
b=int(input("enter the b value:"))
print(add(a,b))
Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function.
Add statements that the functions should execute.
Defining a function:
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax def functionname( parameters ): "function_docstring" function_suite return [expression]