Functions Chapter 4 Python for Everybody

Slides:



Advertisements
Similar presentations
Introduction to PHP Dr. Charles Severance
Advertisements

PHP Functions / Modularity
Structured programming
Introduction to Python
Variables, Expressions, and Statements
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.
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 Chapter 4 Python for Informatics: Exploring Information
Variables, Expressions, and Statements
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
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!.
PHP Functions / Modularity Dr. Charles Severance
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
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.
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.
Chapter 4 Computing With Strings Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle.
Variables, Expressions, and Statements Chapter 2 Python for Everybody
Reading Files Chapter 7 Python for Everybody
PHP Functions / Modularity
Strings Chapter 6 Python for Everybody
Conditional Execution
Python Let’s get started!.
Introduction to Python
Computer Programming Fundamentals
Regular Expressions Chapter 11 Python for Everybody
Loops and Iteration Chapter 5 Python for Everybody
HTTP Parameters and Arrays
Python Lists Chapter 8 Python for Everybody
PHP Arrays Dr. Charles Severance
Presented By S.Yamuna AP/IT
Chapter 4 Computing With Strings
Python - Functions.
Functions CIS 40 – Introduction to Programming in Python
Object Oriented Programming in JavaScript
Variables, Expressions, and Statements
Expressions and Control Flow in PHP
Tuples Chapter 10 Python for Everybody
Conditional Execution
Python - Conditional Execution
Topics Introduction to File Input and Output
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.
Conditional Execution
Variables, Expressions, and Statements
Python for Informatics: Exploring Information
Variables, Expressions, and Statements
G. Pullaiah College of Engineering and Technology
15-110: Principles of Computing
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
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.
More Basics of Python Common types of data we will work with
Functions, Procedures, and Abstraction
Presentation transcript:

Functions Chapter 4 Python for Everybody www.py4e.com Note from Chuck. If you are using these materials, you can remove the UM logo and replace it with your own, but please retain the CC-BY logo on the first page as well as retain the entire last page. Chapter 4 Python for Everybody www.py4e.com

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

Python Functions There are two kinds of functions in Python. - Built-in functions that are provided as part of Python - print(), 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, parentheses, and arguments in an expression

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

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

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

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

String Conversions >>> sval = '123' >>> type(sval) <class '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) <class 'int'> >>> print(ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int(nsv) ValueError: invalid literal for int() 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

Functions of Our Own…

Building our Own Functions We create a new function using the def keyword followed by optional parameters in parentheses 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.')

Hello Yo 7 print_lyrics(): 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_lyrics(): 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

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

I'm a lumberjack, and I'm okay. 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') 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 big = max('Hello world') 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 parentheses 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 we use in the function definition. It is a “handle” that allows the code in the function to access the arguments for a particular function invocation.

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 >>> 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 >>> 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 Parameter def max(inp): blah for x in inp: return 'w' 'Hello world' 'w' Argument 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) 8

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”

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 it up into 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...

Summary Functions Built-In Functions Type conversion (int, float) String conversions Parameters Arguments Results (fruitful functions) Void (non-fruitful) functions Why use functions?

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: 475.0 475 = 40 * 10 + 5 * 15

Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information … Insert new Contributors and Translators here ...