29
Learning to Program With Python Beginners’ Class 6

Learning to Program With Python

  • Upload
    kali

  • View
    54

  • Download
    0

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

Page 1: Learning to Program With Python

Learning to ProgramWith Python

Beginners’ Class 6

Page 2: Learning to Program With Python

TopicsModules and importing

The standard library

Page 3: Learning to Program With Python

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.

Page 4: Learning to Program With Python

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?

Page 5: Learning to Program With Python

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

Page 6: Learning to Program With Python

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.

Page 7: Learning to Program With Python

ImportError

>>> import doesnt_exist>>>Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import doesnt_existImportError: No module named 'doesnt_exist'

Page 8: Learning to Program With Python

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.

Page 9: Learning to Program With Python

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

Page 10: Learning to Program With Python

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)

Page 11: Learning to Program With Python

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)

Page 12: Learning to Program With Python

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.

Page 13: Learning to Program With Python

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”)

Page 14: Learning to Program With Python

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().

Page 15: Learning to Program With Python

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.

Page 16: Learning to Program With Python

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.

Page 17: Learning to Program With Python

math.sqrt(x)This function can be used to find a square

root.

>>> math.sqrt(10)3.1622776601683795

Page 18: Learning to Program With Python

math.pow(x, y)This function can be used to raise a number x

to a power y.

>>> math.pow(4, 3)64.0

Page 19: Learning to Program With Python

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).

Page 20: Learning to Program With Python

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

Page 21: Learning to Program With Python

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.

Page 22: Learning to Program With Python

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

Page 23: Learning to Program With Python

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]

Page 24: Learning to Program With Python

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’]

Page 25: Learning to Program With Python

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.

Page 26: Learning to Program With Python

time.asctime()Just returns a string description of the date

and time.

>>> time.asctime()'Sun Jun 8 01:01:53 2014'

Page 27: Learning to Program With Python

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”

Page 28: Learning to Program With Python

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

Page 29: Learning to Program With Python

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.