Python Functions Explained - Defining, Types, and Returns

functions in python n.w
1 / 17
Embed
Share

Learn about defining functions in Python, understanding dynamic and strong typing, functions as a type, functions without returns, and more. Dive into the world of Python functions and enhance your coding skills.

  • Python Functions
  • Defining
  • Types
  • Returns
  • Dynamic Typing

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Functions in Python By Dr. Ziad Al-Sharif

  2. Defining Functions Defining Functions Function definition begins with def. Function name and its arguments. def get_final_answer(filename): Documentation String line1 line2 return total_counter Colon. The indentation matters First line with less indentation is considered to be outside of the function definition. The keyword return indicates the value to be sent back to the caller. No header file or declaration of types of function or arguments

  3. Python and Types Python and Types Dynamic typing: Python determines the data types of variable bindings in a program automatically (at runtime) Strong typing: But Python s not casual about types, it enforces the types of objects For example, you can t just append an integer to a string, but must first convert it to a string >>> x = the answer is # x bound to a string >>> y = 23 # y bound to an integer. >>> print(x + y) # Python will complain!

  4. Functions as A type Functions as A type A function is a block of code which only runs when it is called. >>> def myfun(x, y): return x * y >>> myfun(3, 4) 12 >>> f = myfun >>> type(f) <class 'function'> >>> f(3,4) 12 >>> You can pass data, known as parameters, into a function. A function can return data as a result. Calling a Function To call a function, use the function name followed by parenthesis Arguments Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

  5. Functions without returns Functions without returns All functions in Python have a return value, even if no return line inside the code Functions without a return returns the special value None None is a special constant in python None is used like NULL, void, or nil in other languages None is also logically equivalent to False Functions can return multiple values: >>> def myfun(x, y): r1 = x * y r2 = x + y return r1 , r2 >>> myfun(3, 4) (12, 7) Returns a tuple

  6. Function overloading? Function overloading? No No There is no function overloading in Python Unlike C++ and Java, a Python function is specified by its name alone The number, order, names, or types of arguments cannot be used to distinguish between two functions with the same name Different functions can t have the same name, even if they have different arguments But: we will see operator overloading in classes and the OOP programming , we will explore this later

  7. Default Values for Arguments Default Values for Arguments You can provide default values for a function s arguments These arguments are optional when the function is called >>>defmyfun(b, c=3, d= hello ): return b + c >>> myfun(5,3, hi ) 8 >>> myfun(5,3) 8 >>> myfun(5) 8 >>> myfun(b=5) 8 >>> myfun(c=3,b=5) 8 >>> All of the function calls return 8

  8. Keyword Arguments Keyword Arguments Can call a function with some/all of its arguments out of order as long as you specify their names >>>deffoo(x,y,z): return(2*x,4*y,8*z) >>>foo(2,3,4) (4, 12, 32) >>>foo(z=4, y=2, x=3) (6, 8, 32) >>>foo(-2, z=-4, y=-3) (-4, -12, -32) Can be combined with defaults, too >>>deffoo(x=1,y=2,z=3): return(2*x,4*y,8*z) >>>foo() (2, 8, 24) >>>foo(z=100) (2, 8, 800)

  9. Keyword Arguments Keyword Arguments When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) >>>deff(*a): print(type(a)) >>>f() <class 'tuple'> >>> >>>deff(*a): for i in a: >>>f(1,2,3,4) 1,2,3,4, >>> print(i,end= , )

  10. Keyword Arguments Keyword Arguments >>>deff(**a): print(type(a)) for i in a: >>>f() <class 'dict'> >>> f(a=1,b=2,c=3) <class 'dict'> Abc >>> print(i, end='')

  11. Lambda Lambda Notation Notation Small anonymous functions can be created with the Small anonymous functions can be created with the lambda keyword. lambda keyword.

  12. Lambda Notation Lambda Notation You can write your very own Python functions using the def keyword, function headers, docstrings, and function bodies. However, there is a quicker way to write functions on the fly, and these are called lambda functions because you use the keyword lambda. Python s lambda creates anonymous functions >>> lambda x: x + 1 <function <lambda> at 0x1004e6ed8> >>> f = lambda x: x + 1 >>> f <function <lambda> at 0x1004e6f50> >>> f(100) 101

  13. Lambda Notation Lambda Notation Python s lambda creates anonymous functions Note: only one expression in the lambda body; its value is always returned >>>square = lambdaz: z * z >>>cube = lambdaz: z * z * z >>>defplus10(z): return z + 10 >>>defapplier(q, x): return q(x) >>> >>>applier(square, 2) 4 >>>applier(cube, 2) 8 >>>applier(plus10, 2) 12 >>>

  14. Lambda Notation Lambda Notation Be careful with the syntax >>> f = lambda x , y : 2 * x + y >>> f <function <lambda> at 0x87d30> >>> f(3, 4) 10 >>> v = (lambda x: x*x)(100) >>> v 10000 >>> f(y=4, x=3) 10 >>> f = lambda x , y=10 : 2 * x + y >>> f(2) 14 >>> lambda_function = lambda x: x*2 if x < 3 else x

  15. Example: Example: Composition Composition Function composition is combining two or more functions in such a way that the output of one function becomes the input of the second. E.g. if F and G are functions, then a composition can be represented as F(G(x)) where x is the argument of G and output of G(x) is the input of F >>>defsquare(x): return x*x >>>deftwice(f): returnlambda x: f(f(x)) >>>twice <function twice at 0x87db0> >>>quad = twice(square) >>>quad <function <lambda> at 0x87d30> >>>quad(5) 625

  16. Example: Example: Closure Closure A Closure is a function object that remembers values in its enclosing scopes even if they are not present in memory. In other words, a closure is a nested function which has access to a variable from an enclosing function that has finished its execution. Three characteristics of a Python closure are: it is a nested function it has access to a free variable in outer scope it is returned from the enclosing function >>>defcounter(start=0, step=1): x = [start] definc(): x[0] += step return x[0] returninc >>> c1 = counter() >>> c2 = counter(100, -10) >>> c1() 1 >>> c1() 2 >>> c1() 3 >>> c2() 90 >>> c2() 80 >>>

  17. References References Lambda Expressions https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions How to Use Python Lambda Functions https://realpython.com/python-lambda/ Lambdas https://docs.python.org/3/reference/expressions.html#lambda AWS Lambda function handler in Python https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html Anonymous function https://en.wikipedia.org/wiki/Anonymous_function

More Related Content