[go: up one dir, main page]

0% found this document useful (0 votes)
12 views39 pages

03 Fns Modules

Uploaded by

jackmwexh1225
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views39 pages

03 Fns Modules

Uploaded by

jackmwexh1225
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

http://www.cs.cornell.

edu/courses/cs1110/2019sp

Lecture 3:
Functions & Modules
(Sections 3.1-3.3)
CS 1110
Introduction to Computing Using Python

[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]


Function Calls
• Function expressions have the form:
fun(x,y,…)
function argument
name
• Some math functions built into Python:
>>> x = 5 >>> a = round(3.14159265)
>>> y = 4 >>> a
>>> bigger = max(x, y) 3
>>> bigger
5

Arguments can be any expression 2


Always-available Built-in Functions

• You have seen many functions already


§ Type casting functions: int(), float(), bool()
§ Get type of a value: type()
§ Exit function: exit()
Arguments go in (), but
name() refers to
function in general
• Longer list:
http://docs.python.org/3/library/functions.html

3
Modules
• Many more functions available via built-in modules
§ “Libraries” of functions and variables
• To access a module, use the import command:
import <module name>
Can then access functions like this:
<module name>.<function name>(<arguments>)
Example:
>>> import math
>>> p = math.ceil(3.14159265)
>>> p
4 4
Module Variables

• Modules can have variables, too


• Can access them like this:
<module name>.<variable name>
• Example:
>>> import math
>>> math.pi
3.141592653589793

5
Visualizing functions & variables
• So far just built-ins
int()
float()
str()
type()
print()

C:\> python
>>>

6
Visualizing functions & variables
• So far just built-ins
int()
• Now we’ve defined a float()
new variable str()
type()
print()

C:\> python x 7

>>> x = 7
>>>

7
Visualizing functions & variables
• So far just built-ins
int()
• Now we’ve defined a float()
new variable str()
• Now we’ve imported a type()
module print()

C:\> python x 7

>>> x = 7 math
ceil()
>>> import math sqrt()
>>> e 2.718281
pi 3.14159

8
module help

After importing a module, see what


functions and variables are available:
>>> help(<module name>)

9
Reading the Python Documentation
https://docs.python.org/3/library/math.html

10
A Closer Reading of the Python
Documentation
https://docs.python.org/3/library/math.html
Function
name
Possible arguments

Module What the function


evaluates to

11
Other Useful Modules
• io
§ Read/write from files
• random
§ Generate random numbers
§ Can pick any distribution
• string
§ Useful string functions
• sys
§ Information about your OS

12
Making your Own Module

Write in a text editor


We recommend Atom…
…but any editor will work

13
Interactive Shell vs. Modules

Python Interactive Shell Module

• Type python at command line • Written in text editor


• Type commands after >>> • Loaded through import
• Python executes as you type • Python executes statements
when import is called

Section 2.4 in your textbook discusses a few differences 14


my_module.py

Module Text

# my_module.py Single line comment


(not executed)
"""This is a simple module.
Docstring
It shows how modules work""" (note the Triple Quotes)
Acts as a multi-line comment
Useful for code documentation
x = 1+2
x = 3*x Commands
Executed on import

15
Modules Must be in Working Directory!
Must run python from same folder as the module

16
Using a Module (my_module.py)

Module Text Python Command Shell

# my_module.py >>> import my_module

"""This is a simple module. Needs to be the same name


It shows how modules work""" as the file without the “.py”

x = 1+2
x = 3*x

17
On import….

Module Text Python Command Shell

# my_module.py Python does not execute >>> import my_module


(because of #)

"""This is a simple module. Python does not execute


(because of """ and """)
It shows how modules work"""
my_module
x = 1+2 Python executes this.
x = 3*x Python executes this. x x
3 9

18
variable x stays “within” the module
Clicker Question!

Module Text Python Command Shell

# my_module.py >>> import my_module

"""This is a simple module. After you hit “Return” here


It shows how modules work""" what will python print next?
(A) >>>
(B) 9
x = 1+2
>>>
x = 3*x (C) an error message
(D) The text of my_module.py
(E) Sorry, no clue.
19
Clicker Answer

Module Text Python Command Shell

# my_module.py >>> import my_module

"""This is a simple module. After you hit “Return” here


It shows how modules work""" what will python print next?
(A) >>>
(B) 9
x = 1+2
>>>
x = 3*x (C) an error message
(D) The text of my_module.py
(E) Sorry, no clue.
20
Using a Module (my_module.py)

Module Text Python Command Shell

# my_module.py >>> import my_module


>>> my_module.x variable we
want to access
"""This is a simple module. 9
It shows how modules work""" module name

x = 1+2 my_module
x = 3*x
x x
3 9

21
Windows command line
You must import (Mac looks different)

With import Without import


C:\> python C:\> python
>>> import math >>> math.ceil(3.14159)
>>> p = math.ceil(3.14159) Traceback (most recent call last):
File "<stdin>", line 1, in <module>
>>> p
NameError: name 'math' is not
4 defined
Python unaware of
math what “math” is
p 4
ceil()
sqrt()
e 2.718281
pi 3.14159
… 22
You Must Use the Module Name
>>> import my_module >>> import my_module
>>> my_module.x >>> x
9 Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

my_module my_module

xx
3 9 xx
3 9

23
What does the docstring do?

Module Text Python Command Shell

# my_module.py

"""This is a simple module.


It shows how modules work"""

x = 1+2
x = 3*x

24
from command
• You can also import like this:
from <module> import <function name>
• Example:
>>> from math import pi
>>> pi no longer need the module name
3.141592653589793
pi 3.141592653589793

25
from command
• You can also import everything from a module:
from <module> import *
• Example:
>>> from math import *
ceil()
>>> pi sqrt()
3.141592653589793 e 2.718281828459045
pi 3.141592653589793
>>> ceil(pi) …
4
Module functions now behave
like built-in functions 26
Dangers of Importing Everything

>>> e = 12345
>>> from math import *
>>> e
2.718281828459045 e 2.718281828459045
12345

e was ceil()
overwritten! sqrt()
pi 3.141592653589793

27
Avoiding from Keeps Variables Separate
>>> e = 12345
>>> import math
>>> math.e
e 12345
2.718281828459045
math
>>> e
ceil()
12345 sqrt()
e 2.718281
pi 3.14159

28
Ways of Executing Python Code

1. running the Python Interactive Shell


2. importing a module
3. NEW: running a script

29
Running a Script

• From the command line, type:


python <script filename>
• Example:
C:\> python my_module.py
C:\>
looks like nothing happened

• Actually, something did happen


§ Python executed all of my_module.py

30
Running my_module.py as a script

my_module.py Command Line

# my_module.py Python does not execute


C:\> (because
python of #)
module.py

"""This is a simple module. Python does not execute


(because of """ and """)
It shows how modules work"""

x = 1+2 Python executes this. x x


3 9
x = 3*x Python executes this.

31
Running my_module.py as a script

my_module.py Command Line

# my_module.py C:\> python my_module.py


C:\>
"""This is a simple my_module. when the script ends, all memory
It shows how modules work""" used by my_module.py is deleted

thus, all variables get deleted


x = 1+2 (including x)
x = 3*x
so there is no evidence that the
script ran
32
Clicker Question

my_module.py Command Line

# my_module.py C:\> python my_module.py


C:\> my_module.x
"""This is a simple my_module.
It shows how modules work""" After you hit “Return” here
what will be printed next?
(A) >>>
x = 1+2 (B) 9
x = 3*x >>>
(C) an error message
(D) The text of my_module.py
(E) Sorry, no clue.
33
Clicker Answer

my_module.py Command Line

# my_module.py C:\> python my_module.py


C:\> my_module.x
"""This is a simple my_module.
It shows how modules work""" After you hit “Return” here
what will be printed next?
(A) >>>
x = 1+2 (B) 9
x = 3*x >>>
(C) an error message
(D) The text of my_module.py
(E) Sorry, no clue.
34
Creating Evidence that the Script Ran

• New (very useful!) command: print


print (<expression>)
• print evaluates the <expression> and writes the
value to the console

35
my_module.py vs. script.py

my_module.py script.py

# my_module.py # script.py

""" This is a simple module. """ This is a simple script.


It shows how modules work""" It shows why we use print"""

x = 1+2 x = 1+2
x = 3*x x = 3*x
Only difference print(x)

36
Running script.py as a script

Command Line script.py

C:\> python script.py # script.py


9
""" This is a simple script.
C:\> It shows why we use print"""

x = 1+2
x = 3*x
print(x)

37
Subtle difference about script mode

Interactive mode script.py

C:\> python # script.py


>>> x = 1+2
>>> x = 3*x """ This is a simple script.
>>> x It shows why we use print"""
9
>>> print(x) x = 1+2
9 x = 3*x
>>> print(x)
# note: in script mode, you will
# not get output if you just type x
38
Modules vs. Scripts

Module Script

• Provides functions, variables • Behaves like an application


• import it into Python shell • Run it from command line

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

39

You might also like