Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming.

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Computer Science 1620 Loops.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
 2007 Pearson Education, Inc. All rights reserved Introduction to C 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 C Programming
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Fundamentals of Python: From First Programs Through Data Structures
Ruby (on Rails) CSE 190M, Spring 2009 Week 1. The Players Kelly "Everyday I'm Hustlin' " Dunn Kim "Mouse" Todd Ryan "Papa T" Tucker.
More Functions CS303E: Elements of Computers and Programming.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Fundamentals of Python: First Programs
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Lists and More About Strings CS303E: Elements of Computers and Programming.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Module 3 Fraser High School. Module 3 – Loops and Booleans import statements - random use the random.randint() function use while loop write conditional.
Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Practice with Lists and Strings CS303E: Elements of Computers and Programming.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
More Functions with Return Values CS303E: Elements of Computers and Programming.
9/14/2015BCHB Edwards Introduction to Python BCHB Lecture 4.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Counter-Controlled Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Learning Javascript From Mr Saem
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
Nested Loops CS303E: Elements of Computers and Programming.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Computer Science 1000 LOGO II. Boolean Expressions like Excel and Scratch, LOGO supports three Boolean operators less than (
Topics Introduction to Repetition Structures
Agenda Control Flow Statements Purpose test statement
Arithmetic operations, decisions and looping
Python Primer 2: Functions and Control Flow
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Chapter (3) - Looping Questions.
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Introduction to Python
Writing Functions( ) (Part 4)
Loops.
G. Pullaiah College of Engineering and Technology
CHAPTER 6: Control Flow Tools (for and while loops)
Loops and Simple Functions
COMPUTER PROGRAMMING SKILLS
CSE 231 Lab 4.
CSE 190p University of Washington Michael Ernst
CISC101 Reminders Assignment 3 due today.
def-ining a function A function as an execution control structure
Lecture 20 – Practice Exercises 4
Presentation transcript:

Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming

Review: sys.stdout.write() Recall that it allows you to print without a trailing space or newline Recall that it allows you to print without a trailing space or newline Unlike print, it only accepts strings Unlike print, it only accepts strings

Functions: Review Functions are useful: Functions are useful: –For carrying out actions that you will want to use multiple times –For grouping actions together for code readability Arguments allow us to pass different values to a function Arguments allow us to pass different values to a function

Functions: Returning Values Functions may return a value Functions may return a value –For example: seq=range(10) #returns a list of values seq=range(10) #returns a list of values root=math.sqrt(9) #returns the square root root=math.sqrt(9) #returns the square root n=random.randint(1,100) #returns a random int n=random.randint(1,100) #returns a random int –In each case, the value returned is assigned to the left-hand-side variable ( seq, root, n ) Functions compute the value and then gives it back via a return statement Functions compute the value and then gives it back via a return statement

Syntax To define a function: def functionName(par1, par2): <code> return someValue To call this function: result=functionName(arg1,arg2) New!

How It Works Given this call: Given this call:result=functionName(arg1,arg2) When the function is called: When the function is called: –par1 set to arg1 –par2 set to arg2 –The function is executed, and –The value that is returned by the function is assigned to result

Example def times3(number): return 3*number return 3*number Function call: result=times3(7) #result is 21 result=times3(7) #result is 21

How It Works You can also call a function that returns a value anywhere you would use a variable or value You can also call a function that returns a value anywhere you would use a variable or value

Example def times3(number): return 3*number return 3*number Function call: if(x*3==times3(x)): if(x*3==times3(x)): print “They are equal!” print “They are equal!” #They are equal #They are equal #The print statement executes #The print statement executes

iClicker Question What is the expected output? def addOne(x): return x+1 return x+1result=addOne(3) print result A. 2C. 4 B. 3D. Error

Multiple Return Statements A function may have more than one return statement A function may have more than one return statement Remember that execution returns to the calling function whenever a return statement is reached Remember that execution returns to the calling function whenever a return statement is reached Some consider this to be a bad programming practice, but it does have value Some consider this to be a bad programming practice, but it does have value

Multiple Returns: Example #returns True if num is a power of 2 def powerOfTwo(num): while(num >2): if(num%2!=0): return False num=num/2 return True

Another Way: Flags A flag is a variable that is used to track some information A flag is a variable that is used to track some information Often used to know when to stop loops or exit a function Often used to know when to stop loops or exit a function

Flags: Example def powerOfTwo_flags(num): poss_power=True #flag poss_power=True #flag while(num>2 and poss_power==True): while(num>2 and poss_power==True): if(num%2!=0): if(num%2!=0): poss_power=False poss_power=False num=num/2 num=num/2

Good Programming Practice: Return Values In Python, a function may return more than one type of value In Python, a function may return more than one type of value Better to always return one type, so that the calling function can expect a particular type Better to always return one type, so that the calling function can expect a particular type For instance, string.find() returns a -1 instead of “Not Found” For instance, string.find() returns a -1 instead of “Not Found” Most languages require this!! Most languages require this!!

Exercise Write a function called reverseIt() that takes a string parameter and returns the reverse of the string. Write a main function that reads 10 strings from the user and prints the reverse of each string. Write a function called reverseIt() that takes a string parameter and returns the reverse of the string. Write a main function that reads 10 strings from the user and prints the reverse of each string.

Question: What is the output?A. 6 def addOne(x): B. 8 return x+1 C. 9 D. 10 x=2 for i in range(3): for j in range(2): for j in range(2): x=addOne(x) x=addOne(x) print x

Another Note: Functions Functions may be called from within functions Functions may be called from within functions Realize: Realize: –main() is a function –We’ve called string functions from other functions –It works the same way!

Exercise Write a function that takes 3 numbers as arguments and returns the product of the three numbers. Write a function that takes 3 numbers as arguments and returns the product of the three numbers. Write a main function that calls this function for the following values and prints the result: Write a main function that calls this function for the following values and prints the result: 1, 2, 3 2, 3, 4 2, 3, 4 3, 4, 5, 3, 4, 5, … 20, 21, 22 20, 21, 22

Gotchas! ALL functions in Python return a value. If there is not a return statement, it returns the value None. ALL functions in Python return a value. If there is not a return statement, it returns the value None. When the execution reaches a return statement, execution immediately returns to the calling function When the execution reaches a return statement, execution immediately returns to the calling function