| | |
Starting Python
![]() |
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 try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk 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.Tk() # create a button, command runs the given function # when button is clicked b1 = tk.Button(root, text="Toggle Color", command=entryColor) # pack button into root window b1.pack(fill=tk.BOTH, expand=1) # create an entry box to color e1 = tk.Entry(root) e1.pack(fill=tk.BOTH, expand=1) # start the event loop root.mainloop()
Last edited by vegaseat; Aug 29th, 2009 at 5:40 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
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/showsnippet.php?codeid=354
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/showsnippet.php?codeid=354
It talks about class inheritance and sheds some light on object and self.
May 'the Google' be with you!
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 ...
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 triple quotes and line continuation (\) # the text lines up properly and # IMHO the easiest to write and 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 # will work with Python2 and Python3 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; Aug 29th, 2009 at 5:54 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
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; Aug 29th, 2009 at 5:57 pm. Reason: [code=python] tag. Python3 ready
May 'the Google' be with you!
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) ) print('-'*60) # or use a list of Employee() instances ... empList = [john, ted, mark] for emp in empList: print( "%s works in the %s and earns $%s/month" % \ (emp.name, emp.dept, emp.salary) ) """my output --> John Johnson works in the computer lab and earns $3000/month ------------------------------------------------------------ John Johnson works in the computer lab and earns $3000/month Ted Tetris works in the human resources and earns $5000/month Mark Marksman works in the shipping area and earns $3200/month """
Last edited by vegaseat; Aug 29th, 2009 at 6:13 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.
Python Syntax (Toggle Plain Text)
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
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 a basic class inheritance signifying the new style class """ 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): """class methods have self as first argument""" 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('') # empty line in Python3 and Python2 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('') print( "Optional tests for the inquisitive folks:" ) print( "box1 =", box1 ) print( "box2 =", box2 ) print( "The depth of box2 is", box2.depth ) print('') # 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; Aug 29th, 2009 at 6:23 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
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) ) # using the format operator % hex2 = "%X" % 705083 print( hex2, type(hex2), int(hex2, 16) ) # let's time the two options ... import timeit print( "Timing study ..." ) t = timeit.Timer('hex(705083)') elapsed = (10 * t.timeit(number=100000)) print( 'hex(705083) takes %0.3f microseconds/pass' % elapsed ) t = timeit.Timer('"%X" % 705083') elapsed = (10 * t.timeit(number=100000)) print( 'Format operator takes %0.3f microseconds/pass' % elapsed ) """my output (Python 3.1) --> 0xac23b <class 'str'> 705083 AC23B <class 'str'> 705083 Timing study ... hex(705083) takes 0.591 microseconds/pass Format operator takes 0.048 microseconds/pass """
Last edited by vegaseat; Aug 29th, 2009 at 6:38 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
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: return '0' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 return bStr # the test code below only runs when used as a standalone program # let's say you save this module as den2bin.py # when you import den2bin the __name__ namespace would now be # 'den2bin' and not '__main__' and the module test will be ignored if __name__ == '__main__': print( denary2binary(255) ) # 11111111 # convert back to test it print( int(denary2binary(255), 2) ) # 255 # with Python3 you can simply use builtin function bin() #print( bin(255), type(bin(255)) ) # 0b11111111 <class 'str'>
Last edited by vegaseat; Aug 29th, 2009 at 7:10 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
This is kind of neat:
Python Syntax (Toggle Plain Text)
# assigning the same value to several variable names: a = b = c = 7 print( a ) # 7 print( c ) # 7 # contents of local dictionary ... print( vars() ) # {'a': 7, 'c': 7, 'b': 7, ... }
Last edited by vegaseat; Aug 29th, 2009 at 7:21 pm. Reason: correction and Python3 update
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: wxpython GUI issue with database
- Next Thread: error in numpy
| Thread Tools | Search this Thread |
abrupt alarm ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd customdialog cx-freeze data decimals dictionaries dictionary directory dynamic error exe file float format function generator getvalue gnu graphics halp heads homework http ideas import input itunes java leftmouse line linux list lists loop maze module mouse number numbers output parsing path pointer prime programming progressbar push py2exe pygame python random recursion schedule screensaverloopinactive script scrolledtext slicenotation sqlite ssh statistics string strings sudokusolver sum table terminal text thread threading time tlapse tuple tutorial twoup ubuntu unicode urllib urllib2 variable ventrilo vigenere web webservice wikipedia write wxpython xlib






