Functions Chapter 4 Python for Informatics: Exploring Information www.pythonlearn.com Slightly modified by Recep Kaya Göktaş on March 2015.

Slides:



Advertisements
Similar presentations
Python for Informatics: Exploring Information
Advertisements

Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
PHP Functions / Modularity
Structured programming
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.
Introduction to Python
Chapter 2 Writing Simple Programs
Variables, Expressions, and Statements
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Computing with Numbers Zelle - Chapter 3 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science, John.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Python – Part 3 Functions 1. Function Calls Function – A named sequence of statements that performs a computation – Name – Sequence of statements “call”
Python for Informatics: Exploring Information
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
CPS120: Introduction to Computer Science Functions.
Built-in Data Structures in Python An Introduction.
Functions Chapter 4 Python for Informatics: Exploring Information
Procedural programming in Java Methods, parameters and return values.
Variables, Expressions, and Statements
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Python Conditionals chapter 5
Python – Part 3 Functions 1. Getting help Start the Python interpreter and type help() to start the online help utility. Or you can type help(print) to.
PHP Functions Dr. Charles Severance
Decision Structures, String Comparison, Nested Structures
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
PHP Functions / Modularity Dr. Charles Severance
PHP Functions Chapter 5 Dr. Charles Severance To be used in association with the book: PHP, MySql, and JavaScript by Robin Nixon.
Python for Informatics: Exploring Information
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Variables, Expressions, and Statements Chapter 2 Python for Everybody
PHP Functions / Modularity
Introduction to Python
Computer Programming Fundamentals
Functions Chapter 4 Python for Everybody
Presented By S.Yamuna AP/IT
Python - Functions.
Functions CIS 40 – Introduction to Programming in Python
Variables, Expressions, and Statements
User-Defined Functions
Conditional Execution
Strings Chapter 6 Slightly modified by Recep Kaya Göktaş in April Python for Informatics: Exploring Information
Topics Introduction to File Input and Output
Functions, Procedures, and Abstraction
Conditional Execution
Python - Strings.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Conditional Execution
Python for Informatics: Exploring Information
Variables, Expressions, and Statements
Python for Informatics: Exploring Information
Variables, Expressions, and Statements
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
General Computer Science for Engineers CISC 106 Lecture 03
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Functions, Procedures, and Abstraction
Using Modules.
Introduction to Computer Science
Presentation transcript:

Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015

Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. Copyright Charles R. Severance

Stored (and reused) Steps Output: Hello Fun Zip Hello Fun Program: def thing(): print 'Hello’ print 'Fun’ thing() print 'Zip’ thing() def print 'Hello' print 'Hello' print 'Fun' thing() print “Zip” We call these reusable pieces of code “functions”. thing(): thing()

Python Functions There are two kinds of functions in Python. Built-in functions that are provided as part of Python - raw_input(), type(), float(), int()... Functions that we define ourselves and then use We treat the built-in function names as "new" reserved words (i.e. we avoid them as variable names)

Function Definition In Python a function is some reusable code that takes arguments(s) as input does some computation and then returns a result or results We define a function using the def reserved word We call/invoke the function by using the function name, parenthesis and arguments in an expression

>>> big = max('Hello world') >>> print big w >>> tiny = min('Hello world') >>> print tiny >>> big = max('Hello world') Argument 'w' Result Assignment

Max Function >>> big = max('Hello world') >>> print big w max()function “Hello world” (a string) ‘w’ (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code

Max Function >>> big = max('Hello world') >>> print big w def max(inp): blah blah for x in y: for x in y: blah blah “Hello world” (a string) ‘w’ (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code

Type Conversions When you put an integer and floating point in an expression the integer is implicitly converted to a float You can control this with the built in functions int() and float() >>> print float(99) / >>> i = 42 >>> type(i) >>> f = float(i) >>> print f 42.0 >>> type(f) >>> print * float(3) / >>>

String Conversions You can also use int() and float() to convert between strings and integers You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) >>> print sval + 1 Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) >>> print ival >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int()

len function Another very common built-in function is the len function which tells us how many items are in its argument. If the argument to len is a string, it returns the number of characters in the string.

Random numbers The random module in phyton provides functions that generate pseudorandom numbers. The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0).

Random numbers

Math functions

Building our Own Functions We create a new function using the def keyword followed by optional parameters in parenthesis. We indent the body of the function This defines the function but does not execute the body of the function def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.'

x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' x = x + 2 print x Hello Yo 7 print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' print_lyrics():

Definitions and Uses Once we have defined a function, we can call (or invoke) it as many times as we like This is the store and reuse pattern

x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' print_lyrics() x = x + 2 print x Hello Yo I'm a lumberjack, and I'm okay.I sleep all night and I work all day. 7

Arguments An argument is a value we pass into the function as its input when we call the function We use arguments so we can direct the function to do different kinds of work when we call it at different times We put the arguments in parenthesis after the name of the function big = max('Hello world') Argument

Parameters A parameter is a variable which we use in the function definition that is a “handle” that allows the code in the function to access the arguments for a particular function invocation. >>> def greet(lang):... if lang == 'es':... print 'Hola’... elif lang == 'fr':... print 'Bonjour’... else:... print 'Hello’... >>> greet('en') Hello >>> greet('es') Hola >>> greet('fr') Bonjour >>>

Return Values Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this. def greet(): return "Hello” print greet(), "Glenn” print greet(), "Sally" Hello Glenn Hello Sally

Return Value A “fruitful” function is one that produces a result (or return value) The return statement ends the function execution and “sends back” the result of the function >>> def greet(lang):... if lang == 'es':... return 'Hola’... elif lang == 'fr':... return 'Bonjour’... else:... return 'Hello’... >>> print greet('en'),'Glenn’ Hello Glenn >>> print greet('es'),'Sally’ Hola Sally >>> print greet('fr'),'Michael’ Bonjour Michael >>>

Return Values Sometimes it is useful to have multiple return statements, one in each branch of a conditional. But be careful not to write dead code!

Return Values What is wrong with this function?

Arguments, Parameters, and Results >>> big = max('Hello world') >>> print big w def max(inp): blah blah for x in y: for x in y: blah blah return ‘w’ return ‘w’ “Hello world” ‘w’‘w’ Argument Parameter Result

Multiple Parameters / Arguments We can define more than one parameter in the function definition We simply add more arguments when we call the function We match the number and order of arguments and parameters def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print x

Exercise

Definitions and Uses

Parameters and Arguments

Void (non-fruitful) Functions When a function does not return a value, we call it a "void" function Functions that return values are "fruitful" functions Void functions are "not fruitful"

Math functions are fruitful functions.

A Void Function

Incremental Development Adding and testing a small amount of code at a time. 1. Start with a working program and make small incremental changes. At any point, if there is an error, you should have a good idea where it is. 2. Use temporary variables to hold intermediate values so you can display and check them. 3. Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.

Exercise

Composition You can call one function from within another. circle_area is a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle:

Boolean Functions Functions can return booleans.

Exercise

A function can call itself! Too difficult to follow the flow of execution here! Use the “leap of faith”: If you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together.

Factorial factorial function that also checks the type of its argument: Exercise: Write this function with a try/except construct.

To function or not to function... Organize your code into “paragraphs” - capture a complete thought and “name it” Dont repeat yourself - make it work once and then reuse it If something gets too long or complex, break up logical chunks and put those chunks in functions Make a library of common stuff that you do over and over - perhaps share this with your friends...

Debugging If a function is not working, there are three possibilities to consider: There is something wrong with the arguments the function is getting. There is something wrong with the function. There is something wrong with the return value or the way it is being used.

Exercise Rewrite your pay computation with time-and-a- half for overtime and create a function called computepay which takes two parameters ( hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: = 40 * * 15

Summary Functions Built-In Functions Type conversion (int, float) Math functions (sin, sqrt) Arguments Parameters