0% found this document useful (0 votes)
24 views

Presentation 03

Uploaded by

marufbl360
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Presentation 03

Uploaded by

marufbl360
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Lecture 3

Functions & Modules


Announcements

Reminders Optional Videos

• Grading AI quiz today • Today


§ Take now if have not § Lesson 3: Function Calls
§ If make 9/10, are okay § Lesson 4: Modules
§ Else must retake § Videos 4.1-4.5
• Survey 0 is still open • Next Time
§ For participation score § Video 4.6 of Lesson 4
§ Must complete them § Lesson 5: Function Defs
• Must access in CMS • Also skim Python API
8/30/22 Functions & Modules 2
Function Calls

• Python supports expressions with math-like functions


§ A function in an expression is a function call
• Function calls have the form
name(x,y,…)

function argument
name

• Arguments are
§ Expressions, not values
§ Separated by commas
8/30/22 Functions & Modules 3
Built-In Functions
• Python has several math functions
Arguments can be
§ round(2.34) any expression
§ max(a+3,24)
• You have seen many functions already
§ Type casting functions: int(), float(), bool()
• Documentation of all of these are online
§ https://docs.python.org/3/library/functions.html
§ Most of these are two advanced for us right now

8/30/22 Functions & Modules 4


Functions as Commands/Statements

• Most functions are expressions.


§ You can use them in assignment statements
§ Example: x = round(2.34)
• But some functions are commands.
§ They instruct Python to do something
§ Help function: help() These take no
§ Quit function: quit() arguments

• How know which one? Read documentation.


8/30/22 Functions & Modules 5
Built-in Functions vs Modules

• The number of built-in functions is small


§ http://docs.python.org/3/library/functions.html
• Missing a lot of functions you would expect
§ Example: cos(), sqrt()
• Module: file that contains Python code
§ A way for Python to provide optional functions
§ To access a module, the import command
§ Access the functions using module as a prefix
8/30/22 Functions & Modules 6
Example: Module math
>>> import math
>>> math.cos(0)
1.0
>>> cos(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cos' is not defined
>>> math.pi
3.141592653589793
>>> math.cos(math.pi)
-1.0
8/30/22 Functions & Modules 7
Example: Module math
>>> import math To access math
functions
>>> math.cos(0)
Functions
1.0
require math
>>> cos(0) prefix!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cos' is not defined
>>> math.pi
3.141592653589793
>>> math.cos(math.pi)
-1.0
8/30/22 Functions & Modules 8
Example: Module math
>>> import math To access math
functions
>>> math.cos(0)
Functions
1.0
require math
>>> cos(0) prefix!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cos' is not defined
>>> math.pi Module has
variables too!
3.141592653589793
>>> math.cos(math.pi)
-1.0
8/30/22 Functions & Modules 9
Example: Module math
>>> import math To access math
functions Other Modules
>>> math.cos(0)
Functions
1.0 • os
require math
>>> cos(0) prefix! § Information about your OS
Traceback (most recent call last): § Cross-platform features

File "<stdin>", line 1, in <module> • random


§ Generate random numbers
NameError: name 'cos' is not defined
§ Can pick any distribution
>>> math.pi Module has
variables too! • introcs
3.141592653589793
§ Custom module for the course
>>> math.cos(math.pi) § Will be used a lot at start
-1.0
8/30/22 Functions & Modules 10
Using the from Keyword
>>> import math • Be careful using from!
Must prefix with
>>> math.pi module name • Using import is safer
3.141592653589793 § Modules might conflict
>>> from math import pi (functions w/ same name)
No prefix needed
>>> pi for variable pi § What if import both?
3.141592653589793 • Example: Turtles
>>> from math import *
§ Used in Assignment 4
>>> cos(pi)
§ 2 modules: turtle, introcs
-1.0 No prefix needed
for anything in math § Both have func. Turtle()
8/30/22 Functions & Modules 11
Reading the Python Documentation

http://docs.python.org/3/library

8/30/22 Functions & Modules 12


Reading the Python Documentation

Function
name

Possible arguments

Module
What the function evaluates to

http://docs.python.org/3/library

8/30/22 Functions & Modules 13


Interactive Shell vs. Modules

• Launch in command line • Write in a code editor


§ We use VS Code
• Type each line separately
§ But anything will work
• Python executes as you type • Load module with import

8/30/22 Functions & Modules 14


Using a Module

Module Contents

""" A simple module.

This file shows how modules work


"""

# This is a comment
x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 15
Using a Module

Module Contents

""" A simple module.

This file shows how modules work


"""
Single line comment
# This is a comment (not executed)

x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 16
Using a Module

Module Contents

""" A simple module. Docstring (note the Triple Quotes)


Acts as a multiple-line comment
This file shows how modules work Useful for code documentation
"""
Single line comment
# This is a comment (not executed)

x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 17
Using a Module

Module Contents

""" A simple module. Docstring (note the Triple Quotes)


Acts as a multiple-line comment
This file shows how modules work Useful for code documentation
"""
Single line comment
# This is a comment (not executed)

x = 1+2 Commands
Executed on import
x = 3*x
x
8/30/22 Functions & Modules 18
Using a Module

Module Contents

""" A simple module. Docstring (note the Triple Quotes)


Acts as a multiple-line comment
This file shows how modules work Useful for code documentation
"""
Single line comment
# This is a comment (not executed)

x = 1+2 Commands
Executed on import
x = 3*x
x Not a command.
import ignores this
8/30/22 Functions & Modules 19
Using a Module

Module Contents Python Shell

""" A simple module. >>> import module


>>> x
This file shows how modules work
"""

# This is a comment
x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 20
Using a Module

Module Contents Python Shell

""" A simple module. >>> import module


>>> x
This file shows how modules work Traceback (most recent call last):
""" File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
# This is a comment
x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 21
Using a Module

Module Contents Python Shell

""" A simple module. >>> import module


>>> x
This file shows how modules work Traceback (most recent call last):
""" File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
# This is a comment >>> module.x
“Module data” must be
x = 1+2 prefixed by module name 9
x = 3*x
x
8/30/22 Functions & Modules 22
Using a Module

Module Contents Python Shell

""" A simple module. >>> import module


>>> x
This file shows how modules work Traceback (most recent call last):
""" File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
# This is a comment >>> module.x
“Module data” must be
x = 1+2 prefixed by module name 9
x = 3*x >>> help(module)
Prints docstring and
x module contents
8/30/22 Functions & Modules 23
Modules Must be in Working Directory!

Module you want


is in this folder

8/30/22 Functions & Modules 24


Modules Must be in Working Directory!

Module you want


is in this folder

Have to navigate to folder


BEFORE running Python

8/30/22 Functions & Modules 25


Modules vs. Scripts

Module Script

• Provides functions, variables • Behaves like an application


§ Example: temp.py § Example: helloApp.py
• import it into Python shell • Run it from command line:
>>> import temp python helloApp.py
>>> temp.to_fahrenheit(100)
212.0
>>>

8/30/22 Functions & Modules 26


Modules vs. Scripts

Module Script

• Provides functions, variables • Behaves like an application


§ Example: temp.py § Example: helloApp.py
• import it into Python shell • Run it from command line:
>>> import temp python helloApp.py
>>> temp.to_fahrenheit(100)
212.0
>>>

Files look the same. Difference is how you use them.


8/30/22 Functions & Modules 27
Scripts and Print Statements

module.py script.py

""" A simple module. """ A simple script.

This file shows how modules work This file shows why we use print
""" """

# This is a comment # This is a comment


x = 1+2 x = 1+2
x = 3*x x = 3*x
x print(x)
8/30/22 Functions & Modules 28
Scripts and Print Statements

module.py script.py

""" A simple module. """ A simple script.

This file shows how modules work This file shows why we use print
""" """

# This is a comment # This is a comment


x = 1+2 x = 1+2
x = 3*x x = 3*x
x Only difference print(x)
8/30/22 Functions & Modules 29
Scripts and Print Statements

module.py script.py

• Looks like nothing happens • We see something this time!


• Python did the following: • Python did the following:
§ Executed the assignments § Executed the assignments
§ Skipped the last line § Executed the last line
(‘x’ is not a statement) (Prints the contents of x)
8/30/22 Functions & Modules 30
Scripts and Print Statements

module.py script.py

a s c ri p t,
n We see something this time!
• Looks like nothing n y
happens
e o u r u•
Wh re e x e c u te d
e n ts a

only statem • Python did the following:
Python did the following:
§ Executed the assignments § Executed the assignments
§ Skipped the last line § Executed the last line
(‘x’ is not a statement) (Prints the contents of x)
8/30/22 Functions & Modules 31
User Input
>>> input('Type something')
Type somethingabc No space after the prompt.
'abc'
>>> input('Type something: ')
Type something: abc Proper space after prompt.
'abc'
>>> x = input('Type something: ')
Type something: abc
Assign result to variable.
>>> x
'abc'
8/30/22 Functions & Modules 32
Making a Script Interactive
"""
A script showing off input. [wmw2] folder> python script.py
Give me something: Hello
This file shows how to make a script You said: Hello
interactive. [wmw2] folder> python script.py
""" Give me something: Goodbye
You said: Goodbye
x = input("Give me a something: ") [wmw2] folder>
print("You said: "+x)
Not using the
interactive shell

8/30/22 Functions & Modules 33


Numeric Input

• input returns a string >>> x = input('Number: ')


§ Even if looks like int Number: 3
§ It cannot know better >>> x
Value is a string.
• You must convert values '3'
§ int(), float(), bool(), etc. >>> x + 1
§ Error if cannot convert TypeError: must be str, not int
• One way to program >>> x = int(x)
§ But it is a bad way >>> x+1 Must convert to
int.
§ Cannot be automated 4

8/30/22 Functions & Modules 34


Next Time: Defining Functions

Function Call Function Definition

• Command to do the function • Command to do the function


• Can put it anywhere • Belongs inside a module
§ In the Python shell
§ Inside another module

8/30/22 Functions & Modules 35


Next Time: Defining Functions

Function Call Function Definition

• Command to do the function • Command to do the function


• Can put it anywhere • Belongs inside a module
§ In the Python shell
§ Inside another module
But only define
arguments function ONCE
inside ()

Can call as many


times as you want
8/30/22 Functions & Modules 36
Clickers (If Time)

8/30/22 Functions & Modules 37


Reading Documentation

8/30/22 Functions & Modules 38


Reading isclose

• Assume that we type


>>> import weird
>>> isclose(2.000005,2.0)
• What is the result (value)?
A: True
B: False
C: An error!
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 39


Reading isclose

• Assume that we type


>>> import weird
>>> isclose(2.000005,2.0)
• What is the result (value)?
A: True
B: False
C: An error! CORRECT
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 40


Reading isclose

• Assume that we type


>>> import weird
>>> weird.isclose(2.000005,2.0)
• What is the result (value)?
A: True
B: False
C: An error!
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 41


Reading isclose

• Assume that we type


>>> import weird
>>> weird.isclose(2.000005,2.0)
• What is the result (value)?
A: True
B: False CORRECT
C: An error!
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 42


Reading isclose

• Assume that we type


>>> import weird
>>> weird.isclose(2.0,3.0,4.0)
• What is the result (value)?
A: True
B: False
C: An error!
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 43


Reading isclose

• Assume that we type


>>> import weird
>>> weird.isclose(2.0,3.0,4.0)
• What is the result (value)?
A: True CORRECT
B: False
C: An error!
D: Nothing!
E: I do not know

8/30/22 Functions & Modules 44

You might also like