Python - Functions.

Slides:



Advertisements
Similar presentations
PHP Functions / Modularity
Advertisements

Functions. A set of statements (lines of code) that can be run repeatedly Goals: Learning Python by Lutz and Ascher –Code reuse –Procedural decomposition.
Structured programming
Functions. A set of statements (lines of code) that can be run repeatedly Goals: Learning Python by Lutz and Ascher –Code reuse –Procedural decomposition.
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
Variables, Expressions, and Statements
Python.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
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.
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
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Functions Chapter 4 Python for Informatics: Exploring Information
Variables, Expressions, and Statements
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Variables, Expressions and Statements
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
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Python Let’s get started!.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
PHP Functions / Modularity Dr. Charles Severance
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
PHP Functions Chapter 5 Dr. Charles Severance To be used in association with the book: PHP, MySql, and JavaScript by Robin Nixon.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Variables, Expressions, and Statements Chapter 2 Python for Everybody
PHP Functions / Modularity
Python Let’s get started!.
Introduction to Python
COMP 170 – Introduction to Object Oriented Programming
Computer Programming Fundamentals
Functions Chapter 4 Python for Everybody
Presented By S.Yamuna AP/IT
Chapter 4 Computing With Strings
Functions CIS 40 – Introduction to Programming in Python
Functions.
Variables, Expressions, and Statements
Imperative Programming
Python - Conditional Execution
Functions, Procedures, and Abstraction
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Conditional Execution
Python - Strings.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Variables, Expressions, and Statements
Python for Informatics: Exploring Information
Variables, Expressions, and Statements
Introduction to Value-Returning Functions: Generating Random Numbers
G. Pullaiah College of Engineering and Technology
15-110: Principles of Computing
Python Basics with Jupyter Notebook
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
By Ryan Christen Errors and Exceptions.
Introduction to Computer Science
General Computer Science for Engineers CISC 106 Lecture 03
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
CISC101 Reminders Assignment 3 due today.
Functions, Procedures, and Abstraction
CMPT 120 Lecture 4 – Unit 1 – Chatbots
Imperative Programming
Presentation transcript:

Python - Functions

Stored (and reused) Steps def hello(): Program: print 'Hello' print 'Fun' Output: def hello(): print 'Hello’ print 'Fun’ Hello Fun Zip Hello Fun hello() hello() print 'Zip’ hello() print “Zip” hello() These reusable pieces of code are called “functions”.

Python Functions -- There are two kinds of functions in Python -- Built-in functions, which are provided by Python - raw_input(), type(), float(), int() ... -- Functions, which are user-defined -- Built-in function names treated as “new” reserved words

Function Definition -- In Python, a function is reusable code, which takes arguments(s) as input does some computation and then returns a result(s) -- Define a function using the def reserved word -- Call/invoke the function by using the function name, parenthesis and arguments in an expression

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

Max Function max() function A function is reusable code, which takes some input and produces an output >>> big = max('Hello world') >>> print big 'w' max() function ‘w’ (a string) “Hello world” (a string)

Max Function A function is reusable code, which takes some input and produces an output >>> big = max('Hello world') >>> print big 'w' def max(inp): blah blah for x in y: blah blah ‘w’ (a string) “Hello world” (a string)

Type Conversions >>> print float(99) / 100 0.99 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4 - 5 -2.5 >>> -- In 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()

String Conversions >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <type 'int'> >>> print ival + 1 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() -- Use int() and float() to convert between strings and integers -- An error will occur if the string does not contain numeric characters

Building our Own Functions -- To create a new function, the def keyword is used followed by optional parameters in parenthesis -- 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 student at ECSU, 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 student at ECSU, and I'm okay." print 'I sleep all night, and I work all day.' print_lyrics(): x = 5 print 'Hello' def print_lyrics(): print "I'm a student at ECSU, and I'm okay.” print 'I sleep all night, and I work all day.' Hello Yo 7 print 'Yo' x = x + 2 print x

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

x = 5 print 'Hello' def print_lyrics(): print "I'm a student at ECSU, 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 student at ECSU, and I'm okay. I sleep all night and I work all day. 7

Arguments big = max('Hello world') -- An argument is a value passed to the function as its input when the function is called -- Arguments direct the function to do different kinds of work when called different times -- Arguments are placed in parenthesis after the name of the function big = max('Hello world') Argument

Parameters >>> 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 >>> ... -- A parameter is a variable, which is used in the function definition as a “handle” to allow the function to access the arguments for a particular function invocation

Return Values -- Often a function will take arguments, do some computation and return a value to be used by the that function called it; this is supported by the return keyword def greet(): return "Hello” Hello Glenn Hello Sally print greet(), "Glenn” print greet(), "Sally"

>>> def greet(lang): Return Value 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 >>> ... -- 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

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

Multiple Parameters / Arguments -- More than one parameter in the function definition can be defined def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print x -- To do this, simply add more arguments when the function is called -- The number and order of arguments and parameters are matched

Void (non-fruitful) Functions -- If a function does not return a value, it is called a "void" function -- Functions, which return values are called "fruitful" functions -- Void functions are "not fruitful"

To function or not to function... Organize your code into “paragraphs” - capture a complete thought and “name it” Don’t 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...

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: 5.15 Pay: 281.00 281.00= 40 * 5.15 + 5 * 15