G. Pullaiah College of Engineering and Technology

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Introduction to C Programming
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 7: User-Defined Functions II
Example 2.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
COMP More About Classes Yi Hong May 22, 2015.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Functions Chapter 4 Python for Informatics: Exploring Information
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
CPS120: Introduction to Computer Science Lecture 14 Functions.
JavaScript III Functions and Abstraction. 2 JavaScript so far statements assignment function calls data types numeric string boolean expressions variables.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
PYTHON FUNCTIONS. What you should already know Example: f(x) = 2 * x f(3) = 6 f(3)  using f() 3 is the x input parameter 6 is the output of f(3)
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Information and Computer Sciences University of Hawaii, Manoa
Topics Introduction to Functions Defining and Calling a Void Function
Chapter 7: User-Defined Functions II
Introduction to Python
CS 1110 Introduction to Programming Spring 2017
PHP 5 Syntax.
Topic: Functions – Part 2
Python - Functions.
Functions CIS 40 – Introduction to Programming in Python
Functions.
User-Defined Functions
CHAPTER FOUR Functions.
PYTHON Varun Jain & Senior Software Engineer
And now for something completely different . . .
Functions, Procedures, and Abstraction
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Python Functions Part I Presented by : Sharmin Abdullah
Topics Introduction to Functions Defining and Calling a Function
Python Syntax Errors and Exceptions
CISC101 Reminders All assignments are now posted.
15-110: Principles of Computing
COMPUTER PROGRAMMING SKILLS
Classes, Objects and Methods
Introduction to Computer Science
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
CISC101 Reminders Assignment 3 due today.
Methods/Functions.
ITM 352 Functions.
def-ining a function A function as an execution control structure
Functions, Procedures, and Abstraction
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Functions John R. Woodward.
© Sangeeta M Chauhan, Gwalior
Presentation transcript:

G. Pullaiah College of Engineering and Technology Python Programming Department of Computer Science & Engineering

Unit -3

Defining Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing

Syntax def functionname( parameters ): "function_docstring" function_suite return [expression]

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.

Example def printme( str ): "This prints a passed string into this function" print str return printme(“hello”) Python34.py

Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.

def printme( str ): "This prints a passed string into this function" print str; return; printme("I'm first call to user defined function!"); printme("Again second call to the same function");

I'm first call to user defined function I'm first call to user defined function! Again second call to the same function

Passing Arguments Passingby Reference Versus Passing byValue 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

def changeme( mylist ): "This changes a passed list into this function" 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

Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

Ex: def powercalc(a,b): p=a**b return p print(powercalc(3,2))

Ex: def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist

Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]

Function Arguments You can call 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 Here, the number of arguments in the function call should match exactly with the function definition. To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows:

def printme( str ): "This prints a passed string into this function" print str; return; printme();

Traceback (most recent call last): File "test Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)

2. 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 into this function" print str; return; printme( str = "My string"); Output: My string

def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); Output: Name: miki Age 50

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.

def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); printinfo( name="miki" );

Name: miki Age 50 Age 35

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.

Syntax def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.

def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; printinfo( 10 ); printinfo( 70, 60, 50 );

Output is: 10 70 60 50

lambda [arg1 [,arg2,.....argn]]:expression Anonymous Functions These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. Syntax: lambda [arg1 [,arg2,.....argn]]:expression

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.

sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) Output: Value of total : 30 Value of total : 40

>>> a=lambda x,y,z:x+y+z >>> a(3,4,5) 12

Ex 1: >>> f = lambda x, y, z: x + y + z >>> f(2, 3, 4) 9

>>> z=lambda x,y:True if x>y else False if a: b else: C can be emulated by either of these roughly equivalent expressions: b if a else c >>> z=lambda x,y:True if x>y else False >>> z(3,4) False

Fruitful Functions(Function Returning Values) 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.

def sum( arg1, arg2 ): total = arg1 + arg2 print "Inside the function : ", total return total; total = sum( 10, 20 ); print "Outside the function : ", total

Inside the function : 30 Outside the function : 30

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.

total = 0; # This is global variable total = 0; # This is global variable. def sum( arg1, arg2 ): total = arg1 + arg2; # total is local variable. print "Inside the function local total : ", total return total; sum( 10, 20 ); print "Outside the function global total : ", total

Inside the function local total : 30 Outside the function global total : 0