Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions.

Slides:



Advertisements
Similar presentations
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Advertisements

JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Python Control of Flow.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Functions & Objects IDIA 618 Spring 2012 Bridget M. Blodgett.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Lists in Python.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?
NA2204.1jcmt CSE 1320 Intermediate Programming C Program Basics Structure of a program and a function type name (parameters) { /* declarations */ statement;
Built-in Data Structures in Python An Introduction.
Python Tricks CMSC 201. Overview Today we are learning some new tricks to make our lives easier! Slicing and other tricks Multiple return values Global.
PHP Constructs Advance Database Management Systems Lab no.3.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?
Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.
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,
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
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.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Introduction to Decision Structures and Boolean Variables
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Lecture 2 Python Basics.
CS 1110 Introduction to Programming Spring 2017
CHAPTER 5 SERVER SIDE SCRIPTING
CSC 108H: Introduction to Computer Programming
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Functions CIS 40 – Introduction to Programming in Python
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
CHAPTER FOUR Functions.
Introduction to Functions
Functions BIS1523 – Lecture 17.
CISC101 Reminders Slides have changed from those posted last night…
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
Coding Concepts (Sub- Programs)
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Passing Parameters by value
Programming for Geographical Information Analysis: Core Skills
Coding Concepts (Basics)
CS 1111 Introduction to Programming Fall 2018
Topics Sequences Introduction to Lists List Slicing
Introduction to Decision Structures and Boolean Variables
5. Functions Rocky K. C. Chang 30 October 2018
Topics Introduction to Functions Defining and Calling a Void Function
References.
G. Pullaiah College of Engineering and Technology
CISC101 Reminders All assignments are now posted.
Peter Seibel Practical Common Lisp Peter Seibel
Topics Sequences Introduction to Lists List Slicing
Python Review
Scope Scope is the space within which a variable label exists and can be used. Python talks of names being bound to the code in an area and that determining.
CISC101 Reminders Assignment 3 due today.
Control Flow statements
ITM 352 Functions.
Enclosing delimiters Python uses three style of special enclosing delimiters. These are what the Python documentation calls them: {} braces # Sometimes.
 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.
Presentation transcript:

Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions in other modules using import. import random a = random.random() We'll now look at building our own functions.

Basic function Functions are a block begun with a function declaration or header: def function_name (): # Suite of statements # Code calling function_name In a standard script, functions need to be defined before you use them.

Example def printit(): print("hello world") printit() # The function can be called printit() # as many times as you like. printit()

Passing info in Functions can be parameterised; that is, made flexible through variables which are set up when the function is called. Note that the arguments sent in are allocated to the parameter variables. def printit(text): print(text) printit("hello world") a = "hi you" printit(a)

Variable labels What is happening here is we're attaching two labels to the same variable: def printit(text): print(text) a = "hi you" printit(a) The effect this has depends whether the variable is mutable or immutable. "hi you" a text This is known as "pass by assignment", though sometimes people also use "pass by reference" for this (though there are also subtly different uses for that - for example, the reference to the variable is copied). The third type of passing is "pass by value", where the value is copied and passed. Python uses assignment.

Variable labels For mutable variables, changes inside the function change the variable outside: def printit(text): text[0] = text[0] + ", Pikachu" print(text[0]) a = ["hi you"] printit(a) # Call the function. print(a) # Check the value of a. As lists are mutable, the value in the list outside the method has changed to "hi you, Pikachu".

Variable labels For immutable variables, changes inside the function just create a new variable inside the function. Even though it has the same name, it isn't the same variable: def printit(text): text = text + ", Pikachu" # New text variable created. print(text) a = "hi you" printit(a) # Call the function. print(a) # Check the value of a. As text is immutable, the value in the list outside the method is still "hi you".

Passing info in Python (unlike many languages) doesn't worry about the type passed in def printit(var): print(str(var)) printit("hello world") printit(430) printit(430.0)

Getting values back By default, functions invisibly return None (you can do so explicitly, as is sometimes useful). But you can pass values back: def get_pi(): return 3.14 pi = get_pi() print(str(pi)) print(str(get_pi())) If something comes back, you either need to attach a label to it, or use it. You can find out the type of a returned object with type(variable_name). If you need to return more than one thing, return a tuple. For more detail on other ways to get stuff from functions, see: https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference

Multiple in (single out) def add(num1, num2): return num1 + num2 answer = add(20,30) Arguments are allocated to parameters like this just on position. These are called positional arguments.

Defaults You can set up default values if a parameter is missing: def add(num1 = 0, num2 = 0): return num1 + num2 answer = add(3) With this type of parameter, positional arguments are allocated left to right, so here, num1 is 3, and num2 is nothing.

Ordering In the absence of a default, an argument must be passed in. If we did this: def add(num1=0, num2): return num1 + num2 answer = add(3) print(answer) It wouldn't be clear if we wanted num1 or num2 to be 3. Because of this, parameters with defaults must come after any undefaulted parameters. All parameters to the right of a defaulted parameter must have defaults (except * and ** - which we'll see shortly).

Keyword arguments You can also name arguments, these are called keyword arguments or kwargs. Note that this use of "keywords" has nothing to do with the generic use for words you can't use as identifiers. def add(num1, num2): return num1 + num2 answer = add(num2 = 30, num1 = 50) Here we've swapped the order of the positional arguments by naming the parameters to assign their values to. It's fairly unfortunate that the same term is used for both types of keyword.

Mixed arguments def add(num1, num2): return num1 + num2 answer = add(3, num2 = 5) Note that once Python has started to deal with kwargs, it won't go back and start allocating positional arguments, so all positional arguments have to be left of the kwargs. You can force parameters to the right to be kwargs by putting a * in the parameters Note also that you can't allocate to the same parameter twice: answer = add(3, num1 = 5)

Flexible parameterisation You can allow for more positional arguments than you have parameters using *tuple_name, thus: def sum (num1, num2, *others): sum = num1 sum += num2 for num in others: sum += num return sum answer = sum(1,2,3,4,5,6,7) *is known as the iterable un/packing operator. If nothing is allocated, the tuple is empty.

Iterable unpacking You can equally use the * operator with lists or tuples to generate parameters: def sum (num1, num2, num3, num4): return num1 + num2 + num3 + num4 a = [1,2,3,4] answer = sum(*a) # Note that these can also be in the middle. a = [10,20] answer = sum(1,*a, 2)

Iterable unpacking def sum(*nums): sum = 0 for num in nums: sum += num You can, therefore, use these in both positions: def sum(*nums): sum = 0 for num in nums: sum += num return sum a = [1,2,3] answer = sum(*a)

Flexible parameterisation The same can be done with **dict_name (** is the dictionary unpacking operator), which will make a dictionary from unallocated kwargs: def print_details (a, **details): first = details["first"] surname = details["surname"] print (first + " " + surname + " has " + a + " pounds") print_details("5", first="George", surname="Formby") Note that you can't use one of these to override other variables. If nothing is allocated, the dictionary is empty.

Unpacking dictionaries You can also use ** to create keyword arguments: def print_details(a, first, surname): print (first + " " + surname + " has " + a + " pounds") d = {"first":"George","surname":"Formby"} print_details("5",**d)

Unpacking quirks Note also that just as with standard arguments *tuple_name must come before **dict_name if you use both. *tuple_name must come after positional parameters and **dict_name after kwargs. It is, therefore usual to place them after their associated variables or together at the end. def func(a,b,*c,d,**e) # d has to be a kwarg. def func(a,b,d,*c,**e) # abd,bd,or d can be kwargs. But this is also how you force variables to be kwargs. Note that attempts to do this: def a(**d): print(d) a(d={1:2}) End up with a dictionary variable inside the dictionary, with the same name: {d:{1,2}}

Summary of order Parameters: Arguments: Undefaulted parameters *tuple_name Forced keyword parameters **dict_name Arguments: Positional arguments Keyword arguments Unpacked lists, tuples, or dicts may be anywhere For more on unpacking operators, see: https://www.python.org/dev/peps/pep-0448/

Nested functions Note that there is nothing to stop you having functions within functions: def a(): print("1") def b(): print("2") b() a() One restriction is that if your function is inside a loop, you can't break inside the function.