•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 361,896 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,340 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 48617 | Replies: 139
![]() |
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
Just simple code to construct a toggle button, in this case we are using the venerable Tkinter for the GUI implementation.
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
python Syntax (Toggle Plain Text)
# make a toggle button with Tkinter from Tkinter import * toggleFlag = True def entryColor(): """toggle the entry color between white and red""" global toggleFlag if toggleFlag: e1.config(bg='red') toggleFlag = False else: e1.config(bg='white') toggleFlag = True # create the root window root = Tk() # create a button, command runs the given function when button is clicked b1 = Button(root, text="Toggle Color", command=entryColor) # pack button into root window b1.pack(fill=BOTH, expand=1) # create an entry box to color e1 = Entry(root) e1.pack(fill=BOTH, expand=1) # this allows the program to be an importable module and a runnable program if __name__ == "__main__": # start the event loop root.mainloop()
Last edited by vegaseat : Mar 1st, 2007 at 3:13 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
I have donated a fair number of code snippets to DaniWeb. Many of the snippets are written like "Almost Tutorials" concentrating on Strings, Lists, Sets, Dictionaries and so on. I think and hope that they can be a good source of information for Beginners in the Python language. Click on this ...
http://www.daniweb.com/code/python.html
For instance check the code snippet at:
http://www.daniweb.com/code/snippet354.html
It talks about class inheritance and sheds some light on object and self.
http://www.daniweb.com/code/python.html
For instance check the code snippet at:
http://www.daniweb.com/code/snippet354.html
It talks about class inheritance and sheds some light on object and self.
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
In a recent thread we looked at ways to create a multiline string. Here are a few code samples showing you how to do this, some are preference, some are cosmetic ...
BTW, the php code field seems to eat up some of the trailing \ characters, so I switched to the regular code=python field.
python Syntax (Toggle Plain Text)
# a look at multiline strings # using line continuation (\) to form one long/multiline string # complex and tough to read # (no space right after \ or an empty line following \) str1 = "The alien gasps and says, 'Oh, this is it. I will die! \n\ Tell my 2.4 million larvae that I loved them... \n\ Good-bye, cruel universe.' " # using line continuation (\) to combine three strings to one string # ignores indentations between strings, easy on the eye str2 = "The alien gasps and says, 'Oh, this is it. I will die! \n"\ "Tell my 2.4 million larvae that I loved them... \n"\ "Good-bye, cruel universe.'" # using just triple quotes, still tough to read? # note: newline characters are taken care of str3 = """The alien gasps, 'Oh, this is it. I will die! Tell my 2.4 million larvae that I loved them... Good-bye, cruel universe.' """ # using line continuation (\) and triple quotes # might be easier to read str4 = \ """The alien gasps and says, 'Oh, this is it. I will die! Tell my 2.4 million larvae that I loved them... Good-bye, cruel universe.' """ # note: indentations become part of the string str5 = """The alien gasps, 'Oh, this is it. I will die! Tell my 2.4 million larvae that I loved them... Good-bye, cruel universe.' """ # gee, one more way to do a multiline string with the + concatinator ... str6 = "The alien gasps and says, 'Oh, this is it. I will die! \n" str6 = str6 + "Tell my 2.4 million larvae that I loved them... \n" str6 = str6 + "Good-bye, cruel universe.'" # another variation using + str7 = "The alien gasps and says, 'Oh, this is it. I will die! \n" str8 = "Tell my 2.4 million larvae that I loved them... \n" str9 = "Good-bye, cruel universe.'" str10 = str7 + str8 + str9 print '-'*60 # pretty up with 60 dashes print str1 print '-'*60 print str2 print '-'*60 print str3 print '-'*60 print str4 print '-'*60 print str5 print '-'*60 print str6 print '-'*60 print str10
Last edited by vegaseat : Mar 1st, 2007 at 2:44 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
Since Python does not need type declarations, I wanted to test the numeric capacity with a program that calculates factorials since they quickly give very large numbers. I stopped at the factorial of 69 only because the line started wrapping.
This boggles my mind since it took all sorts of hoops to try this with C++ earlier in my life. In C++ the unsigned long integer fizzles out at a measly 4.3 billion. Those are only ten digits!
Here is another little number trick I picked up from one of the forums. This poor fellow wanted to do it in C, but the old compiler just couldn't handle the number of digits in the result. No sweat for Python ...
python Syntax (Toggle Plain Text)
# check the numeric range of Python with huge factorials # factorial(69) still checks out accurately! Has 98 digits in it! # 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000 def fact(n): """returns the factorial of n""" if n == 0: return 1 else: k = n*fact(n-1) return k for k in range(1, 70): print "factorial of", k,"=", fact(k)
Here is another little number trick I picked up from one of the forums. This poor fellow wanted to do it in C, but the old compiler just couldn't handle the number of digits in the result. No sweat for Python ...
python Syntax (Toggle Plain Text)
# another little number trick ... a = 111111111 # that's nine ones print "%d * %d = %d" % (a, a, a * a) # result = 12345678987654321
Last edited by vegaseat : Mar 1st, 2007 at 2:45 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
This shows you how to mimic a C struct type with an empty Python class ...
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
python Syntax (Toggle Plain Text)
# create a structure similar to C struct using an empty class class Employee(object): pass john = Employee() # Create empty employee record/struct ted = Employee() mark = Employee() # fill the fields of the record/struct john.name = 'John Johnson' john.dept = 'computer lab' john.salary = 3000 ted.name = 'Ted Tetris' ted.dept = 'human resources' ted.salary = 5000 mark.name = 'Mark Marksman' mark.dept = 'shipping area' mark.salary = 3200 # this works like a struct or record print "%s works in the %s and earns $%s/month" % (john.name, john.dept, john.salary) # good for large employee lists, make a list of objects (not strings) empList = [john, ted, mark] for emp in empList: print "%s works in the %s and earns $%s/month" % \ (getattr(emp, "name"), getattr(emp, "dept"), getattr(emp, "salary"))
Last edited by vegaseat : Mar 1st, 2007 at 3:14 pm. Reason: [code=python] tag
May 'the Google' be with you!
While Python offers flexible container data structures, such as lists and dictionaries, it is occasionally helpful to create our own. Suppose, for example, that we wanted to create a data structure with two dictionaries: one for key-value pairs where len(key) is even, and one for key-value pairs where len(key) is odd. We would like to allow the Python builtins, such as str(), len(), container[key], etc, to access our objects in a meaningful way, and Python lets us do this via container-emulation methods:
What this gives you is the freedom to define your own container data structures, and then use them just like you would use Python-supplied containers. Pretty snazzy!
The trick here is that you can define these functions any way you want. For example, your __repr__ method could always return "fish" regardless of the values of the object's instance variables - but that would be counter-intuitive, because programmers generally expect str() to return a string value that represents, at least in part, the internal state of the object. So beware!
Also, the __iter__ method I provided doesn't really build an iterator object - it just compiles a list of keys, then borrows the iterator from that. For more information on iterators and generators, see van Rossum's reference manual.
import sys
# -- The Container class
class Container:
# Instance variables:
# self.even is a dictionary which stores key-value pairs
# where the key has an even length
# self.odd is a dictionary which stores key-value pairs
# where the key has an odd length
# Initialize new Container objects
def __init__(self):
self.even = dict(); self.odd = dict()
# __len__() lets you use len() to evaluate this object
def __len__(self):
return len(self.even)+len(self.odd)
# __repr__() lets you use str() to evaluate this object
def __repr__(self):
return str(self.even)+"\n"+str(self.odd)
# __getitem__ allows evaluation of container[key]
def __getitem__(self, key):
if len(key)%2 == 0: return self.even[key]
else: return self.odd[key]
# __setitem__ allows assignment to container[key]
def __setitem__(self, key, value):
if len(key)%2 == 0: self.even[key] = value
else: self.odd[key] = value
# __delitem__ lets you use del container[key] to remove keys
def __delitem__(self, key):
if len(key)%2 == 0: del self.even[key]
else: del self.odd[key]
# __contains__ lets you use "key in container" boolean expressions
def __contains__(self, key):
return (key in self.even or key in self.odd)
# __iter__ lets you iterate through the items via "for x in container"
def __iter__(self):
ret = []
ret.extend(self.even.keys())
ret.extend(self.odd.keys())
return ret.__iter__()
# -- The main function (diagnostic)
def main(args):
# __init__
c = Container()
# __setitem__
print "Adding key-value pairs\n"
c["Laverne"] = "Shirley"
c["Ozzie"] = "Harriet"
c["Abbott"] = "Costello"
c["Carl"] = "Steve"
# __len__
print "The length of our container is", len(c), "\n"
# __repr__
print "One string representation is:\n", str(c), "\n"
# __getitem__
print "The partner of Abbott is", c["Abbott"], "\n"
# __delitem__
del c["Laverne"]
print "We have just deleted the Laverne:Shirley key-value pair"
print "The new length is", len(c)
print "Now, the container looks like\n", str(c), "\n"
# __contains__
print "Is the key 'Batman' in our container?"
if "Batman" in c: print c["Batman"]
else: print "Sorry, Boy Wonder"
print "Is the key 'Ozzie' in our container?"
if "Ozzie" in c: print "Yes, and it is", c["Ozzie"], "\n"
else: print "No Ozzies here", "\n"
# __iter__
print "Let's iterate through all available keys and their values"
for x in c: print x, "\t", c[x]
# -- The following code executes upon program invocation
if __name__ == "__main__": main(sys.argv)The trick here is that you can define these functions any way you want. For example, your __repr__ method could always return "fish" regardless of the values of the object's instance variables - but that would be counter-intuitive, because programmers generally expect str() to return a string value that represents, at least in part, the internal state of the object. So beware!
Also, the __iter__ method I provided doesn't really build an iterator object - it just compiles a list of keys, then borrows the iterator from that. For more information on iterators and generators, see van Rossum's reference manual.
Vi veri veniversum vivus vici
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
A look at a simple Python class example for the OOP beginner ...
Here class Box inherits the most basic container class object (actually just a place holder), this is the newer class writing convention, adding (object) is "still" optional.
python Syntax (Toggle Plain Text)
# looking at a simple Python class # a class combines a number of methods/functions that belong together class Box(object): """class names by convention are capitalized, (object) is an optional inheritance""" def __init__(self, depth, height, width): """__init__() is called first (acts as Constructor) brings in data from outside the class and makes it usable within the class via the instance object self. Look at self as the data carrier within the class. """ self.depth = depth self.height = height self.width = width def volume(self): return self.height * self.width * self.depth def surface(self): return 2*self.height*self.width + 2*self.height*self.depth + 2*self.width*self.depth # construct an instance of a 10x10x10 box and reference it with box1 box1 = Box(10, 10 ,10) print "A 10x10x10 box has a volume of", box1.volume() print "and a surface area of", box1.surface() print "Let's change the depth to 5" # construct an instance of a 5x10x10 box and reference it with box2 box2 = Box(5, 10 ,10) print "A 5x10x10 box has a volume of", box2.volume() print "and a surface area of", box2.surface() print "Optional tests for the inquisitive folks:" print "box1 =", box1 print "box2 =", box2 print "The depth of box2 is", box2.depth # Can we set the box dimensions directly? Let's try it. box1.depth = 5 box1.height = 5 box1.width = 5 print "Box1 volume after setting box1 dimensions to 5x5x5 =", box1.volume()
Last edited by vegaseat : Mar 1st, 2007 at 2:46 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...
python Syntax (Toggle Plain Text)
# two different ways to represent integer 705083 as a hexadecimal number # 0x is the official prefix for a hexnumber # the results appear different, but both are of type string and change back to base 10 properly # using the hex() function hex1 = hex(705083) print hex1, type(hex1), int(hex1,16) # result = 0xac23b <type 'str'> 705083 # using the format operator % hex2 = "%X" % 705083 print hex2, type(hex2), int(hex2, 16) # result = AC23B <type 'str'> 705083 # let's time the two options ... import timeit t = timeit.Timer('hex(705083)') elapsed = (10 * t.timeit(number=100000)) print 'Function hex(705083) takes %0.3f micro-seconds/pass' % elapsed t = timeit.Timer('"%X" % 705083') elapsed = (10 * t.timeit(number=100000)) print 'The format operator takes %0.3f micro-seconds/pass' % elapsed
Last edited by vegaseat : Mar 1st, 2007 at 2:47 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation:
Rep Power: 8
Solved Threads: 167
Writing a module and testing it ...
python Syntax (Toggle Plain Text)
# save as den2bin.py and use import den2bin in any program that needs it # call the function with something like den2bin.Denary2Binary(76) # (it's easiest to keep this file in the working folder) def Denary2Binary(n): '''convert denary integer n (base 10) to binary string bStr (base 2)''' bStr = '' if n < 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 return bStr # this test runs when used as a standalone program, but not as an imported module # let's say you save this module as den2bin.py and use it in another program # when you import den2bin the __name__ namespace would now be den2bin and the # test would be ignored if __name__ == '__main__': print Denary2Binary(255) # convert back to test it print int(Denary2Binary(255), 2) # check the exceptions print Denary2Binary(0) print Denary2Binary(-5) # should give a ValueError
Last edited by vegaseat : Mar 1st, 2007 at 2:48 pm. Reason: [code=python] tag
May 'the Google' be with you!
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: My 10 line calculator, I want it to display decimals when the equation calls for it.
- Next Thread: winsound SND_PURGE not working.



Linear Mode