Download CS 130R: Programming in Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS 130R: Programming in Python
#12: Modules
Reading: Chapters 10,11
Contents
• Modules
– math
– matplotlib
– tkinter
– graphics
Modules
How do I get my definitions of functions and constants to
many places, in many programs?
Answer: module
A module is a Python file that (generally) has only definitions of
constants, functions, and classes.
Once created a module can be imported in your code. That means
you do not have to re-write code for these functions that are in
the module and you can just use them.
WHY? A very simple lesson, but now you can organize your
programs very neatly.
Modules
fileA.py
def func1():
…
def func2():
…
# main
print (…)
mymodule.py
fileA.py
fileB.py
common
functions
def func1():
…
def func2():
…
# main
aa = 10
instead,
use a module
def func1():
…
def func2():
…
fileB.py
import mymodule
import mymodule
# main
print (…)
# main
aa = 10
Modules
Importing modules:
import module_name
Imports the entire module, i.e. all functions and constants
defined inside the module.
To use only a specific function from a module:
import mymodule
aa = mymodule.functionAA()
Or, in a shorter way:
from mymodule import functionAA
Modules
Example – a module fibo.py implementing Fibonacci
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Modules
# in myfile.py
import fibo
fibo.fib(1000)
fibo.fib2(100)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
OR same thing
# in myfile.py
from fibo import fib, fib2
fib(1000)
fib2(100)
Math module
import math
print math.sqrt(10)
from math import sin
from math import cos
from math import sqrt
print sqrt(10)
Math module
# quadratic.py
# Program to calculate real roots
# of a quadratic equation
import math
a, b, c = input("Enter the coefficients (a, b, c): ")
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("\nThe solutions are:", root1, root2)
Matplotlib
Matplotlib is a Python 2D plotting library which
produces publication quality figures in a
variety of hardcopy formats and interactive
environments across platforms.
You can generate plots, histograms, power
spectra, bar charts, errorcharts, scatterplots,
etc, with just a few lines of code
Matplotlib
from pylab import *
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
plot(t, s, linewidth=1.0)
xlabel('time (s)')
ylabel('voltage (mV)')
title('About as simple as it gets, folks')
grid(True)
savefig("test.png")
show()
Matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
Matplotlib
• Examples and full documentation
http://matplotlib.org
Modules:
• pylab
• mplot3d
• numpy
• scipy
• …
Tkinter
• Tkinter is an acronym for "Tk interface".
Tk was developed as a GUI extension
• Tutorial:
http://www.pythonware.com/library/tkinter/introduction/index.htm
• Tk provides the following widgets:
–
–
–
–
–
–
–
–
–
–
–
–
–
–
Button, checkbutton, radiobutton, menubutton
Combobox, listbox, spinbox
entry
Frame, label, labelframe, canvas,
menu
message
notebook
tk_optionMenu
panedwindow
progressbar
scale
scrollbar
separator
Text, treeview
Tkinter
# a hello.py script that shows “Hello Tkinter!” in a
window
from Tkinter import *
# if you are working under Python 3, comment the
previous line and comment out the following line
#from tkinter import *
root = Tk()
w = Label(root, text="Hello Tkinter!")
w.pack()
root.mainloop()
Tkinter
import Tkinter as tk
counter = 0
def counter_label(label):
counter = 0
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
Graphics
• Graphics make programming more fun for
many people.
• For reference:
http://mcsp.wartburg.edu/zelle/python/graphic
s/graphics/index.html
Graphics
from graphics import *
def main():
win = GraphWin('Draw a Triangle', 350, 350)
win.yUp() # right side up coordinates win.setBackground('yellow')
message = Text(Point(win.getWidth()/2, 30), 'Click on three points') message.setTextColor('red')
message.setStyle('italic')
message.setSize(20)
message.draw(win) # Get and draw three vertices of triangle
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
vertices = [p1, p2, p3] # Use Polygon object to draw the triangle
triangle = Polygon(vertices)
triangle.setFill('gray')
triangle.setOutline('cyan')
triangle.setWidth(4) # width of boundary line
triangle.draw(win)
message.setText('Click anywhere to quit') # change text message
win.getMouse()
win.close()
main()