• No results found

Working with Functions in Python Part II. Introduction to Programming - Python

N/A
N/A
Protected

Academic year: 2022

Share "Working with Functions in Python Part II. Introduction to Programming - Python"

Copied!
39
0
0

Loading.... (view fulltext now)

Full text

(1)

+

Working with Functions in Python – Part II

Introduction to Programming - Python

(2)

+ Week of 10/12

n Reading Gaddis Chapter #5

n Midterm Review w/ Course Assistants – October 22nd

n See NYU Brightspace Announcement

n Midterm Review Class – October 26th

n Lecture

n Void Functions

n Defining Functions

n Value-returning Functions

n Storing Functions in Modules

n Text Adventure Game

Day 14

(3)

+

Functions

Definitions Revisited

(4)

+ Functions

n A function is a group of statements that exist within a program for the purpose of performing a specific task

n Since the beginning of the semester we have been using a number of Python’s built-in functions, including:

n print()

n range()

n len()

n random.randint()

n … etc

(5)

+ Functions

n Most programs perform tasks that are large enough to be broken down into subtasks

n Because of this, programmers often organize their programs into smaller, more manageable chunks by writing their own functions

n Instead of writing one large set of statements we can break down a program into several small functions, allowing us to

“divide and conquer” a programming problem

(6)

+ Syntax for Defining & Calling Python Functions

n Defining a Python function:

def <function_name>([<parameters>]):

<statement(s)>

n First line – function header

n Statements – block / function body

n Calling a Python function:

<function_name>([<arguments>])

(7)

+ Void Functions

n Functions returning no values def f():

s = '-- Inside f()' print(s)

print('Before calling f()')

# calling the function f()

print('After calling f()')

(8)

+ Void Functions

def main():

x = 1 y = 3.4

print(x, y) # PART 1 - what gets printed?

change_us(x, y)

print(x, y) # PART 3 - what gets printed?

def change_us(a, b):

a = 0 b = 0

print(a, b) # PART 2 - what gets printed?

main()

Following the Program Display

(9)

+

(10)

+

(11)

+

(12)

+ Some notes on functions

n When you run a function you say that you “call” it

n Once a function has completed, Python will return back to the line directly after the initial function call

n When a function is called programmers commonly say that the “control” of the program has been transferred to the function. The function is responsible for the program’s execution.

n Functions must be defined before they can be used. In Python we generally place all of our functions at the beginning of our programs.

(13)

+

Multiple Functions

(14)

+ Pass Keyword

def step1():

pass

def step2():

pass

def step3():

pass

def step4():

pass

(15)

+ Calling functions inside functions

def main():

value = 99

print(f'The value is {value}.') change_me(value)

print(f'Back in main the value is {value}.')

def change_me(arg):

print('I am changing the value.') arg = 0

print(f'Now the value is {arg}.') main()

(16)

+

(17)

+ Mixing Keyword and Positional Arguments

def main():

# Show the amount of simple interest, using 0.01 as

# interest rate per period, 10 as the number of periods,

# and $10,000 as the principal.

show_interest(rate=0.01, periods=10, principal=10000.0)

def show_interest(principal, rate, periods):

# The show_interest function displays the amount of

# simple interest for a given principal, interest rate

# per period, and number of periods.

interest = principal * rate * periods

print(f'The simple interest will be ${interest:,.2f}.')

main()

show_interest(10000.0, rate=0.01, periods=10) show_interest(1000.0, rate=0.01, 10)

(18)

+

Value Returning Functions

(19)

+ Value Returning Functions

n Value returning functions are functions that return a value to the part of the program that initiated the function call

n They are almost identical to the type of functions we have been writing so far, but they have the added ability to send back information at the end of the function call

n We have secretly been using these all semester!

n somestring = input(“Tell me your name”)

n somenumber = random.randint(1,5)

(20)

+ Value Returning Functions

def myfunction(arg1, arg2):

# statement

# statement

# …

# statement

return expression

# call the function

returnvalue = myfunction(10, 50)

(21)

+ Writing your own value returning functions

n You use almost the same syntax for writing a value returning function as you would for writing a normal function

n The only difference is that you need to include a “return”

statement in your function to tell Python that you intend to return a value to the calling program

n The return statement causes a function to end immediately.

It’s like the break statement for a loop.

n A function will not proceed past its return statement once encountered. Control of the program is returned back to the caller.

(22)

+ Calling Functions in f-strings

import random

print(f'The number is {random.randint(1, 100)}.’)

# print a random number that is center-aligned in a field that is 10 characters wide

(23)

+ Returning Boolean Values

n Boolean values can drastically simplify decision and repetition structures

n Example:

n Write a program that asks the user for a part number

n Only accept part #’s that are on the following list:

n 100

n 200

n 300

n 400

n 500

n Continually prompt the user for a part # until they enter a correct value

(24)

+ Using Boolean Functions in Validation Code

# Get the model number.

model = int(input('Enter the model number:

'))

# Validate the model number.

while model != 100 and model != 200 and model != 300:

print('The valid model numbers are 100, 200 and 300.')

model = int(input('Enter a valid model number: '))

# Get the model number.

model = int(input('Enter the model number: '))

# Validate model number with a function def is_invalid(model):

if model != 100 and model != 200 and model !=

300:

return True return False

# Validate with a function while is_invalid(model):

print('The valid model numbers are 100, 200 and 300.')

model = int(input('Enter a valid model number:

'))

Without Boolean Function With Boolean Function

(25)

+

Modules

Storing Functions in Modules

(26)

+ Storing Functions in Modules

# The area function accepts a rectangle's width and

# length as arguments and returns the rectangle's area.

def area(width, length):

return width * length

# The perimeter function accepts a rectangle's width

# and length as arguments and returns the rectangle's

# perimeter.

def perimeter(width, length):

return 2 * (width + length)

# The main function is used to test the other functions.

def main():

width = float(input("Enter the rectangle's width: ")) length = float(input("Enter the rectangle's length: ")) print('The area is', area(width, length))

print('The perimeter is', perimeter(width, length))

# Call the main function ONLY if the file is being run as

# a standalone program.

if __name__ == '__main__':

main()

(27)

+

Programming Challenges

(28)

+ Programming Challenge: Hollow Square

n Write a program that prints the pattern to the right using functions

(29)

+ Programming Challenge:

User Controlled Hollow Rectangle

n Ask the user for the height for a rectangle

n Then draw a rectangle of that height

(30)

+ Programming Challenge

n Write a function that accepts a restaurant check and a tip %

n Print out the tip that should be left on the table as well as the total bill

n If the tip is less than 15% you should tell the user that they might want to leave a little more on the table

(31)

+ Programming Challenge: Distance Formula

n Write a program that asks the user to enter two points on a 2D plane (i.e. enter X1 & Y1, enter X2 & Y2)

n Compute the distance

between those points using a function.

n Continually ask the user for numbers until they wish to quit

(32)

+ Programming Challenge

n Write a “joke” generator that prints out a random knock knock joke.

n Extension: Write a “drum roll”

function that pauses the

program for dramatic effect!

Have the drum roll function accept a parameter that controls how long it should pause.

(33)

+ Programming Challenge:

Combined Age

n Write a function that takes two age values as integers, adds them up and returns the result as an integer

(34)

+ Programming Challenge:

Discounted Pricing

n Prompt the use for an item price (using a function)

n Apply a 20% discount to the price (using a function)

n Print the starting price and the discounted price

n Extension:

n Don’t accept price values less than $0.05 – repeatedly ask the user to enter new data if this happens

n Repeat the discounting

process until the user elects to stop entering data

(35)

+ Programming Challenge: Two Dice

n Write a function that simulates the rolling of two dice

n The function should accept a size parameter (i.e. how many sides does each die have)

n The function should return two values which represent the result of each roll

n Extension:

n Make sure both numbers that you return are different (i.e. you can’t roll doubles or snake eyes)

n Build in an argument that lets you specify whether you want to

enforce the no doubles policy

(36)

+ Programming Challenge:

Maximum of two values

n Write a function named

“maximum” that accepts two integer values and returns the one that the greater of the two to the calling program

(37)

+ Programming Challenge

n Create a module called

“geometry_helper”

n Write two functions in this module:

n Area of circle

n Perimeter of circle

n Each of these functions will accept one argument (a

radius) and will print out the result to the user.

(38)

+ Program Challenge

n Write a function that takes three numbers as parameters

n Your function should return the median value of those parameters

n Include a main program that reads three values from the users and displays their median

Median of Three Values

(39)

+ Programming Challenge

n Write a function to determine whether a password is valid

n Criteria for a good password:

n At least 8 characters long

n Contains at least one uppercase letter

n Contains at least one lowercase letter

n Contains at least one number

n Your function should return True if the password is good—

otherwise return False

n Include a main program that reads a password from the user and reports whether it is a valid password

Password Checker

References

Related documents

The project addresses a number of different topics related to ground source heating and cooling such as the importance of geological variations, drilling and grouting in

• Regulation involves both encouraging the timing of investment and seeking that where investment is forced the firm is just financially viable and low cost • Variation in demand

Our estimates show that for the average Sub-Saharan African countries, at the peak, the total e¤ect of HIV/AIDS on growth is a reduction by 6% of income per capita; the e¤ect

Although Euro 5 emission standards could be met by different technologies, Euro 6 standards (into force January 2014) require the use of Selective Catalytic Reduction with

This course provides students with the core to advanced concepts of creating architectural and structural Families in Autodesk Revit Architecture and Revit Structure!. Students

Functions: Designing structured programs, Declaring a function, Signature of a function, Parameters and return type of a function, passing parameters to functions, call

ischemic stroke patients with disease in other vascular beds were at particularly high risk of future vascular events as pre- viously suggested, 13,14 we studied patients