Upload
kali
View
54
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Learning to Program With Python. Beginners’ Class 6. Topics. Modules and importing The standard library. What is a module?. It’s a . py file. There’s nothing else to it. A python file and its contents are referred to as a python module. Writing code in multiple files. - PowerPoint PPT Presentation
Citation preview
Learning to ProgramWith Python
Beginners’ Class 6
TopicsModules and importing
The standard library
What is a module?It’s a .py file.
There’s nothing else to it. A python file and its contents are referred to as a python module.
Writing code in multiple filesIt isn’t good practice to write an entire
program in a single file, unless it’s quite small.
Separate your code out logically into its separate portions and save them as separate modules.
But how can we access code from one file in another file?
The import statementIf you have a file named stuff.py, and another
file named main.py, and you want to use the contents of stuff.py inside main.py, then you simply write this at the top of main.py:
import stuff
The import statementIn order for ‘import stuff’ to work, both files
will have to be stored in the same place on your computer--- inside the same directory. If you place one in “My Documents” and another in “My Pictures”, they won’t be able to see each other, and you’ll get an ImportError.
ImportError is what you get whenever the import statement fails.
ImportError
>>> import doesnt_exist>>>Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import doesnt_existImportError: No module named 'doesnt_exist'
Placement of the import statement
The import statement can go anywhere….even inside an if statement, if you only want to import something under certain circumstances.
But in general, good practice is to always place all your import statements at the top of your file, before any other code.
Importing multiple modulesIf you wanted to import stuff.py AND morestuff.py, you could write either of the following. They are identical.
import stuff, morestuff
OR:
import stuffimport morestuff
Using code from imported modules
Let’s imagine we had defined the function calculateOdds(percent, rate) inside of our module stuff.py, which we’ve now imported into main.py.
To use it in main.py, we write:
stuff.calculateOdds(.4, 22)
Using code from imported modules
To access any functions or variables defined inside an imported module, you must write:
importedModuleName.variableName
or…
importedModuleName.functionName(arguments)
What happens when amodule is imported
At the moment a file is imported, any code inside that file is run.
Which means the functions and variables become defined.
But besides function/variable declarations, if there’s any other code, it is also run at that moment of importation.
Import exampleLet’s say this is the content of stuff.py:
def printMessage(name):print(“Hey, ” + name + “!”)
x = 3for n in range(x):
printMessage(“Bill”)
Import exampleSo when we import stuff.py in main, we see the
output:
Hey, Bill!Hey, Bill!Hey, Bill!
…because that code just got run.
And now we can use stuff.x or stuff.printMessage().
The standard libraryThe standard library is a set of modules that
come with python by default. They provide a massive amount of built-in functionality.
There are dozens of modules in the standard library. We’re going to take a look at a few basic ones.
The math modulePredictably contains a wide set of functions
related to mathematical operations.
For starters, the math module defines two constants, e and pi, so you can simply import math and refer to math.e and math.pi to get at those numbers.
math.sqrt(x)This function can be used to find a square
root.
>>> math.sqrt(10)3.1622776601683795
math.pow(x, y)This function can be used to raise a number x
to a power y.
>>> math.pow(4, 3)64.0
math.cos(x)This trigonometric function can be used to
find the cosine of a number.
>>> math.cos(40)-0.6669380616522619
There is also math.sin(x), math.tan(x), math.asin(x), math.acos(x), and math.atan(x).
math.degrees(x)This function can be used to convert radians
to degrees. There is, likewise, a math.radians(x) to do the inverse.
>>> math.degrees(3.14159)179.9998479605043
The random moduleThis module is full of functionality related to
randomness. It can be used to generate random numbers, shuffle lists, and pick elements from lists at random, among other things.
random.randint(x, y)This function will return a random integer
between x and y.
>>> random.randint(4, 100)17>>> random.randint(56, 10334)994
random.shuffle(x)This function can be used to shuffle a list. It
returns None.
>>> m = [1, 2, 3, 4, 5]>>> random.shuffle(m)>>> m[5, 2, 3, 1, 4]
random.sample(x, y)This function will return y random items from
list x.
>>> m = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]>>> randomItems = random.sample(m, 3)>>> randomItems[‘b’, ‘e’, ‘a’]
The time moduleThis module is full of functionality related to
finding out what time it is. It also contains the extremely handy sleep function, which allows you to tell the computer to do nothing for a certain amount of time.
time.asctime()Just returns a string description of the date
and time.
>>> time.asctime()'Sun Jun 8 01:01:53 2014'
time.strftime(x)Lets you format a string with whatever time
information you want.
>>> time.strftime(“The weekday is %A”)“The weekday is Sunday”>>> time.strftime(“The year is %Y and the month is %B”)“The year is 2014 and the month is June”
time.localtime()Gives you all the time information as a series
of numbers, accessible as attributes. This syntax will appear unfamiliar to you, but consider it your first brush with object oriented programming.
>>> the_time = time.localtime()>>> the_time.tm_year2014
time.sleep(x)Tell the computer to do nothing for x
seconds.
>>> time.sleep(100)>>>
That second prompt won’t appear for 100 seconds, because the function will still be holding the computer in place during that time.