SlideShare a Scribd company logo
Functions & Modules
Lecture 3
Announcements
Reminders Optional Videos
8/30/22 Functions & Modules 2
โ€ข Grading AI quiz today
ยง Take now if have not
ยง If make 9/10, are okay
ยง Else must retake
โ€ข Survey 0 is still open
ยง For participation score
ยง Must complete them
โ€ข Must access in CMS
โ€ข Today
ยง Lesson 3: Function Calls
ยง Lesson 4: Modules
ยง Videos 4.1-4.5
โ€ข Next Time
ยง Video 4.6 of Lesson 4
ยง Lesson 5: Function Defs
โ€ข Also skim Python API
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,โ€ฆ)
โ€ข Arguments are
ยง Expressions, not values
ยง Separated by commas
function
name
argument
8/30/22 Functions & Modules 3
Built-In Functions
โ€ข Python has several math functions
ยง round(2.34)
ยง 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
Arguments can be
any expression
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()
ยง Quit function: quit()
โ€ข How know which one? Read documentation.
These take no
arguments
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
>>> 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 8
To access math
functions
Functions
require math
prefix!
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 9
To access math
functions
Functions
require math
prefix!
Module has
variables too!
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
โ€ข os
ยง Information about your OS
ยง Cross-platform features
โ€ข random
ยง Generate random numbers
ยง Can pick any distribution
โ€ข introcs
ยง Custom module for the course
ยง Will be used a lot at start
8/30/22 Functions & Modules 10
To access math
functions
Functions
require math
prefix!
Module has
variables too!
Other Modules
Using the from Keyword
>>> import math
>>> math.pi
3.141592653589793
>>> from math import pi
>>> pi
3.141592653589793
>>> from math import *
>>> cos(pi)
-1.0
โ€ข Be careful using from!
โ€ข Using import is safer
ยง Modules might conflict
(functions w/ same name)
ยง What if import both?
โ€ข Example: Turtles
ยง Used in Assignment 4
ยง 2 modules: turtle, introcs
ยง Both have func. Turtle()
8/30/22 Functions & Modules 11
Must prefix with
module name
No prefix needed
for variable pi
No prefix needed
for anything in math
Reading the Python Documentation
8/30/22 Functions & Modules 12
http://docs.python.org/3/library
Reading the Python Documentation
8/30/22 Functions & Modules 13
Function
name
Possible arguments
What the function evaluates to
Module
http://docs.python.org/3/library
Interactive Shell vs. Modules
8/30/22 Functions & Modules 14
โ€ข Write in a code editor
ยง We use VS Code
ยง But anything will work
โ€ข Load module with import
โ€ข Launch in command line
โ€ข Type each line separately
โ€ข Python executes as you type
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
"""
# This is a comment
x = 1+2
x = 3*x
x
8/30/22 Functions & Modules 16
Single line comment
(not executed)
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 17
Single line comment
(not executed)
Docstring (note the Triple Quotes)
Acts as a multiple-line comment
Useful for code documentation
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 18
Single line comment
(not executed)
Docstring (note the Triple Quotes)
Acts as a multiple-line comment
Useful for code documentation
Commands
Executed on import
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 19
Single line comment
(not executed)
Docstring (note the Triple Quotes)
Acts as a multiple-line comment
Useful for code documentation
Commands
Executed on import
Not a command.
import ignores this
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
Python Shell
>>> import module
>>>
8/30/22 Functions & Modules 20
x
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
Python Shell
>>> import module
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
8/30/22 Functions & Modules 21
x
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
Python Shell
>>> import module
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
9
8/30/22 Functions & Modules 22
x
module.x
โ€œModule dataโ€ must be
prefixed by module name
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
Python Shell
>>> import module
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
9
>>>
8/30/22 Functions & Modules 23
x
module.x
help(module)
โ€œModule dataโ€ must be
prefixed by module name
Prints docstring and
module contents
Modules Must be in Working Directory!
8/30/22 Functions & Modules 24
Module you want
is in this folder
Modules Must be in Working Directory!
8/30/22 Functions & Modules 25
Module you want
is in this folder
Have to navigate to folder
BEFORE running Python
Modules vs. Scripts
Module
โ€ข Provides functions, variables
ยง Example: temp.py
โ€ข import it into Python shell
>>> import temp
>>> temp.to_fahrenheit(100)
212.0
>>>
Script
โ€ข Behaves like an application
ยง Example: helloApp.py
โ€ข Run it from command line:
python helloApp.py
8/30/22 Functions & Modules 26
Modules vs. Scripts
Module
โ€ข Provides functions, variables
ยง Example: temp.py
โ€ข import it into Python shell
>>> import temp
>>> temp.to_fahrenheit(100)
212.0
>>>
Script
โ€ข Behaves like an application
ยง Example: helloApp.py
โ€ข Run it from command line:
python helloApp.py
8/30/22 Functions & Modules 27
Files look the same. Difference is how you use them.
Scripts and Print Statements
module.py
""" A simple module.
This file shows how modules work
"""
# This is a comment
x = 1+2
x = 3*x
x
script.py
""" A simple script.
This file shows why we use print
"""
# This is a comment
x = 1+2
x = 3*x
print(x)
8/30/22 Functions & Modules 28
Scripts and Print Statements
module.py
""" A simple module.
This file shows how modules work
"""
# This is a comment
x = 1+2
x = 3*x
x
script.py
""" A simple script.
This file shows why we use print
"""
# This is a comment
x = 1+2
x = 3*x
print(x)
8/30/22 Functions & Modules 29
Only difference
Scripts and Print Statements
module.py script.py
8/30/22 Functions & Modules 30
โ€ข Looks like nothing happens
โ€ข Python did the following:
ยง Executed the assignments
ยง Skipped the last line
(โ€˜xโ€™ is not a statement)
โ€ข We see something this time!
โ€ข Python did the following:
ยง Executed the assignments
ยง Executed the last line
(Prints the contents of x)
Scripts and Print Statements
module.py script.py
8/30/22 Functions & Modules 31
โ€ข Looks like nothing happens
โ€ข Python did the following:
ยง Executed the assignments
ยง Skipped the last line
(โ€˜xโ€™ is not a statement)
โ€ข We see something this time!
โ€ข Python did the following:
ยง Executed the assignments
ยง Executed the last line
(Prints the contents of x)
When you run a script,
only statements are executed
User Input
>>> input('Type something')
Type somethingabc
'abc'
>>> input('Type something: ')
Type something: abc
'abc'
>>> x = input('Type something: ')
Type something: abc
>>> x
'abc'
No space after the prompt.
Proper space after prompt.
Assign result to variable.
8/30/22 Functions & Modules 32
Making a Script Interactive
"""
A script showing off input.
This file shows how to make a script
interactive.
"""
x = input("Give me a something: ")
print("You said: "+x)
[wmw2] folder> python script.py
Give me something: Hello
You said: Hello
[wmw2] folder> python script.py
Give me something: Goodbye
You said: Goodbye
[wmw2] folder>
8/30/22 Functions & Modules 33
Not using the
interactive shell
Numeric Input
โ€ข input returns a string
ยง Even if looks like int
ยง It cannot know better
โ€ข You must convert values
ยง int(), float(), bool(), etc.
ยง Error if cannot convert
โ€ข One way to program
ยง But it is a bad way
ยง Cannot be automated
>>> x = input('Number: ')
Number: 3
>>> x
'3'
>>> x + 1
TypeError: must be str, not int
>>> x = int(x)
>>> x+1
4
Value is a string.
Must convert to
int.
8/30/22 Functions & Modules 34
Next Time: Defining Functions
Function Call
โ€ข Command to do the function
โ€ข Can put it anywhere
ยง In the Python shell
ยง Inside another module
Function Definition
โ€ข Command to do the function
โ€ข Belongs inside a module
8/30/22 Functions & Modules 35
Next Time: Defining Functions
Function Call
โ€ข Command to do the function
โ€ข Can put it anywhere
ยง In the Python shell
ยง Inside another module
Function Definition
โ€ข Command to do the function
โ€ข Belongs inside a module
8/30/22 Functions & Modules 36
Can call as many
times as you want
But only define
function ONCE
arguments
inside ()
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)?
8/30/22 Functions & Modules 39
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
Reading isclose
โ€ข Assume that we type
>>> import weird
>>> isclose(2.000005,2.0)
โ€ข What is the result (value)?
8/30/22 Functions & Modules 40
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
CORRECT
Reading isclose
โ€ข Assume that we type
>>> import weird
>>> weird.isclose(2.000005,2.0)
โ€ข What is the result (value)?
8/30/22 Functions & Modules 41
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
Reading isclose
โ€ข Assume that we type
>>> import weird
>>> weird.isclose(2.000005,2.0)
โ€ข What is the result (value)?
8/30/22 Functions & Modules 42
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
CORRECT
Reading isclose
โ€ข Assume that we type
>>> import weird
>>> weird.isclose(2.0,3.0,4.0)
โ€ข What is the result (value)?
8/30/22 Functions & Modules 43
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
Reading isclose
โ€ข Assume that we type
>>> import weird
>>> weird.isclose(2.0,3.0,4.0)
โ€ข What is the result (value)?
8/30/22 Functions & Modules 44
A: True
B: False
C: An error!
D: Nothing!
E: I do not know
CORRECT
Ad

Recommended

PDF
Unit-2 Introduction of Modules and Packages.pdf
Harsha Patil
ย 
PPTX
Python programming workshop session 4
Abdul Haseeb
ย 
PPTX
Python - Functions - Azure Jupyter Notebooks
Adri Jovin
ย 
PPTX
Functions and Modules.pptx
Ashwini Raut
ย 
DOCX
Modules in Python.docx
manohar25689
ย 
PDF
ch 2. Python module
Prof .Pragati Khade
ย 
PDF
Python lecture 03
Tanwir Zaman
ย 
PPTX
Chapter - 4.pptx
MikialeTesfamariam
ย 
PPTX
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
ย 
PDF
Python Basics
tusharpanda88
ย 
PPT
Python Training v2
ibaydan
ย 
PDF
Functions and modules in python
Karin Lagesen
ย 
PPTX
An Introduction : Python
Raghu Kumar
ย 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
ย 
PPTX
Learn Python The Hard Way Presentation
Amira ElSharkawy
ย 
PPTX
Introduction to Python External Course !!!
SlrcMalgn
ย 
PPTX
Python Programming Basics for begginners
Abishek Purushothaman
ย 
PDF
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
ย 
PPTX
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
ย 
PPTX
Functions_in_Python.pptx
krushnaraj1
ย 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
ย 
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
ย 
PDF
Using Python Libraries.pdf
SoumyadityaDey
ย 
PDF
Python Modules, Packages and Libraries
Venugopalavarma Raja
ย 
PPTX
Python module 3, b.tech 5th semester ppt
course5325
ย 
PPTX
lakshya's ppt python for final final.pptx
krishan123sharma123
ย 
PPTX
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
ย 
PDF
Introduction To Programming with Python
Sushant Mane
ย 
PPTX
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
ย 
PPTX
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
ย 

More Related Content

Similar to Python Course Functions and Modules Slides (20)

PPTX
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
ย 
PDF
Python Basics
tusharpanda88
ย 
PPT
Python Training v2
ibaydan
ย 
PDF
Functions and modules in python
Karin Lagesen
ย 
PPTX
An Introduction : Python
Raghu Kumar
ย 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
ย 
PPTX
Learn Python The Hard Way Presentation
Amira ElSharkawy
ย 
PPTX
Introduction to Python External Course !!!
SlrcMalgn
ย 
PPTX
Python Programming Basics for begginners
Abishek Purushothaman
ย 
PDF
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
ย 
PPTX
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
ย 
PPTX
Functions_in_Python.pptx
krushnaraj1
ย 
PPTX
Unit 2function in python.pptx
vishnupriyapm4
ย 
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
ย 
PDF
Using Python Libraries.pdf
SoumyadityaDey
ย 
PDF
Python Modules, Packages and Libraries
Venugopalavarma Raja
ย 
PPTX
Python module 3, b.tech 5th semester ppt
course5325
ย 
PPTX
lakshya's ppt python for final final.pptx
krishan123sharma123
ย 
PPTX
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
ย 
PDF
Introduction To Programming with Python
Sushant Mane
ย 
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
ย 
Python Basics
tusharpanda88
ย 
Python Training v2
ibaydan
ย 
Functions and modules in python
Karin Lagesen
ย 
An Introduction : Python
Raghu Kumar
ย 
Unit 2function in python.pptx
vishnupriyapm4
ย 
Learn Python The Hard Way Presentation
Amira ElSharkawy
ย 
Introduction to Python External Course !!!
SlrcMalgn
ย 
Python Programming Basics for begginners
Abishek Purushothaman
ย 
Functions_in_Python.pdf text CBSE class 12
JAYASURYANSHUPEDDAPA
ย 
CLASS-11 & 12 ICT PPT Functions in Python.pptx
seccoordpal
ย 
Functions_in_Python.pptx
krushnaraj1
ย 
Unit 2function in python.pptx
vishnupriyapm4
ย 
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
ย 
Using Python Libraries.pdf
SoumyadityaDey
ย 
Python Modules, Packages and Libraries
Venugopalavarma Raja
ย 
Python module 3, b.tech 5th semester ppt
course5325
ย 
lakshya's ppt python for final final.pptx
krishan123sharma123
ย 
Python-Certification-Training-Day-1-2.pptx
muzammildev46gmailco
ย 
Introduction To Programming with Python
Sushant Mane
ย 

More from MuhammadIfitikhar (10)

PPTX
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
ย 
PPTX
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
ย 
PDF
Python course slides topic objects in python
MuhammadIfitikhar
ย 
PDF
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
ย 
PDF
Python Slides conditioanls and control flow
MuhammadIfitikhar
ย 
PDF
Python course lecture slides specifications and testing
MuhammadIfitikhar
ย 
PDF
Python Lecture Slides topic strings handling
MuhammadIfitikhar
ย 
PDF
Python Course Lecture Defining Functions
MuhammadIfitikhar
ย 
PDF
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
ย 
PDF
Course Overview Python Basics Course Slides
MuhammadIfitikhar
ย 
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
ย 
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
ย 
Python course slides topic objects in python
MuhammadIfitikhar
ย 
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
ย 
Python Slides conditioanls and control flow
MuhammadIfitikhar
ย 
Python course lecture slides specifications and testing
MuhammadIfitikhar
ย 
Python Lecture Slides topic strings handling
MuhammadIfitikhar
ย 
Python Course Lecture Defining Functions
MuhammadIfitikhar
ย 
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
ย 
Course Overview Python Basics Course Slides
MuhammadIfitikhar
ย 
Ad

Recently uploaded (20)

PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
PDF
Mastering VPC Architecture Build for Scale from Day 1.pdf
Devseccops.ai
ย 
PPTX
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
ย 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
ย 
PDF
The Next-Gen HMIS Software AI, Blockchain & Cloud for Housing.pdf
Prudence B2B
ย 
PPTX
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
PDF
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
ย 
PPTX
declaration of Variables and constants.pptx
meemee7378
ย 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
PDF
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
ย 
PDF
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
ย 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
ย 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
ย 
Mastering VPC Architecture Build for Scale from Day 1.pdf
Devseccops.ai
ย 
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
ย 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
ย 
The Next-Gen HMIS Software AI, Blockchain & Cloud for Housing.pdf
Prudence B2B
ย 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
ย 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
ย 
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
ย 
declaration of Variables and constants.pptx
meemee7378
ย 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
ย 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
ย 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
ย 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
ย 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
ย 
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
ย 
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
ย 
Automated Test Case Repair Using Language Models
Lionel Briand
ย 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack โ€“ Licensing...
Shane Coughlan
ย 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
ย 
Ad

Python Course Functions and Modules Slides

  • 2. Announcements Reminders Optional Videos 8/30/22 Functions & Modules 2 โ€ข Grading AI quiz today ยง Take now if have not ยง If make 9/10, are okay ยง Else must retake โ€ข Survey 0 is still open ยง For participation score ยง Must complete them โ€ข Must access in CMS โ€ข Today ยง Lesson 3: Function Calls ยง Lesson 4: Modules ยง Videos 4.1-4.5 โ€ข Next Time ยง Video 4.6 of Lesson 4 ยง Lesson 5: Function Defs โ€ข Also skim Python API
  • 3. 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,โ€ฆ) โ€ข Arguments are ยง Expressions, not values ยง Separated by commas function name argument 8/30/22 Functions & Modules 3
  • 4. Built-In Functions โ€ข Python has several math functions ยง round(2.34) ยง 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 Arguments can be any expression 8/30/22 Functions & Modules 4
  • 5. 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() ยง Quit function: quit() โ€ข How know which one? Read documentation. These take no arguments 8/30/22 Functions & Modules 5
  • 6. 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
  • 7. 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
  • 8. 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 8 To access math functions Functions require math prefix!
  • 9. 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 9 To access math functions Functions require math prefix! Module has variables too!
  • 10. 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 โ€ข os ยง Information about your OS ยง Cross-platform features โ€ข random ยง Generate random numbers ยง Can pick any distribution โ€ข introcs ยง Custom module for the course ยง Will be used a lot at start 8/30/22 Functions & Modules 10 To access math functions Functions require math prefix! Module has variables too! Other Modules
  • 11. Using the from Keyword >>> import math >>> math.pi 3.141592653589793 >>> from math import pi >>> pi 3.141592653589793 >>> from math import * >>> cos(pi) -1.0 โ€ข Be careful using from! โ€ข Using import is safer ยง Modules might conflict (functions w/ same name) ยง What if import both? โ€ข Example: Turtles ยง Used in Assignment 4 ยง 2 modules: turtle, introcs ยง Both have func. Turtle() 8/30/22 Functions & Modules 11 Must prefix with module name No prefix needed for variable pi No prefix needed for anything in math
  • 12. Reading the Python Documentation 8/30/22 Functions & Modules 12 http://docs.python.org/3/library
  • 13. Reading the Python Documentation 8/30/22 Functions & Modules 13 Function name Possible arguments What the function evaluates to Module http://docs.python.org/3/library
  • 14. Interactive Shell vs. Modules 8/30/22 Functions & Modules 14 โ€ข Write in a code editor ยง We use VS Code ยง But anything will work โ€ข Load module with import โ€ข Launch in command line โ€ข Type each line separately โ€ข Python executes as you type
  • 15. 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
  • 16. 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 16 Single line comment (not executed)
  • 17. 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 17 Single line comment (not executed) Docstring (note the Triple Quotes) Acts as a multiple-line comment Useful for code documentation
  • 18. 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 18 Single line comment (not executed) Docstring (note the Triple Quotes) Acts as a multiple-line comment Useful for code documentation Commands Executed on import
  • 19. 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 19 Single line comment (not executed) Docstring (note the Triple Quotes) Acts as a multiple-line comment Useful for code documentation Commands Executed on import Not a command. import ignores this
  • 20. 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 Python Shell >>> import module >>> 8/30/22 Functions & Modules 20 x
  • 21. 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 Python Shell >>> import module >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined 8/30/22 Functions & Modules 21 x
  • 22. 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 Python Shell >>> import module >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> 9 8/30/22 Functions & Modules 22 x module.x โ€œModule dataโ€ must be prefixed by module name
  • 23. 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 Python Shell >>> import module >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> 9 >>> 8/30/22 Functions & Modules 23 x module.x help(module) โ€œModule dataโ€ must be prefixed by module name Prints docstring and module contents
  • 24. Modules Must be in Working Directory! 8/30/22 Functions & Modules 24 Module you want is in this folder
  • 25. Modules Must be in Working Directory! 8/30/22 Functions & Modules 25 Module you want is in this folder Have to navigate to folder BEFORE running Python
  • 26. Modules vs. Scripts Module โ€ข Provides functions, variables ยง Example: temp.py โ€ข import it into Python shell >>> import temp >>> temp.to_fahrenheit(100) 212.0 >>> Script โ€ข Behaves like an application ยง Example: helloApp.py โ€ข Run it from command line: python helloApp.py 8/30/22 Functions & Modules 26
  • 27. Modules vs. Scripts Module โ€ข Provides functions, variables ยง Example: temp.py โ€ข import it into Python shell >>> import temp >>> temp.to_fahrenheit(100) 212.0 >>> Script โ€ข Behaves like an application ยง Example: helloApp.py โ€ข Run it from command line: python helloApp.py 8/30/22 Functions & Modules 27 Files look the same. Difference is how you use them.
  • 28. Scripts and Print Statements module.py """ A simple module. This file shows how modules work """ # This is a comment x = 1+2 x = 3*x x script.py """ A simple script. This file shows why we use print """ # This is a comment x = 1+2 x = 3*x print(x) 8/30/22 Functions & Modules 28
  • 29. Scripts and Print Statements module.py """ A simple module. This file shows how modules work """ # This is a comment x = 1+2 x = 3*x x script.py """ A simple script. This file shows why we use print """ # This is a comment x = 1+2 x = 3*x print(x) 8/30/22 Functions & Modules 29 Only difference
  • 30. Scripts and Print Statements module.py script.py 8/30/22 Functions & Modules 30 โ€ข Looks like nothing happens โ€ข Python did the following: ยง Executed the assignments ยง Skipped the last line (โ€˜xโ€™ is not a statement) โ€ข We see something this time! โ€ข Python did the following: ยง Executed the assignments ยง Executed the last line (Prints the contents of x)
  • 31. Scripts and Print Statements module.py script.py 8/30/22 Functions & Modules 31 โ€ข Looks like nothing happens โ€ข Python did the following: ยง Executed the assignments ยง Skipped the last line (โ€˜xโ€™ is not a statement) โ€ข We see something this time! โ€ข Python did the following: ยง Executed the assignments ยง Executed the last line (Prints the contents of x) When you run a script, only statements are executed
  • 32. User Input >>> input('Type something') Type somethingabc 'abc' >>> input('Type something: ') Type something: abc 'abc' >>> x = input('Type something: ') Type something: abc >>> x 'abc' No space after the prompt. Proper space after prompt. Assign result to variable. 8/30/22 Functions & Modules 32
  • 33. Making a Script Interactive """ A script showing off input. This file shows how to make a script interactive. """ x = input("Give me a something: ") print("You said: "+x) [wmw2] folder> python script.py Give me something: Hello You said: Hello [wmw2] folder> python script.py Give me something: Goodbye You said: Goodbye [wmw2] folder> 8/30/22 Functions & Modules 33 Not using the interactive shell
  • 34. Numeric Input โ€ข input returns a string ยง Even if looks like int ยง It cannot know better โ€ข You must convert values ยง int(), float(), bool(), etc. ยง Error if cannot convert โ€ข One way to program ยง But it is a bad way ยง Cannot be automated >>> x = input('Number: ') Number: 3 >>> x '3' >>> x + 1 TypeError: must be str, not int >>> x = int(x) >>> x+1 4 Value is a string. Must convert to int. 8/30/22 Functions & Modules 34
  • 35. Next Time: Defining Functions Function Call โ€ข Command to do the function โ€ข Can put it anywhere ยง In the Python shell ยง Inside another module Function Definition โ€ข Command to do the function โ€ข Belongs inside a module 8/30/22 Functions & Modules 35
  • 36. Next Time: Defining Functions Function Call โ€ข Command to do the function โ€ข Can put it anywhere ยง In the Python shell ยง Inside another module Function Definition โ€ข Command to do the function โ€ข Belongs inside a module 8/30/22 Functions & Modules 36 Can call as many times as you want But only define function ONCE arguments inside ()
  • 37. Clickers (If Time) 8/30/22 Functions & Modules 37
  • 39. Reading isclose โ€ข Assume that we type >>> import weird >>> isclose(2.000005,2.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 39 A: True B: False C: An error! D: Nothing! E: I do not know
  • 40. Reading isclose โ€ข Assume that we type >>> import weird >>> isclose(2.000005,2.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 40 A: True B: False C: An error! D: Nothing! E: I do not know CORRECT
  • 41. Reading isclose โ€ข Assume that we type >>> import weird >>> weird.isclose(2.000005,2.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 41 A: True B: False C: An error! D: Nothing! E: I do not know
  • 42. Reading isclose โ€ข Assume that we type >>> import weird >>> weird.isclose(2.000005,2.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 42 A: True B: False C: An error! D: Nothing! E: I do not know CORRECT
  • 43. Reading isclose โ€ข Assume that we type >>> import weird >>> weird.isclose(2.0,3.0,4.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 43 A: True B: False C: An error! D: Nothing! E: I do not know
  • 44. Reading isclose โ€ข Assume that we type >>> import weird >>> weird.isclose(2.0,3.0,4.0) โ€ข What is the result (value)? 8/30/22 Functions & Modules 44 A: True B: False C: An error! D: Nothing! E: I do not know CORRECT