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,

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Lists Introduction to Computing Science and Programming I.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Intro to Robots Robots are Everywhere. Intro to Robots Various robots in use today lawnmower pet baby seal for convalescents gutter cleaner home security.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Lesson Three: Organization
CHAPTER 6 Functions. Function Overview We’ve used built-in functions:  Examples:  print(“ABC”, x+10, sep=“:”)  round(x * 5, 2)  pygame.draw.circle(screen,
Introduction to Python
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
If statements while loop for loop
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
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,
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Python Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Python Let’s get started!.
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,
Week 8 - Friday.  What did we talk about last time?  Static methods.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
APS105 Functions (and Pointers) 1. Modularity –Break a program into manageable parts (modules) –Modules interoperate with each other Benefits of modularity:
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
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.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
Functions. 2 Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are:
User-Written Functions
PYGAME.
Lecture 2 Python Basics.
CS-104 Final Exam Review Victor Norman.
Case Statements and Functions
Topic: Functions – Part 2
Variables, Expressions, and IO
Week 8 - Friday CS 121.
Functions CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
Writing Functions.
5. Functions Rocky K. C. Chang 30 October 2018
G. Pullaiah College of Engineering and Technology
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
CS1201: Programming Language 2
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

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, (255,0,0), (400,300), 10, 0) – Behind the scenes: many lines of python/C++ Now we’ll look at writing our own – A way to group lines of related code. – Examples: A function to draw the main character A function to calculate the distance between 2 points A function to draw a game menu.

Why use functions? Readability (to you and others) Problem Decomposition – Team-based projects Code re-use (removing redundancy) – Make your own library (module) Abstraction Encapsulation

Fucntion Definition syntax def newFuncNoParams(): """ A 'docstring' explaining the func""" # Put the body (1-n lines) here def newFuncWithParams(param1, param2, …): """ A 'docstring' explaining the func""" # Put the body (1-n lines) here # NOTE: the … above just means more params # It's not valid python syntax

Example [A function to print a random string]

Parameters A way to tell a function how to do its job. – Makes it useful in more situations. Example: def f(a, b): """ Adds two numbers and prints""" print(a + b) x = 9 f(4, x) Parameters vs. Arguments Arguments: Values copied to parameters when a function is called – Can be constants, variables (the value is copied), expressions, another function call, etc. Parameters: Variables used in the function – Created when the function starts; destroyed when it ends.

Parameters, cont. Python evaluates this in these steps: 1.Line1. A new function def. Stores the name (f) and the number of params. 2.Line2. Associates the docstring with f. 3.Line3. Adds this line to the body of f. 4.Line4 (main program). Create a variable x. 5.Line5 (main program). Call f a.create a temporary variable, a. Copy the value 4 to it. b.create a temporary variable, b. Copy the value of x (9) to it. c.execute the body of f, using a and b. d.destroy the variables a and b. 6.Continue with any code after Line 5. def f(a, b): """ docstring. """ print(a + b) x = 9 f(4, x)

Example [A function to draw an ASCII box] + add Params

Default and keyword parameters Default params def func2(a, b, c=9): print(a + b + c) func(1,2,3) # Prints 6 func(1,2) # Prints 12 – All default params must come after non-defaults Positional vs. Keyword arguments def func2(a, b, c=2, d=3): print((a + b + c) * d) func2(1,2,3,4) # Prints 24. Using positional arguments func2(1,2,c=4,d=3) # Prints 21. Using keyword args for c & d. – Keyword params allow you to pass args in any order.

Return values A way to return a value from a function – Makes the function more usable. Return values we've already seen. x = int(f) pygame.draw.circle(screen,(0,0,0),(int(x),int(y)), 5, 0) – The int function returns a integer version of f. – This can be used as part of a larger expression.

Return Values, cont. Example: def adder(a, b): return a + b x = adder(5, 7) # x holds 12 print(adder("AB", "XY")) # prints 'ABXY' If you don't include a return statement, python silently returns the value None. – e.g. myCircle = pygame.draw.circle(…) print(myCircle) # prints None

Return values, cont. Three types of return statements: return returns None return expression Evaluates the expression and returns it. Can be any python object – int, float, list, tuple, pygame surface, etc. return expression1, expression2 Makes a tuple containing expression1 and expression2 You can pack as many expressions as you like.

Return values, cont. A return statement immediately ends a function call and returns to the caller def func(): print("You'll see me…") return print("…but you won't ever see me.") Often used to "back out" of a function (often in error cases) def divide(a, b): if b == 0: # Division would cause an error return 0.0 # Later, raise an exception return a / b # We won't get here if b is 0.

Example [Menu drawing code] – pygame? [Circular hit-detection]

Mutable objects as parameters Recall: we've seen these mutable objects… – Lists – Dictionaries – Objects (e.g. pygame surfaces) Recall with lists… L = [1, 2, 3] G = L # G and L refer to the same mem. loc. G[1] = 99 print(L) # prints [1, 99, 3] This is important when you pass a mutable object as an argument.

Mutable objects as parameters Example: def func(a): for i in range(len(a)): if i % 2 == 0: a[i] = -a[i] L = [1,2,3,4,5,6] func(L) print(L) # Prints [-1,2,-3,4,-5,6]

Scope and global variables Scope is a set of statements in which a name (usually of a variable) is valid. Python has two types of scope: – File (global) scope: your entire script Any variable defined outside of a function is global. – Function (local, temporary) scope: the set of statements in a function. Any variable defined inside a function has this scope. This variable us un-defined after the function ends. A local can have the same name as a global – it normally masks the global variable.

Scope and global variables def foo(a, b): # a and b are local variables c = 9 # This creates another. print(a + b + c) x = 99 # This is a global variable #print(c)# Error! c only exists in foo. a = 5 # This is a global a. It is *totally* separate from # the local a above. foo(x, a) # Note, the value of a (5) is copied to the local b.

Scope and global variables. Using global variables in a function – First rule: DON'T DO IT! Hurts readability, creates "spaghetti code", breaks encapsulation – Second rule: if you must do it, know how to use them. def printGold(): print("You have $" + str(gold)) # OK. Uses the global gold = 100 # Global variable printGold() # Prints $100 loseGold() printGold() # Still $100 loseGold2() printGold() # Now it's 0. def addGold(amt): gold += amt # Error – gold doesn't exist here. def loseGold(): gold = 0 # Works, but creates a new LOCAL; # doesn't change global gold. def loseGold2(): global gold gold = 0 # Works as expected now.

Example of a bad use of globals def drawFace(): global x, y pygame.draw.circle(screen, (255,0,0), (x,y), 20, 0) # Other drawing code pygame.event.pump() pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: x -= 1 # Other input commands Problems: Style / Readability: The name "drawFace" indicates this is for drawing. Updating breaks the abstraction. We have to search the entire program for places x/y are used, modified. Events: This "eats" all events. We may be trying to capture mouse events somewhere else, but we won't get them. Reusability: We can't use this for a second player (drawn in blue). We'd have to copy/paste this code, with only a few modifications.

Example of bad global usage, fixed. def drawFace(surf, x, y, color): pygame.draw.circle(surf, color, (x,y), 20, 0) # Other drawing commands player1X = 100; player1Y = 100 player2X = 700; player2Y = 500 # Inside game loop pygame.event.pump() pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: player1X -= 1 # Other player 1 keys if pressed[pygame.K_w]: player2X -= 1 # Other player 2 keys # Drawing code drawFace(screen, player1X, player1Y, (255,0,0)) drawFace(screen, player2X, player2Y, (0,0,255))

Making your own modules Make a new file, my_module.py – Define a function f (2 integer args) Make a new file, tester.py import my_module # Notice missing.py x = my_module.f(5, 7) Useful for making libraries of re-usable code.

Examples [UFO] – Function: draw a ufo, with animated lights. – Function: Draw a gradient sky background – Function: Create a list of humans – Function: Draw all humans – Function: Update the ufo, fire bullets – Function: distance – Function: Update the list of humans