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
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.
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 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.
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.
The document discusses Python functions. It defines functions as reusable blocks of code that can be called anywhere in a program. Some key points covered include:
- Functions allow code reuse and make programs easier to understand by splitting them into logical blocks.
- There are built-in and user-defined functions. User-defined functions are defined using the def keyword followed by the function name and parameters.
- Functions can take arguments, have default values, and return values. They improve readability and maintainability of large Python programs.
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.
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.
This presentation educates you about the Functions of the Python, Defining a Function, Calling a Function, Pass by reference vs value, Pass by reference vs value, Required arguments, Keyword arguments, Default arguments and Variable-length arguments.
For more topics stay tuned with Learnbay.
The document discusses object-oriented programming in Python using functions and modules. It covers key topics such as defining functions, calling functions, function arguments, scope rules, modules and importing modules. Specific functions like built-in functions, lambda functions, and passing functions as arguments are explained. The document also discusses defining user-defined functions, variable-length arguments, global vs local variables and their scopes. Examples are provided to illustrate concepts like function arguments, default arguments, and variable-length arguments.
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.
The document discusses functions in the Python math module. It provides a list of common mathematical functions in the math module along with a brief description of what each function does, such as ceil(x) which returns the smallest integer greater than or equal to x, copysign(x, y) which returns x with the sign of y, and factorial(x) which returns the factorial of x. It also includes trigonometric functions like sin(x), cos(x), and tan(x), their inverse functions, and functions for exponentials, logarithms, and other common mathematical operations.
This document discusses functions in C programming. It defines a function as a self-contained block of statements that performs a specific task. Functions have a unique name, receive values from the calling program, may return a value, and are independent and reusable. There are two types of functions: predefined/standard library functions and user-defined functions. The document outlines the advantages of using functions and modular design. It also explains function declarations, definitions, parameters, scope, and how to define and call user-defined functions in C using both call-by-value and call-by-reference parameter passing.
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.
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.
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 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.
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.
The document discusses Python functions. It defines functions as reusable blocks of code that can be called anywhere in a program. Some key points covered include:
- Functions allow code reuse and make programs easier to understand by splitting them into logical blocks.
- There are built-in and user-defined functions. User-defined functions are defined using the def keyword followed by the function name and parameters.
- Functions can take arguments, have default values, and return values. They improve readability and maintainability of large Python programs.
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.
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.
This presentation educates you about the Functions of the Python, Defining a Function, Calling a Function, Pass by reference vs value, Pass by reference vs value, Required arguments, Keyword arguments, Default arguments and Variable-length arguments.
For more topics stay tuned with Learnbay.
The document discusses object-oriented programming in Python using functions and modules. It covers key topics such as defining functions, calling functions, function arguments, scope rules, modules and importing modules. Specific functions like built-in functions, lambda functions, and passing functions as arguments are explained. The document also discusses defining user-defined functions, variable-length arguments, global vs local variables and their scopes. Examples are provided to illustrate concepts like function arguments, default arguments, and variable-length arguments.
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.
The document discusses functions in the Python math module. It provides a list of common mathematical functions in the math module along with a brief description of what each function does, such as ceil(x) which returns the smallest integer greater than or equal to x, copysign(x, y) which returns x with the sign of y, and factorial(x) which returns the factorial of x. It also includes trigonometric functions like sin(x), cos(x), and tan(x), their inverse functions, and functions for exponentials, logarithms, and other common mathematical operations.
This document discusses functions in C programming. It defines a function as a self-contained block of statements that performs a specific task. Functions have a unique name, receive values from the calling program, may return a value, and are independent and reusable. There are two types of functions: predefined/standard library functions and user-defined functions. The document outlines the advantages of using functions and modular design. It also explains function declarations, definitions, parameters, scope, and how to define and call user-defined functions in C using both call-by-value and call-by-reference parameter passing.
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.
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.
This document discusses stacking, an ensemble machine learning method. Stacking involves training multiple base models on a dataset and then training a meta-model to make predictions based on the predictions of the base models. Specifically, stacking trains a meta-learner on the out-of-sample predictions from each base model to improve predictive performance. Stacking allows for a diverse set of base model types and can incorporate their probabilistic outputs to help the meta-model avoid overfitting.
This document discusses various ensemble machine learning techniques including decision trees, bagging, boosting, and stacking. It provides the following information:
- Decision trees work by recursively splitting a dataset into purer subsets based on entropy, Gini index, or error impurity measures to minimize at each node.
- Bagging creates multiple classifiers by sampling the training data with replacement and takes a majority vote. Random forest is a variant that also samples features. This reduces variance.
- Boosting iteratively reweights instances based on misclassifications and combines weak learners into a weighted ensemble. AdaBoost is an example algorithm.
- Stacking combines multiple learning algorithms by using one as a meta-learner on
- DBMS stands for Database Management System and is a collection of interrelated data and a set of programs used to access, update, and manage the data. The goal of a DBMS is to provide an environment that is convenient and efficient for retrieving, storing, and manipulating data.
- A database schema represents the logical structure of a database and includes information about the database's tables, fields, relationships, and data types. A database instance is a snapshot of the data stored in a database at a particular point in time.
- There are three levels of data abstraction: the physical level describes how data is physically stored, the logical level describes the logical relationships and structure of data, and the view level describes how different
The document discusses principles of effective writing. It provides tips for clear communication, such as using an active voice, eliminating unnecessary words, and maintaining parallel structure in lists. Some key points covered include writing with a clear purpose in mind, using concise language, and focusing on what is being said rather than how it is being said. Effective writing is presented as a learnable craft based on logical thinking and simple style rules.
There are 4 main types of machine learning technologies: supervised learning, unsupervised learning, semi-supervised learning, and reinforcement learning. Supervised learning uses labeled data for training, unsupervised learning finds patterns in unlabeled data, semi-supervised uses both labeled and unlabeled data, and reinforcement learning allows an agent to learn from its environment through rewards. Examples of machine learning technologies include facial recognition, credit card fraud detection, recommendation systems, and loan application approvals.
Blockchain is a decentralized and distributed ledger system that allows multiple parties to securely record and store information in a transparent and tamper-resistant manner. It works by creating a chain of blocks, with each block containing a set of transactions. This chain is then distributed across a network of computers, making it nearly impossible to alter. Key features of blockchain include decentralization, transparency, immutability, and security. While applications include cryptocurrency, NFTs, and supply chain management, challenges remain around scalability, energy consumption, and potential security flaws from 51% attacks.
Renewable energy sources like solar and wind power are reducing reliance on fossil fuels and emissions. A circular economy promotes reuse, recycling and repurposing to minimize waste and maximize resource use. Innovations in green transportation like electric vehicles and public transit are prioritizing sustainable mobility options. Smart cities integrate technologies to optimize energy, transportation and infrastructure usage while enhancing quality of life and minimizing environmental footprints. Biodegradable materials offer eco-friendly alternatives to plastics and packaging by embracing materials that naturally decompose.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearARUN KUMAR
Definition and classification with examples
Sources, chemical nature, functions, coenzyme form, recommended dietary requirements, deficiency diseases of fat- and water-soluble vitamins
How to Subscribe Newsletter From Odoo 18 WebsiteCeline George
Newsletter is a powerful tool that effectively manage the email marketing . It allows us to send professional looking HTML formatted emails. Under the Mailing Lists in Email Marketing we can find all the Newsletter.
As of Mid to April Ending, I am building a new Reiki-Yoga Series. No worries, they are free workshops. So far, I have 3 presentations so its a gradual process. If interested visit: https://www.slideshare.net/YogaPrincess
https://ldmchapels.weebly.com
Blessings and Happy Spring. We are hitting Mid Season.
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 771 from Texas, New Mexico, Oklahoma, and Kansas. 72 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly.
The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsDrNidhiAgarwal
Unemployment is a major social problem, by which not only rural population have suffered but also urban population are suffered while they are literate having good qualification.The evil consequences like poverty, frustration, revolution
result in crimes and social disorganization. Therefore, it is
necessary that all efforts be made to have maximum.
employment facilities. The Government of India has already
announced that the question of payment of unemployment
allowance cannot be considered in India
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessMark Soia
Boost your chances of passing the 2V0-11.25 exam with CertsExpert reliable exam dumps. Prepare effectively and ace the VMware certification on your first try
Quality dumps. Trusted results. — Visit CertsExpert Now: https://www.certsexpert.com/2V0-11.25-pdf-questions.html
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
GDGLSPGCOER - Git and GitHub Workshop.pptxazeenhodekar
This presentation covers the fundamentals of Git and version control in a practical, beginner-friendly way. Learn key commands, the Git data model, commit workflows, and how to collaborate effectively using Git — all explained with visuals, examples, and relatable humor.
The *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responThe *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responses*: Insects can exhibit complex behaviors, such as mating, foraging, and social interactions.
Characteristics
1. *Decentralized*: Insect nervous systems have some autonomy in different body parts.
2. *Specialized*: Different parts of the nervous system are specialized for specific functions.
3. *Efficient*: Insect nervous systems are highly efficient, allowing for rapid processing and response to stimuli.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive in diverse environments.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive
1. 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.
2. 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]
3. • Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
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 ):
"This prints a passed string function"
print str
return
4. Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print str;
return;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
• This would produce following result:
I'm first call to user defined function!
Again second call to the same function
5. Pass by reference vs value
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:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
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]]
6. 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]
7. Function Arguments:
A function by using the following types of formal arguments::
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Required arguments:
• Required arguments are the arguments passed to a function in correct
positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
8. 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 printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
9. 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;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
10. 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
11. 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,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
12. • 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( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
13. 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
14. 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
15. 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.
16. • Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can 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
17. Type Conversions
• When you put an
integer and
floating point in
an expression the
integer is
implicitly
converted to a
float
• You can control
this with the built
in functions int()
and float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
18. String
Conversions
• You can also
use int() and
float() to
convert between
strings and
integers
• You will get an
error if the
string does not
contain numeric
characters
>>> sval = '123'
>>> type(sval)
<type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
19. Building our Own Functions
• We create a new function using the def
keyword followed by optional parameters
in parenthesis.
• We indent the body of the function
• This defines the function but does not
execute the body of the function
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
20. x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
x = x + 2
print x
Hello
Yo
7
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all
day.'
print_lyrics():
21. Definitions and Uses
• Once we have defined a function, we can
call (or invoke) it as many times as we like
• This is the store and reuse pattern
22. x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics()
x = x + 2
print x
Hello
Yo
I'm a lumberjack, and I'm okay.I
sleep all night and I work all day.
7
23. 1. Write a Python function to find the Max of three
numbers.
2.Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
3.Write a Python function to reverse a string.
4.Write a Python function that takes a list and returns a
new list with unique elements of the first list.
24. 1)def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest
# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))
26. 3)def reverse(string):
string = string[::-1] #Using
Slicing
return string
s = "IloveIndia"
print ("The original string is :
",end="")
print (s)
print ("The reversed string(using
extended slice syntax) is : ",end="")
print (reverse(s))
27. 4)def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,3,3,3,3,4,5]))
30. • To display a list of all available modules, use the following command in
the Python console
>>> help(‘modules’)
31. OS MODULE
• mkdir( ) - A new directory corresponding to the path in the string argument of
the function will be created.
• getcwd( ) - current working directory
• rmdir( ) - removes the specified directory either with an absolute or relative
path. However, we can not remove the current working directory. Also, for a
directory to be removed, it should be empty.
• listdir( ) - returns the list of all files and directories in the specified directory.
If we don't specify any directory, then list of files and directories in the
current working directory will be returned.
32. SYS MODULE
• sys.argv - returns a list of command line arguments passed to a Python script.
The item at index 0 in this list is always the name of the script. The rest of the
arguments are stored at the subsequent indices.
• sys.maxsize - Returns the largest integer a variable can take.
• sys.path - This is an environment variable that is a search path for all Python
modules.
• sys.version - This attribute displays a string containing the version number of the
current Python interpreter.
33. PYTHON MODULES
Python has a way to put definitions in a file and use them in
a script or in an interactive instance of the interpreter. Such a
file is called a module; definitions from a module can
be imported into other modules or into the main module (the
collection of variables that you have access to in a script
executed at the top level and in calculator mode).
34. A module is a file containing Python
definitions and statements.
The file name is the module name
with the suffix .py appended.
Within a module, the module’s name
(as a string) is available as
the value of the global variable __name__.
For instance, use your favorite text editor to
create a file called fibo.py in the
current directory with the following contents:
36. Modules can import other modules.
It is customary but not required to
place all import statements at the
beginning of a module (or script, for that matter).
The imported module names are placed in the
importing module’s global symbol table.
43. # Python program to
# demonstrate date class
# import the date class
from datetime import date
# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
# Uncommenting my_date = date(1996, 12, 39)
# will raise an ValueError as it is
# outside range
# uncommenting my_date = date('1996', 12, 11)
# will raise a TypeError as a string is
# passed instead of integer
44. Current date
To return the current local date today() function of date class is used.
today() function comes with several attributes (year, month and day). These
can be printed individually.
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
# Printing date's components
print("Date components", today.year, today.month, today.day)
46. Time class
Time object represents local time, independent of any
day.
Constructor Syntax:
class datetime.time(hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, *, fold=0)
All the arguments are optional. tzinfo can be None otherwise all the attributes
must be integer in the following range –
•0 <= hour < 24
•0 <= minute < 60
•0 <= second < 60
•0 <= microsecond < 1000000
•fold in [0, 1]
47. # Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute = 12)
print("nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("nTime without argument", my_time)
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int
48. from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
50. # Python program to
# demonstrate datetime object
from datetime import datetime
# Initializing constructor
a = datetime(1999, 12, 12)
print(a)
# Initializing constructor
# with time parameters as well
a = datetime(1999, 12, 12, 12, 12, 12, 342380)
print(a)
53. # Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + timedelta(days = 730)
future_date_after_2days = ini_time_for_now + timedelta(days = 2)
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
54. # Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now +
timedelta(days = 2)
# printing new final_date
print ("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time -
ini_time_for_now))
57. Python
• Exceptions Exception Handling Try and
Except Nested try Block
• Handling Multiple Exceptions in single
Except Block Raising Exception
• Finally Block
• User Defined Exceptions
58. Exception
⚫ When writing a program, we, more often than
not, will encounter errors.
⚫ Error caused by not following the proper
structure (syntax) of the language is called
syntax error or parsing error
⚫ Errors can also occur at runtime and these are
called exceptions.
⚫ They occur, for example, when a file we try to
open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError)
⚫ Whenever these type of runtime error occur,
Python creates an exception object. If not
handled properly, it prints a traceback to that
error along with some details about why that
error occurred.
60. Exception Handling
⚫To handle exceptions, and to call code
when an exception occurs, we can use
a try/except statement.
⚫The try block contains code that might
throw an exception.
⚫If that exception occurs, the code in
the try block stops being executed,
and the code in the except block is
executed.
⚫If no error occurs, the code in the
except
block doesn't execute.
73. finally
⚫To ensure some code runs no
matter what errors occur, you can
use a finally statement.
⚫The finally statement is placed at
the bottom of a try/except
statement.
⚫Code within a finally statement
always runs after execution of the
code in the try, and possibly in the
except, blocks.
76. ⚫Code in a finally statement even
runs if an uncaught exception
occurs in one of the preceding
blocks.