Bind Key action: Return
from Tkinter import * root = Tk() def greet(*ignore): print 'Hello World' root.bind('', greet) root.mainloop()
Bind Key action: Return
from Tkinter import * root = Tk() def greet(*ignore): print 'Hello World' root.bind('', greet) root.mainloop()
import csv spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', quotechar='|', quoting=QUOTE_MINIMAL) spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
import csv spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') for row in spamReader: print ', '.join(row) # Spam, Spam, Spam, Spam, Spam, Baked Beans # Spam, Lovely Spam, Wonderful Spam
Here is a Python Program to create an HTML message with an alternative plain text version
#!/usr/bin/env python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\Hi!
""" # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit()
How are you?
Here is the link you wanted.
Here is a Python Program to send the entire contents of a directory as an email message
#!/usr/bin/env python """Send the contents of a directory as a MIME message.""" import os import sys import smtplib # For guessing MIME type based on file name extension import mimetypes from optparse import OptionParser from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText COMMASPACE = ', ' def main(): parser = OptionParser(usage="""\ Send the contents of a directory as a MIME message. Usage: %prog [options] Unless the -o option is given, the email is sent by forwarding to your local SMTP server, which then does the normal delivery process. Your local machine must be running an SMTP server. """) parser.add_option('-d', '--directory', type='string', action='store', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_option('-o', '--output', type='string', action='store', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_option('-s', '--sender', type='string', action='store', metavar='SENDER', help='The value of the From: header (required)') parser.add_option('-r', '--recipient', type='string', action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') opts, args = parser.parse_args() if not opts.sender or not opts.recipients: parser.print_help() sys.exit(1) directory = opts.directory if not directory: directory = '.' # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory) outer['To'] = COMMASPACE.join(opts.recipients) outer['From'] = opts.sender outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) # Now send or store the message composed = outer.as_string() if opts.output: fp = open(opts.output, 'w') fp.write(composed) fp.close() else: s = smtplib.SMTP('localhost') s.sendmail(opts.sender, opts.recipients, composed) s.quit() if __name__ == '__main__': main()
Here is a Python Program to send a MIME message containing a bunch of family pictures that may be residing in a directory
# Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(me, family, msg.as_string()) s.quit()
Here is a Python Program to create and send a simple text message:
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. fp = open(textfile, 'rb') # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit()
import sys def open_file(file_name, mode): """Open a file.""" try: the_file = open(file_name, mode) except(IOError), e: print "Unable to open the file", file_name, "Ending program.\n", e raw_input("\n\nPress the enter key to exit.") sys.exit() else: return the_file def next_line(the_file): """Return next line from the trivia file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line trivia_file = open_file("trivia.txt", "r") title = next_line(trivia_file) trivia_file.close()
Here is a Python Program to Close the File
# Open files consume system resources, and depending on the file mode, # other programs may not be able to access them. # It's important to close files as soon as you're finished with them, as shown in # f = open("/music/_singles/kairo.mp3", "rb") print f.closed f.close() print f print f.closed # The closed attribute of a file object indicates whether the object has # a file open or not. In this case, the file is still open (closed is False).
f = open("/music/_singles/kairo.mp3", "rb") print f print f.tell() f.seek(-128, 2) print f.tell() tagData = f.read(128) print tagData print f.tell()
# The os.path module has several functions for manipulating files and directories. # Here, we'll look at handling pathnames and listing the contents of a directory. import os print os.path.join("c:\\yourfolder\\", "yourfile.txt") print os.path.join("c:\\yourfolder", "yourfile.txt") os.path.expanduser("~") print os.path.join(os.path.expanduser("~"), "Python") # os.path is a reference to a module-which module depends on your platform. Just # as getpass encapsulates differences between platforms by setting getpass to a # platform-specific function, os encapsulates differences between platforms by # setting path to a platform-specific module.
Here is a Python Program to Change Directory
import os os.chdir('/server/accesslogs') #Be sure to use the "import os" style instead of "from os import *". This will keep #os.open() from shadowing the builtin open() function which operates much #differently.
import os os.listdir("c:\\") import glob glob.glob('c:\\*.mp3') glob.glob('c:\\*.mp3') glob.glob('c:\\c\\*\\*.mp3')
import os os.listdir("c:\\") dirname = "c:\\" os.listdir(dirname) print [f for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f))] [3] print [f for f in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, f))] [4]
import smtplib #to send the email to concerned persons def Send_Mail(TEXT): sender = 'sender_mail_address in single quotes ' receivers = ['firstperson mailaddress in single quotes ','secondperson mail address in single quotes '] # Prepare actual message message = "Subject:ALERT!\n" message=message+TEXT try: smtpObj = smtplib.SMTP(' SMTP MAIL SERVER in single quotes ',25) smtpObj.sendmail(sender, receivers, message) smtpObj.close() except smtplib.SMTPConnectError: print "Error: unable to send email by connect" except smtplib.SMTPException: print "Error: unable to send email" #main Send_Mail("enter you text here..")
import MySQLdb db= MySQLdb.connect(host="localhost", user="python-test", passwd="python", db="python-test") try: title = raw_input("Please enter a book title: ") if title == "" : exit author = raw_input("Please enter the author's name: ") pubdate = int( raw_input("Enter the publication year: ") ) except: print "Invalid value" exit print "Title: [" + title + "]" print "Author: ["+ author + "]" print "Publication Date: " + str(pubdate) cursor = db.cursor() stmt = "INSERT INTO Books (BookName, BookAuthor, PublicationDate) VALUES ('" stmt = stmt + title stmt = stmt + "', '" stmt = stmt + author stmt = stmt + "', " stmt = stmt + str(pubdate) stmt = stmt + ")" cursor.execute(stmt) print "Record added!" cursor.close () db.commit ()
import MySQLdb import MySQLdb.cursors def get_column_name( data, prompt, names ) : value=-1 while value == -1: idx = 1 for col in data : print str(idx) + ": " + col names.append( col ) idx = idx + 1 value = int( raw_input(prompt) ) if value < 1 or value >= idx : value = -1 return value conn = MySQLdb.Connect( host='localhost', user='python-test', passwd='python', db='python-test') cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) cursor.execute("SELECT * FROM books") data = cursor.fetchone() names = [] old_value = get_column_name( data, "Which column do you want to change records for? ", names ) names = [] new_value = get_column_name( data, "Which column do you want to change records to? ", names ) old_val = raw_input("What value do you want to change for " + names[old_value-1] + ": ") new_val = raw_input("What value do you want to change to for " + names[new_value-1] + ": ") stmt = "UPDATE books SET " + names[new_value-1] + " = '"+ new_val + "' WHERE " + names[old_value-1] + " = '" + old_val + "'" print stmt cursor.execute(stmt) print "Rows affected: " + str(cursor.rowcount) cursor.close() conn.commit() conn.close()
import MySQLdb db= MySQLdb.connect(host="localhost", user="python-test", passwd="python", db="python-test") cursor = db.cursor() stmt = "SELECT * from books" cursor.execute(stmt) rows = cursor.fetchall () for row in rows: print "Row: " for col in row : print "Column: %s" % (col) print "End of Row" print "Number of rows returned: %d" % cursor.rowcount cursor.close() db.close()
#/* #Python and Tkinter Programming #John E. Grayson #ISBN: 1884777813 #Publisher: Manning #*/ from Tkinter import * SQUARE = 1 ROUND = 2 ARROW = 3 POINT_DOWN = 0 POINT_UP = 1 POINT_RIGHT = 2 POINT_LEFT = 3 STATUS_OFF = 1 STATUS_ON = 2 STATUS_WARN = 3 STATUS_ALARM = 4 STATUS_SET = 5 class DummyClass: pass Color = DummyClass() Color.PANEL = '#545454' Color.OFF = '#656565' Color.ON = '#00FF33' Color.WARN = '#ffcc00' Color.ALARM = '#ff4422' class LED: def __init__(self, master=None, width=25, height=25, appearance=FLAT, status=STATUS_ON, bd=1, bg=None, shape=SQUARE, outline="", blink=0, blinkrate=1, orient=POINT_UP, takefocus=0): # preserve attributes self.master = master self.shape = shape self.onColor = Color.ON self.offColor = Color.OFF self.alarmColor = Color.ALARM self.warningColor = Color.WARN self.specialColor = '#00ffdd' self.status = status self.blink = blink self.blinkrate = int(blinkrate) self.on = 0 self.onState = None if not bg: bg = Color.PANEL ## Base frame to contain light self.frame=Frame(master, relief=appearance, bg=bg, bd=bd, takefocus=takefocus) basesize = width d = center = int(basesize/2) if self.shape == SQUARE: self.canvas=Canvas(self.frame, height=height, width=width, bg=bg, bd=0, highlightthickness=0) self.light=self.canvas.create_rectangle(0, 0, width, height, fill=Color.ON) elif self.shape == ROUND: r = int((basesize-2)/2) self.canvas=Canvas(self.frame, width=width, height=width, highlightthickness=0, bg=bg, bd=0) if bd > 0: self.border=self.canvas.create_oval(center-r, center-r, center+r, center+r) r = r - bd self.light=self.canvas.create_oval(center-r-1, center-r-1, center+r, center+r, fill=Color.ON, outline=outline) else: # Default is an ARROW self.canvas=Canvas(self.frame, width=width, height=width, highlightthickness=0, bg=bg, bd=0) x = d y = d if orient == POINT_DOWN: self.light=self.canvas.create_polygon(x-d,y-d, x,y+d, x+d,y-d, x-d,y-d, outline=outline) elif orient == POINT_UP: self.light=self.canvas.create_polygon(x,y-d, x-d,y+d, x+d,y+d, x,y-d, outline=outline) elif orient == POINT_RIGHT: self.light=self.canvas.create_polygon(x-d,y-d, x+d,y, x-d,y+d, x-d,y-d, outline=outline) elif orient == POINT_LEFT: self.light=self.canvas.create_polygon(x-d,y, x+d,y+d, x+d,y-d, x-d,y, outline=outline) self.canvas.pack(side=TOP, fill=X, expand=NO) self.update() def turnon(self): self.status = STATUS_ON if not self.blink: self.update() def turnoff(self): self.status = STATUS_OFF if not self.blink: self.update() def alarm(self): self.status = STATUS_ALARM if not self.blink: self.update() def warn(self): self.status = STATUS_WARN if not self.blink: self.update() def set(self, color): self.status = STATUS_SET self.specialColor = color self.update() def blinkon(self): if not self.blink: self.blink = 1 self.onState = self.status self.update() def blinkoff(self): if self.blink: self.blink = 0 self.status = self.onState self.onState = None self.on = 0 self.update() def blinkstate(self, blinkstate): if blinkstate: self.blinkon() else: self.blinkoff() def update(self): # First do the blink, if set to blink if self.blink: if self.on: if not self.onState: self.onState = self.status self.status = STATUS_OFF self.on = 0 else: if self.onState: self.status = self.onState # Current ON color self.on = 1 if self.status == STATUS_ON: self.canvas.itemconfig(self.light, fill=self.onColor) elif self.status == STATUS_OFF: self.canvas.itemconfig(self.light, fill=self.offColor) elif self.status == STATUS_WARN: self.canvas.itemconfig(self.light, fill=self.warningColor) elif self.status == STATUS_SET: self.canvas.itemconfig(self.light, fill=self.specialColor) else: self.canvas.itemconfig(self.light, fill=self.alarmColor) self.canvas.update_idletasks() if self.blink: self.frame.after(self.blinkrate * 1000, self.update) if __name__ == '__main__': class TestLEDs(Frame): def __init__(self, parent=None): # List of Colors and Blink On/Off states = [(STATUS_OFF, 0), (STATUS_ON, 0), (STATUS_WARN, 0), (STATUS_ALARM, 0), (STATUS_SET, 0), (STATUS_ON, 1), (STATUS_WARN, 1), (STATUS_ALARM, 1), (STATUS_SET, 1)] # List of LED types to display, # with sizes and other attributes leds = [(ROUND, 25, 25, FLAT, 0, None, ""), (ROUND, 15, 15, RAISED, 1, None, ""), (SQUARE, 20, 20, SUNKEN, 1, None, ""), (SQUARE, 8, 8, FLAT, 0, None, ""), (SQUARE, 8, 8, RAISED, 1, None, ""), (SQUARE, 16, 8, FLAT, 1, None, ""), (ARROW, 14, 14, RIDGE, 1, POINT_UP, ""), (ARROW, 14, 14, RIDGE, 0, POINT_RIGHT, ""), (ARROW, 14, 14, FLAT, 0, POINT_DOWN, "white")] Frame.__init__(self) # Do superclass init self.pack() self.master.title('LED Example - Stage 1') # Iterate for each type of led for shape, w, h, app, bd, orient, outline in leds: frame = Frame(self, bg=Color.PANEL) frame.pack(anchor=N, expand=YES, fill=X) # Iterate for selected states for state, blink in states: LED(frame, shape=shape, status=state, width=w, height=h, appearance=app, orient=orient, blink=blink, bd=bd, outline=outline).frame.pack(side=LEFT, expand=YES, padx=1, pady=1) TestLEDs().mainloop()
from Tkinter import * import Pmw, string class SLabel(Frame): """ SLabel defines a 2-sided label within a Frame. The left hand label has blue letters the right has white letters """ def __init__(self, master, leftl, rightl): Frame.__init__(self, master, bg='gray40') self.pack(side=LEFT, expand=YES, fill=BOTH) Label(self, text=leftl, fg='steelblue1', font=("arial", 6, "bold"), width=5, bg='gray40').pack( side=LEFT, expand=YES, fill=BOTH) Label(self, text=rightl, fg='white', font=("arial", 6, "bold"), width=1, bg='gray40').pack( side=RIGHT, expand=YES, fill=BOTH) class Key(Button): def __init__(self, master, font=('arial', 8, 'bold'), fg='white',width=5, borderwidth=5, **kw): kw['font'] = font kw['fg'] = fg kw['width'] = width kw['borderwidth'] = borderwidth apply(Button.__init__, (self, master), kw) self.pack(side=LEFT, expand=NO, fill=NONE) class Calculator(Frame): def __init__(self, parent=None): Frame.__init__(self, bg='gray40') self.pack(expand=YES, fill=BOTH) self.master.title('Tkinter Toolkit TT-42') self.master.iconname('Tk-42') self.calc = Evaluator() # This is our evaluator self.buildCalculator() # Build the widgets # This is an incomplete dictionary - a good exercise! self.actionDict = {'second': self.doThis, 'mode': self.doThis, 'delete': self.doThis, 'alpha': self.doThis, 'stat': self.doThis, 'math': self.doThis, 'matrix': self.doThis, 'program': self.doThis, 'vars': self.doThis, 'clear': self.clearall, 'sin': self.doThis, 'cos': self.doThis, 'tan': self.doThis, 'up': self.doThis, 'X1': self.doThis, 'X2': self.doThis, 'log': self.doThis, 'ln': self.doThis, 'store': self.doThis, 'off': self.turnoff, 'neg': self.doThis, 'enter': self.doEnter, } self.current = "" def doThis(self,action): print '"%s" has not been implemented' % action def turnoff(self, *args): self.quit() def clearall(self, *args): self.current = "" self.display.component('text').delete(1.0, END) def doEnter(self, *args): result = self.calc.runpython(self.current) if result: self.display.insert(END, '\n') self.display.insert(END, '%s\n' % result, 'ans') self.current = "" def doKeypress(self, event): key = event.char if not key in ['\b']: self.current = self.current + event.char if key == '\b': self.current = self.current[:-1] def keyAction(self, key): self.display.insert(END, key) self.current = self.current + key def evalAction(self, action): try: self.actionDict[action](action) except KeyError: pass def buildCalculator(self): FUN = 1 # Designates a Function KEY = 0 # Designates a Key KC1 = 'gray30' # Dark Keys KC2 = 'gray50' # Light Keys KC3 = 'steelblue1' # Light Blue Key KC4 = 'steelblue' # Dark Blue Key keys = [ [('2nd', '', '', KC3, FUN, 'second'), # Row 1 ('Mode', 'Quit', '', KC1, FUN, 'mode'), ('Del', 'Ins', '', KC1, FUN, 'delete'), ('Alpha','Lock', '', KC2, FUN, 'alpha'), ('Stat', 'List', '', KC1, FUN, 'stat')], [('Math', 'Test', 'A', KC1, FUN, 'math'), # Row 2 ('Mtrx', 'Angle','B', KC1, FUN, 'matrix'), ('Prgm', 'Draw', 'C', KC1, FUN, 'program'), ('Vars', 'YVars','', KC1, FUN, 'vars'), ('Clr', '', '', KC1, FUN, 'clear')], [('X-1', 'Abs', 'D', KC1, FUN, 'X1'), # Row 3 ('Sin', 'Sin-1','E', KC1, FUN, 'sin'), ('Cos', 'Cos-1','F', KC1, FUN, 'cos'), ('Tan', 'Tan-1','G', KC1, FUN, 'tan'), ('^', 'PI', 'H', KC1, FUN, 'up')], [('X2', 'Root', 'I', KC1, FUN, 'X2'), # Row 4 (',', 'EE', 'J', KC1, KEY, ','), ('(', '{', 'K', KC1, KEY, '('), (')', '}', 'L', KC1, KEY, ')'), ('/', '', 'M', KC4, KEY, '/')], [('Log', '10x', 'N', KC1, FUN, 'log'), # Row 5 ('7', 'Un-1', 'O', KC2, KEY, '7'), ('8', 'Vn-1', 'P', KC2, KEY, '8'), ('9', 'n', 'Q', KC2, KEY, '9'), ('X', '[', 'R', KC4, KEY, '*')], [('Ln', 'ex', 'S', KC1, FUN, 'ln'), # Row 6 ('4', 'L4', 'T', KC2, KEY, '4'), ('5', 'L5', 'U', KC2, KEY, '5'), ('6', 'L6', 'V', KC2, KEY, '6'), ('-', ']', 'W', KC4, KEY, '-')], [('STO', 'RCL', 'X', KC1, FUN, 'store'), # Row 7 ('1', 'L1', 'Y', KC2, KEY, '1'), ('2', 'L2', 'Z', KC2, KEY, '2'), ('3', 'L3', '', KC2, KEY, '3'), ('+', 'MEM', '"', KC4, KEY, '+')], [('Off', '', '', KC1, FUN, 'off'), # Row 8 ('0', '', '', KC2, KEY, '0'), ('.', ':', '', KC2, KEY, '.'), ('(-)', 'ANS', '?', KC2, FUN, 'neg'), ('Enter','Entry','', KC4, FUN, 'enter')]] self.display = Pmw.ScrolledText(self, hscrollmode='dynamic', vscrollmode='dynamic', hull_relief='sunken', hull_background='gray40', hull_borderwidth=10, text_background='honeydew4', text_width=16, text_foreground='black', text_height=6, text_padx=10, text_pady=10, text_relief='groove', text_font=('arial', 12, 'bold')) self.display.pack(side=TOP, expand=YES, fill=BOTH) self.display.tag_config('ans', foreground='white') self.display.component('text').bind('', self.doKeypress) self.display.component('text').bind(' ', self.doEnter) for row in keys: rowa = Frame(self, bg='gray40') rowb = Frame(self, bg='gray40') for p1, p2, p3, color, ktype, func in row: if ktype == FUN: a = lambda s=self, a=func: s.evalAction(a) else: a = lambda s=self, k=func: s.keyAction(k) SLabel(rowa, p2, p3) Key(rowb, text=p1, bg=color, command=a) rowa.pack(side=TOP, expand=YES, fill=BOTH) rowb.pack(side=TOP, expand=YES, fill=BOTH) class Evaluator: def __init__(self): self.myNameSpace = {} self.runpython("from math import *") def runpython(self, code): try: return 'eval(code, self.myNameSpace, self.myNameSpace)' except SyntaxError: try: exec code in self.myNameSpace, self.myNameSpace except: return 'Error' Calculator().mainloop()
from Tkinter import * def frame(root, side): w = Frame(root) w.pack(side=side, expand=YES, fill=BOTH) return w def button(root, side, text, command=None): w = Button(root, text=text, command=command) w.pack(side=side, expand=YES, fill=BOTH) return w class Calculator(Frame): def __init__(self): Frame.__init__(self) self.option_add('*Font', 'Verdana 12 bold') self.pack(expand=YES, fill=BOTH) self.master.title('Simple Calculator') self.master.iconname("calc1") display = StringVar() Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH) for key in ("123", "456", "789", "-0."): keyF = frame(self, TOP) for char in key: button(keyF, LEFT, char, lambda w=display, c=char: w.set(w.get() + c)) opsF = frame(self, TOP) for char in "+-*/=": if char == '=': btn = button(opsF, LEFT, char) btn.bind('', lambda e, s=self, w=display: s.calc(w), '+') else: btn = button(opsF, LEFT, char, lambda w=display, s=' %s '%char: w.set(w.get()+s)) clearF = frame(self, BOTTOM) button(clearF, LEFT, 'Clr', lambda w=display: w.set('')) def calc(self, display): try: display.set('eval(display.get())') except: display.set("ERROR") if __name__ == '__main__': Calculator().mainloop()
seq1 = "spam" seq2 = "scam" res = [] for x in seq1: if x in seq2: res.append(x) print res
#!/usr/bin/python import random # Using the back ticks, which convert to string. for n in range(0,5): a = random.randrange(0, 101) b = random.randrange(0, 201) print `a` + '+' + `b`, '=', `a+b` print # Using the % operator, similar to printf. for n in range(0,5): a = random.randrange(0, 101) b = random.randrange(0, 201) print '%d+%d = %d' % (a, b, a + b) print # % allows field sizes as well. for n in range(0,5): a = random.randrange(-100, 101) b = random.randrange(-50, 201) print '%4d + %4d = %4d' % (a, b, a + b) print # Some other formatting. dribble = { 'onion' : 1.4, 'squash' : 2.02, 'carrots' : 1.0, 'pixie toenails' : 43.22, 'lemon drops' : .75 } for n in dribble.keys(): print '%-15s %6.2f' % (n + ':', dribble[n])
#!/usr/bin/python # # Python program to generate a random number with commentary. # # Import is much like Java's. This gets the random number generator. import random # Generate a random integer in the range 10 to 49. i = random.randrange(10,50) print 'Your number is', i # Carefully analyze the number for important properties. if i < 20: print "That is less than 20." if i % 3 == 0: print "It is divisible by 3." elif i == 20: print "That is exactly twenty. How nice for you." else: if i % 2 == 1: print "That is an odd number." else: print "That is twice", i / 2, '.' print "Wow! That's more than 20!"
#!/usr/bin/python # Several other operations on lists. fred = [ 'Alice', 'goes', 'to', 'market' ] print 'A:', fred fred.extend([ 'with', 'Mike' ]) print 'B:', fred last = fred.pop() fred.append('Fred') print 'C:', fred print 'So much for Mike.' print 'There are', len(fred), 'items in fred.' print 'The word market is located at position', fred.index('market') fred = [ 'On', 'Tuesday,' ] + fred print 'D:', fred fred.reverse() print 'E:', fred fred.sort() print 'F:', fred
#!/usr/bin/python # A python list. fred = [ 'The', 'answer', 'to', 'your', 'question', 'is', 24 ] print 'A:', fred # Subscript, as strings. Returns an item from the list. print 'B:', fred[0], fred[2], fred[6], fred[-1], fred[-4] # Ranges create a "slice" -- a sublist. print 'C:', fred[2:5], fred[-6:-3], fred[4:5], fred[3:3] # Individual items may be replaced. fred[1] = 'response' fred[-1] = fred[-1] + 200 fred[-3] = 'query' print 'D:', fred # Assignment to slices is allowed, and can change the list size. fred[0:2] = [ 'An', 'unlikely', 'answer' ] fred[-1:-1] = [ 'a', 'conservative' ] print 'E:', fred # Sublists are allowed. mike = [ 3, 4, ['and', 'also', 'a'], 52] print 'F:', mike mike[0] = [2, '+', 1] mike[2] = 11 print 'G:', mike fred[1:3] = [fred[1:3]] fred[-1:] = [mike] print 'H:', fred print 'Fred has', len(fred), 'entries.'
#!/usr/bin/python # Use brackets for string subscripting and substrings. bozon = 'Cheer for Friday' # 0123456789012345 # Index at zero. print bozon[0], bozon[1], bozon[15] # You may not use [] on the left of an assignment, however. # Use the colon to describe ranges. The last character is not part of the # range. print bozon[0:5] + ", " + bozon[0:6] + bozon[10:16] + '!' # Defaults to first and last. print bozon[:5] + ", " + bozon[:6] + bozon[10:] + '!' # The * operator repeats strings (like x in perl). print bozon[:6] * 3 + '!' # Negatives index back from the right, the rightmost character being -1. print bozon[-1] + ' ' + bozon[-10:-6]
#!/usr/bin/python # Strings have various escapes. print "Hi\nth\ere,\thow \141\x72\145\x20you?" # Raw strings ignore them. print r"Hi\nth\ere,\thow \141\x72\145\x20you?" print # Very useful when building file paths on Windows. badpath = 'C:\that\new\stuff.txt'; print badpath path = r'C:\that\new\stuff.txt'; print path
#!/usr/bin/python # Strings in single quotes. s1 = 'I\'m single' # Double quotes are the same. You just have to end with the same character # you started with, and you don't have to escape the other one. s2 = "I'm double double" # You can create multi-line strings with triple quotes (triple double quotes # work, too.) The newlines stay in the string. s3 = '''I'm very long-winded and I really need to take up more than one line. That way I can say all the very `important' things which I must tell you. Strings like me are useful when you must print a long set of instructions, etc.''' # String literals may be concatinated by a space. s4 = 'left' "right" 'left' # Any string expression may be concatinated by a + (Java style). s5 = s1 + "\n" + s2 print s5 + '\n' + s3, "\n", s4 print 's5 has', len(s5), 'characters'
#!/usr/bin/python # Some calculations. Note the lack of semicolons. Statements end at the end # of the line. Also, variables need not start with a special symbol as in # perl and some other Unix-bred languages. fred = 18 barney = FRED = 44; # Case sensistive. bill = (fred + barney * FRED - 10) alice = 10 + bill / 100 # Integer division truncates frank = 10 + float(bill) / 100 print "fred = ", fred print "bill = ", bill print "alice = ", alice print "frank = ", frank print # Each variable on the left is assigned the corresponding value on the right. fred, alice, frank = 2*alice, fred - 1, bill + frank print "fred = ", fred print "alice = ", alice print "frank = ", frank print # Exchange w/o a temp. fred, alice = alice, fred print "fred = ", fred print "alice = ", alice print # Python allows lines to be continued by putting a backslash at the end of # the first part. fred = bill + alice + frank - \ barney print "fred =", fred print # The compiler will also combine lines when the line break in contained # in a grouping pair, such as parens. joe = 3 * (fred + bill - alice) print "joe =", fred
import random guesses_made = 0 name = raw_input('Hello! What is your name?\n') number = random.randint(1, 20) print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name) while guesses_made < 6: guess = int(raw_input('Take a guess: ')) guesses_made += 1 if guess < number: print 'Your guess is too low.' if guess > number: print 'Your guess is too high.' if guess == number: break if guess == number: print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made) else: print 'Nope. The number I was thinking of was {0}'.format(number)
import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # this code iteratively builds up a chain of # filters...slightly tricky, but ponder it a bit numbers = itertools.ifilter(prime.__rmod__, numbers) for p in iter_primes(): if p > 1000: break print p
BOARD_SIZE = 8 def under_attack(col, queens): left = right = col for r, c in reversed(queens): left, right = left - 1, right + 1 if c in (left, col, right): return True return False def solve(n): if n == 0: return [[]] smaller_solutions = solve(n - 1) return [solution+[(n,i+1)] for i in xrange(BOARD_SIZE) for solution in smaller_solutions if not under_attack(i+1, solution)] for answer in solve(BOARD_SIZE): print answer
from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting' } time_now = localtime() hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < activity_time: print activities[activity_time] break else: print 'Unknown, AFK or sleeping!'
#!/usr/bin/env python # This program adds up integers in the command line import sys try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total except ValueError: print 'Please supply integer arguments'
Bloggerized by DheTemplate.com - Main Blogger