Python Functions.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Example 2.
Introduction to Python
Understanding the Mainline Logical Flow Through a Program (continued)
Introduction to C Programming
Basic Elements of C++ Chapter 2.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Munster Programming Training
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
COMPSCI 101 Principles of Programming Lecture 28 – Docstrings & Doctests.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 5 Function Interfaces 4/18/09 Python Mini-Course: Day 2 - Lesson 5 1.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Built-in Data Structures in Python An Introduction.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Functions Chapter 6. Function Overview We’ve used built-in functions: – Examples: print(“ABC”, x+10, sep=“:”) round(x * 5, 2) pygame.draw.circle(screen,
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
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.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
The Functions and Purposes of Translators Syntax (& Semantic) Analysis.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
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.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
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,
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
CS0004: Introduction to Programming
C++ First Steps.
Chapter 9: Value-Returning Functions
Chapter Topics The Basics of a C++ Program Data Types
Topics Introduction to Functions Defining and Calling a Void Function
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Lecture 2 Python Basics.
Introduction to Python
Suppose we want to print out the word MISSISSIPPI in big letters.
Basic Elements of C++.
Topic: Functions – Part 2
Functions CIS 40 – Introduction to Programming in Python
Functions.
Basic Elements of C++ Chapter 2.
CHAPTER FOUR Functions.
Higher-Order Procedures
User Defined Functions
Variables ICS2O.
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
CISC101 Reminders All assignments are now posted.
COMPUTER PROGRAMMING SKILLS
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
Functions John R. Woodward.
© Sangeeta M Chauhan, Gwalior
Presentation transcript:

Python Functions

Defining a Function You can define functions to provide the required functionality. 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.

Example Defining a function Syntax def functionname( parameters ): "function_docstring" function_suite return [expression]

Doc Strings Python has a feature called documentation strings, usually referred as docstrings. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. Docstrings provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It's specified in source code that is used, like a comment, to document a specific segment of code. This allows the program to inspect these comments at run time, for instance as an interactive help system, or as metadata The doc string line should begin with a capital letter and end with a period. The first line should be a short description. def my_function(): """Do nothing, but document it. No, really, it doesn't do anything. """ pass >>> print my_function.__doc__ Do nothing, but document it. No, really, it doesn't do anything.

Example

Function parameters

Local & global variables Using of local variables Using of global variable ‘global’ key word is used to declare global variable

Function arguments Types of formal arguments are Default arguments Keyword arguments Required arguments Variable-length arguments Keyword –only Parameters

default argument values For some functions, you may want to make some parameters as optional and use default values if the user does not want to provide values for such parameters. This is done with the help of default argument values. Note that the default argument value should be immutable. you cannot use mutable objects such as lists for default argument values. Note : Only those parameters which are at the end of the parameter list can be given as default argument values. For Eg. def fun (a,b=5)valid def fun (a=1,b)  Invalid

keyword arguments If you have some functions with many parameters and you want to specify only some parameters, then you can give values for such parameters by naming them this is called keyword arguments. We use the name instead of the position which we have been using all along. This has two advantages - One, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.

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 would give a syntax error

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 syntax is 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.

Example for variable length arguments Note : When we declare a starred parameter such as *param, then all the positional arguments from that point till the end are collected as a list called 'param'. When we declare a double-starred parameter such as **param, then all the keyword arguments from that point till the end are collected as a dictionary called 'param'.

Keyword-only Parameters If we want to specify certain keyword parameters to be available as keyword-only and not as positional arguments, they can be declared after a starred parameter

return statement The return statement is used to return from a function i.e. break out of the function. We can optionally return a value from the function as well. Every function implicitly contains a return None statement. You can see this by running print someFunction() where the function someFunction does not use the return statement

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.

Function example There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.

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.

Exercises Define a function max_of_three() that takes three numbers as arguments and returns the largest of them using default arguments Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24 using VarArgs. Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long. For example, generate_n_chars(5,"x") should return the string "xxxxx“ using keyword only parameters.

Exercises Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example,histogram ([4, 9, 7]) should print the following: **** ********* ******* Write python function for binary search