Functions. A set of statements (lines of code) that can be run repeatedly Goals: Learning Python by Lutz and Ascher –Code reuse –Procedural decomposition.

Slides:



Advertisements
Similar presentations
Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
Advertisements

Variables and I/O. Types Strings –Enclosed in quotation marks –“Hello, World!” Integers –4, 3, 5, 65 Floats –4.5, 0.7 What about “56”?
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
Algorithms. Software Development Method 1.Specify the problem requirements 2.Analyze the problem 3.Design the algorithm to solve the problem 4.Implement.
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
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.
Algorithms. Software Development Method 1.Specify the problem requirements 2.Analyze the problem 3.Design the algorithm to solve the problem 4.Implement.
Variables and I/O. Types Strings –Enclosed in quotation marks –“Hello, World!” Integers –4, 3, 5, 65 Floats –4.5, 0.7 What about “56”?
Chapter 2 Writing Simple Programs
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Python Programming Fundamentals
Introduction to Python
Munster Programming Training
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Functions Chapter 4 Python for Informatics: Exploring Information
COMP 171: Data Types John Barr. Review - What is Computer Science? Problem Solving  Recognizing Patterns  If you can find a pattern in the way you solve.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Variables When programming it is often necessary to store a value for use later on in the program. A variable is a label given to a location in memory.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Functions : chapter 3
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.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Variables, Types, Expressions Intro2CS – week 1b 1.
Values, Types, and Variables. Values Data Information Numbers Text Pretty much anything.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
Input, Output and Variables GCSE Computer Science – Python.
CS0004: Introduction to Programming
Chapter 2 Writing Simple Programs
Topics Introduction to Functions Defining and Calling a Void Function
Introduction to Programming
Introduction to Python
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Python - Functions.
Functions CIS 40 – Introduction to Programming in Python
Lesson 06: Functions Class Chat: Attendance: Participation
Introduction to Programming
Variables, Data Types & Math
Topics Introduction to Functions Defining and Calling a Void Function
Python for Informatics: Exploring Information
Variables, Data Types & Math
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
Variables, Data Types & Math
Loops and Simple Functions
COMPUTER PROGRAMMING SKILLS
Introduction to Programming
More Basics of Python Common types of data we will work with
def-ining a function A function as an execution control structure
 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

A set of statements (lines of code) that can be run repeatedly Goals: Learning Python by Lutz and Ascher –Code reuse –Procedural decomposition

Top-Down Design Break problem into subproblems Print HIHO in block letters 1.print H 2.print I 3.print H 4.print O Write a function to solve each subproblem

def printH(): print "* *" print "***" print "* *" print def printI(): print "***" print " * " print "***" print def printO(): print " * " print "* *" print " * " print printH() printI() printH() printO()

Function Calls We’ve seen a few: –my_num = input(“Enter number: “) –my_string = raw_input(“Enter string: “) Syntax: function_name(parameters) Other examples: –int(“7”) - converts the string “7” to an integer –str(9) - converts the integer 9 to a string –float(2) - converts the integer 2 to a float(2.0) can be used to force floating point division: float(5)/2 = 2.5!

Modules A module groups together several functions math is a common module import math allows you to use the math functions dot operator allows you to call math functions –syntax: module_name.function(parameters) import math math.floor(9.5) math.ceil(9.5) str(math.floor(9.4)) #function call as parameter

Function Definition Step 1: Think about what your function will do, the input it requires, the result it will produce, and the side-effects it might have –printH the function will display the letter H in star characters it does not require input it will not produce a result the side-effect will be output displayed on the screen

Function Definition Syntax: def function_name(parameters): statements function_name can be anything - follow the rules for variable names parameters are the input statements are the code that gets executed statements MUST be indented (all by the same number of spaces/tabs)

Example - no input #definition of function to print a greeting #no input, no output, side-effect: greeting is displayed def greeting(): print "Hello” greeting() #call to function greeting #definition of function to print a closing #no input, no output, side-effect: closing is displayed def closing(): print "Goodbye" closing() #call to function closing #definition of function to print a greeting and closing #no input, no output, side-effect: greeting and closing displayed def meeting(): greeting() #example of a function call from within closing() #a function meeting() #call to function meeting

Call to function meeting() main meeting main meeting greeting main meeting main meeting closing main meeting main “Goodbye” “Hello” 2

Parameters/Arguments Input for functions Specify variable names in parameter list def add(number1, number2): sum = number1 + number2 print “Sum: “, sum When function add is called, two numbers must be passed as input add(3, 4) Variable number1 gets the value 3 and variable number2 gets the value 4

Parameters/Arguments Values are assigned in order –the first value passed in the function call is assigned to the first parameter in the function definition >>> def taketwo(mynum, mystring):... print "mynum ", mynum... print "mystring ", mystring... >>> taketwo("hello", 7) mynum hello mystring 7

Parameters/Arguments Variables can be passed as parameters number1 = input("Enter first number: ") number2 = input("Enter second number: ") add(number1, number2) bob = input("Enter first number: ") alice = input("Enter second number: ") add(bob, alice)

Parameters/Arguments Pass by assignment number1 = input("Enter first number: ") number2 = input("Enter second number: ") add(number1, number2) number1 number2 NamesObjects main number1 number2 add 3 4

Parameters/Arguments Pass by assignment bob = input("Enter first number: ") alice = input("Enter second number: ") add(bob, alice) bob alice NamesObjects main number1 number2 add 3 4

Scope Parameters and variables defined inside a function can only be accessed in that function def greeting(word): sentence = "The greeting is " + word + "." print sentence Traceback (most recent call last): File "test.py", line 4, in ? print sentence NameError: name 'sentence' is not defined

Scope Parameters and variables defined inside a function can only be accessed in that function def greeting(word): sentence = "The greeting is " + word + "." print word Traceback (most recent call last): File "test.py", line 4, in ? print sentence NameError: name ’word' is not defined

Another Example def greeting(word): sentence = "The greeting is " + word + "." print sentence sentence = "This is not the greeting." print sentence greeting("hello") print sentence This is not the greeting. The greeting is hello. This is not the greeting.

Return Values Functions may return a value to the caller Results should be saved in a variable –the function call should appear on the right side of an = #a function to get input def getprice(): price = input("Enter purchase price: ") return price price = getprice()

TAX_RATE =.0825 def getcost(): cost = input("Enter item cost: ") return cost def calctax(cost): tax = cost*TAX_RATE return tax def calctotal(cost, tax): total = cost+tax return total def printresult(cost, tax, total): print "Cost: ", cost print "Tax : ", tax print "Total: ", total cost = getcost() tax = calctax(cost) total = calctotal(cost, tax) printresult(cost, tax, total)