This document discusses functions in Python. It defines what a function is and provides the basic syntax for defining a function using the def keyword. It also covers function parameters, including required, keyword, default, and variable-length arguments. The document explains how to call functions and discusses pass by reference vs pass by value. Additionally, it covers anonymous functions, function scope, and global vs local variables.
Python programming - Functions and list and tuplesMalligaarjunanN
- A function is a block of reusable code that takes in parameters, performs an action, and returns a value. Functions provide modularity and code reusability.
- Functions in Python are defined using the def keyword followed by the function name and parameters in parentheses. The code block is indented and can return a value. Parameters can have default values.
- Functions can take positional arguments, keyword arguments, and variable length arguments. Parameters are passed by reference, so changes inside the function also affect the variables outside.
- Anonymous functions called lambdas are small single expression functions defined with the lambda keyword. They do not have a name and cannot contain multiple expressions or statements.
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
Multidimensional arrays store data in tabular form with multiple indices. A 3D array declaration would be datatype arrayName[size1][size2][size3]. Elements can be initialized and accessed similar to 2D arrays but with additional nested brackets and loops for each dimension. Functions allow dividing a problem into smaller logical parts. Functions are defined with a return type, name, parameters and body. Arguments are passed by value or reference and arrays can also be passed to functions. Recursion occurs when a function calls itself, requiring a base case to terminate the recursion.
The document discusses functions in Python. It describes what functions are, different types of built-in functions like abs(), min(), max() etc. It also discusses commonly used modules like math, random, importing modules and functions within modules. It explains function definition, parameters, scope and lifetime of variables, return statement, default parameters, keyword arguments, variable length arguments and command line arguments.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
This document discusses functions and modular programming in C++. It defines what a function is and explains that functions allow dividing code into separate and reusable tasks. It covers function declarations, definitions, parameters, return types, and calling functions. It also discusses different ways of passing arguments to functions: call by value, call by pointer, and call by reference. Finally, it provides an example program that calculates addition and subtraction using different functions called within the main function. Modular programming is also summarized as dividing a program into independent and reusable modules to reduce complexity, decrease duplication, improve collaboration and testing.
The document discusses functions in Python. It defines what functions are, how to define functions, pass arguments to functions, return values from functions, and scope of objects in functions. It covers built-in functions, when to write your own functions, and different types of arguments like required arguments, keyword arguments, default arguments, and variable-length arguments. It also discusses how functions communicate with their environment through parameters and arguments, and pass-by-reference vs pass-by-value in Python functions.
This document discusses modular programming in C, specifically functions and parameters. It defines functions as blocks of code that perform specific tasks. Functions have components like declarations, definitions, parameters, return values, and scope. Parameters can be passed into functions and different storage classes like auto, static, and extern determine variable lifetime and scope. Functions are useful for code reusability and modularity.
The document discusses functions in C++. It begins by outlining key topics about functions that will be covered, such as function definitions, standard library functions, and function calls. It then provides details on defining and calling functions, including specifying return types, parameters, function prototypes, scope rules, and passing arguments by value or reference. The document also discusses local and global variables, function errors, and the differences between calling functions by value or reference.
Functions allow programmers to organize Python code into reusable chunks. They take in parameters, perform tasks, and return outputs. Variables used inside functions have local scope, while those outside have global scope. Functions can take different argument types like required, keyword, default, and variable arguments. Functions are first-class objects in Python - they can be defined inside other functions, returned from functions, or passed into functions as arguments. Common built-in functions like map() and filter() apply functions across iterable objects.
The document discusses functions in C programming. It defines functions as mini-programs that can take in inputs, execute statements, and return outputs. Functions allow programmers to break large tasks into smaller, reusable parts. The key aspects of functions covered include: defining functions with return types and parameters; calling functions and passing arguments; return values; function prototypes; recursion; and examples of calculating factorials and acceleration using functions.
This document discusses functions in C programming. It defines functions as blocks of code that perform specific tasks. It explains the key components of functions - function declaration, definition, and call. It provides examples of defining, declaring, and calling functions. It also discusses recursion, system-defined library functions, and user-defined functions.
Chapter Functions for grade 12 computer ScienceKrithikaTM
1. A function is a block of code that performs a specific task and can be called anywhere in a program. Functions make code reusable, improve modularity, and make programs easier to understand.
2. There are three main types of functions: built-in functions, functions defined in modules, and user-defined functions. Built-in functions are pre-defined and always available, module functions require importing, and user-defined functions are created by programmers.
3. Functions improve code organization and readability by separating code into logical, modular units. Functions can take parameters, return values, and be called from other parts of a program or other functions. This allows for code reuse and modular programming.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Multidimensional arrays store data in tabular form with multiple indices. A 3D array declaration would be datatype arrayName[size1][size2][size3]. Elements can be initialized and accessed similar to 2D arrays but with additional nested brackets and loops for each dimension. Functions allow dividing a problem into smaller logical parts. Functions are defined with a return type, name, parameters and body. Arguments are passed by value or reference and arrays can also be passed to functions. Recursion occurs when a function calls itself, requiring a base case to terminate the recursion.
The document discusses functions in Python. It describes what functions are, different types of built-in functions like abs(), min(), max() etc. It also discusses commonly used modules like math, random, importing modules and functions within modules. It explains function definition, parameters, scope and lifetime of variables, return statement, default parameters, keyword arguments, variable length arguments and command line arguments.
This document provides an outline and overview of functions in C++. It discusses:
- The definition of a function as a block of code that performs a specific task and can be called from other parts of the program.
- The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more.
- The parts of a function definition including the return type, name, parameters, and body.
- How to declare functions, call functions by passing arguments, and how arguments are handled.
- Scope rules for local and global variables as they relate to functions.
This document discusses functions and modular programming in C++. It defines what a function is and explains that functions allow dividing code into separate and reusable tasks. It covers function declarations, definitions, parameters, return types, and calling functions. It also discusses different ways of passing arguments to functions: call by value, call by pointer, and call by reference. Finally, it provides an example program that calculates addition and subtraction using different functions called within the main function. Modular programming is also summarized as dividing a program into independent and reusable modules to reduce complexity, decrease duplication, improve collaboration and testing.
The document discusses functions in Python. It defines what functions are, how to define functions, pass arguments to functions, return values from functions, and scope of objects in functions. It covers built-in functions, when to write your own functions, and different types of arguments like required arguments, keyword arguments, default arguments, and variable-length arguments. It also discusses how functions communicate with their environment through parameters and arguments, and pass-by-reference vs pass-by-value in Python functions.
This document discusses modular programming in C, specifically functions and parameters. It defines functions as blocks of code that perform specific tasks. Functions have components like declarations, definitions, parameters, return values, and scope. Parameters can be passed into functions and different storage classes like auto, static, and extern determine variable lifetime and scope. Functions are useful for code reusability and modularity.
The document discusses functions in C++. It begins by outlining key topics about functions that will be covered, such as function definitions, standard library functions, and function calls. It then provides details on defining and calling functions, including specifying return types, parameters, function prototypes, scope rules, and passing arguments by value or reference. The document also discusses local and global variables, function errors, and the differences between calling functions by value or reference.
Functions allow programmers to organize Python code into reusable chunks. They take in parameters, perform tasks, and return outputs. Variables used inside functions have local scope, while those outside have global scope. Functions can take different argument types like required, keyword, default, and variable arguments. Functions are first-class objects in Python - they can be defined inside other functions, returned from functions, or passed into functions as arguments. Common built-in functions like map() and filter() apply functions across iterable objects.
The document discusses functions in C programming. It defines functions as mini-programs that can take in inputs, execute statements, and return outputs. Functions allow programmers to break large tasks into smaller, reusable parts. The key aspects of functions covered include: defining functions with return types and parameters; calling functions and passing arguments; return values; function prototypes; recursion; and examples of calculating factorials and acceleration using functions.
This document discusses functions in C programming. It defines functions as blocks of code that perform specific tasks. It explains the key components of functions - function declaration, definition, and call. It provides examples of defining, declaring, and calling functions. It also discusses recursion, system-defined library functions, and user-defined functions.
Chapter Functions for grade 12 computer ScienceKrithikaTM
1. A function is a block of code that performs a specific task and can be called anywhere in a program. Functions make code reusable, improve modularity, and make programs easier to understand.
2. There are three main types of functions: built-in functions, functions defined in modules, and user-defined functions. Built-in functions are pre-defined and always available, module functions require importing, and user-defined functions are created by programmers.
3. Functions improve code organization and readability by separating code into logical, modular units. Functions can take parameters, return values, and be called from other parts of a program or other functions. This allows for code reuse and modular programming.
It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc
function with
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
Call by value and address
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
Analysis of reinforced concrete deep beam is based on simplified approximate method due to the complexity of the exact analysis. The complexity is due to a number of parameters affecting its response. To evaluate some of this parameters, finite element study of the structural behavior of the reinforced self-compacting concrete deep beam was carried out using Abaqus finite element modeling tool. The model was validated against experimental data from the literature. The parametric effects of varied concrete compressive strength, vertical web reinforcement ratio and horizontal web reinforcement ratio on the beam were tested on eight (8) different specimens under four points loads. The results of the validation work showed good agreement with the experimental studies. The parametric study revealed that the concrete compressive strength most significantly influenced the specimens’ response with the average of 41.1% and 49 % increment in the diagonal cracking and ultimate load respectively due to doubling of concrete compressive strength. Although the increase in horizontal web reinforcement ratio from 0.31 % to 0.63 % lead to average of 6.24 % increment on the diagonal cracking load, it does not influence the ultimate strength and the load-deflection response of the beams. Similar variation in vertical web reinforcement ratio leads to an average of 2.4 % and 15 % increment in cracking and ultimate load respectively with no appreciable effect on the load-deflection response.
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
3. Python - Functions
• A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provides better modularity
for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These functions
are called user-defined functions.
4. Defining a Function
Here are simple rules to define a function in Python:
• 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]
5. • Syntax:
def functionname( parameters ):
"function_docstring”
function_code
return [expression]
By default, parameters have a positional behavior, and you need
to inform them in the same order that they were defined.
• Example:
def printme( str ):
“creating first function”
print("This prints a passed string function“)
print (str)
Printme(“Happy Programming!”)
6. Calling a Function without argument
• Following is the example to call printme() function:
def print():
“creating second function to display msg”
print(“Hello world”);
print()
print();
• This would produce following result:
Hello world
Hello world
Here function print() is called without arguments .
This function is called twice so displays Hello world
twice.
7. Calling a Function with argument i.e
Pass by reference
All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a
function, the change also reflects back in the calling function. For
example:
Program to add two numbers using function with arguments
def add(a,b):
sum=a+b
print sum
add(2,3) # calling add with two arguments 2,3 will print 5
add(4,5) # calling add with two arguments 4,5 will print 9
8. Calling a Function with argument
Program to swap two numbers using function with arguments
def swap(a,b):
temp=a
a=b
b=temp
x=2
y=3
print(“before swap x=“,x,”y=“,y)
swap(x,y) # swaping two numbers using pass byreference
print(“after swap x=“,x,”y=“,y)
====Output=====
before swap x=2 y=3
after swap x=3 y=2
9. Passing List to function
def changeme( mylist ):
#This function changes a passed list
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
10. There is one more example where argument is being passed by reference but
inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes
nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
11. Function returning value
A return statement is used to end the execution of the function
call and “returns” the result (value of the expression following
the return keyword) to the caller.
The statements after the return statements are not executed. If
the return statement is without any expression, then the special
value None is returned.
A return statement is overall used to invoke a function so that
the passed statements can be executed.
Note: Return statement can not be used outside the function.
Syntax:
def functionname(parameters):
statements
.
.
return [expression]
12. Function returning value Example
Function to find cube of a number and return value of
cube
def cube(x):
r=x**3
return r
val=cube(3)
#calls function and pass 3
#function returns value and store in val
print(“cube is”,value)
Output
Cube is 27
13. Function returning value Example
Program to find factorial of a number using function
returning value
def factorial(x):
fact=1
for i in range(1,x+1):
fact=fact*I
return fact
num=4
f=factorial(num)
print(“factorial of”,num,” is”,f)
14. Function returning Multiple values
In Python, we can return multiple values from a function
def getdata():
name = “Rahi"
rollno= 20
return rollno,name;
# call function
n,r = getdata()
print(“name=“,n)
print(“rollno=“,r)
15. Function Arguments:
A function by using the following types of formal arguments::
– Positional arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Positional arguments:
– The list of variables declared in the parentheses at the time of
defining a function are the formal arguments. And, these arguments
are also known as positional arguments. A function may be defined
with any number of formal arguments.
– While calling a function −
– All the arguments are required.
– The number of actual arguments must be equal to the number of
formal arguments.
– They Pick up values in the order of definition.
16. Positional arguments Example
def add(x,y):
z = x+y
print (z)
a = 10
b = 20
add(a, b)
It will produce the following output −
x=10 y=20 x+y=30
Here, the add() function has two formal arguments, both are
numeric.
When integers 10 and 20 passed to it. The variable "a" takes 10
and "b" takes 20, in the order of declaration. The add() function
displays the addition.
17. Keyword arguments:
• Keyword arguments are related to the function calls. When you
use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
• This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords
provided to match the values with parameters.
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function by positional
arguments
printinfo ("Naveen", 29)
# by keyword arguments
printinfo(name="miki", age = 30)
printinfo(age=40,name=“Raghav”)
18. Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
printinfo( age=40, name=“Raghav" );
• This would produce following result:
Name: Raghav Age 40
19. Default arguments:
• A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
• Following example gives idea on default arguments, it would
print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
20. Variable-length arguments:
• You may need to process a function for more arguments than
you specified while defining the function. These arguments are
called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
• The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *args_tuple ):
function_code
return [expression]
21. • An asterisk (*) is placed before the variable name that will hold
the values of all nonkeyword variable arguments. This tuple
remains empty if no additional arguments are specified during
the function call. For example:
def printinfo(*argstuple ):
print(“in function”)
for var in vartuple:
print var
printinfo();
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
In function
Output is:
In function
70
60
50
22. The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions.
These functions are called anonymous because they are not declared
in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression.
• Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the
global namespace.
• Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose
purpose is by passing function stack allocation during invocation for
performance reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
23. Example:
• Following is the example to show how lembda form of function
works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
24. Scope of Variables:
• All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where
you can access a particular identifier. There are two basic scopes of
variables in Python:
Global variables
Local variables
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
• This means that local variables can be accessed only inside the
function in which they are declared whereas global variables can be
accessed throughout the program body by all functions. When you call
a function, the variables declared inside it are brought into scope.
25. • Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ): # arg1 and arg2 are local
variables
total = arg1 + arg2;
print "Inside the function local total : ", total
# Now call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Note:
1.Scope of local variables is within function
2.Scope of global variables is outside function also.
26. Questions
• Create function to find whether number is
prime or not using function with argument
• Create a function to find area of circle
• Create a function to return area and
perimeter of cube