| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
Get your lotto numbers here, simple with Python:
python Syntax (Toggle Plain Text)
# select 6 unique lotto numbers from 1 - 49 import random lotto_list = random.sample(range(1, 50), 6) print lotto_list print sorted(lotto_list) """ possible result ---> [49, 43, 8, 42, 1, 33] [1, 8, 33, 42, 43, 49] """
Should you find Irony, you can keep her!
You can run the command window from python and obtain the results and error messages:
python Syntax (Toggle Plain Text)
# run DOS cmd.exe from Python code # works on XP, but may not work on Windows Vista import subprocess cmd = "cmd.exe" command = "dir c:" p = subprocess.Popen(cmd, shell=True, #bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # the \n is important to flush buffer p.stdin.write("%s\n" % command) p.stdin.close() # give it enough time to respond p.wait() # optional check (0 = success) print p.returncode # read the result to a string result = p.stdout.read() print result # optionally read any error message returned error = p.stderr.read() print "error =", error
drink her pretty
Here is an example showing you how to read off a number, in this case a phone number, digit by digit on your computer's sound system. You need to extract the attached Numbers.zip file into your working directory. It contains sound files 0.wav to 9.wav spoken by a pleasant female voice ...
python Syntax (Toggle Plain Text)
# read each digit of a phone number using module pyglet # download module pyglet from: http://www.pyglet.org/download.html # soundfiles 0.wav ... 9.wav are in subdirectory num # extract the Numbers.zip file into your working directory import pyglet import time #window = pyglet.window.Window(640, 480) # read all the sound sources into a list sound = [] for n in range(0, 10): # soundfiles 0.wav ... 9.wav are in subdirectory num sound_file = "num/%s.wav" % n #print sound_file sound.append(pyglet.media.load(sound_file, streaming=False)) # create an instance of the media player class # for better control s = pyglet.media.Player() # optional volume setting 0.0 to 1.0 s.volume = 0.8 # read out a phone number string phone_number_str = '734-344-9941' for n in phone_number_str: if n.isdigit(): s.queue(sound[int(n)]) s.play() # give each digit play() time to finish properly # you might have to experiment with sleep seconds time.sleep(0.8) s.next() time.sleep(0.4) pyglet.app.run()
Last edited by vegaseat; Apr 23rd, 2008 at 12:49 am. Reason: spell
May 'the Google' be with you!
If you make a copy of a list, and you have a nested list or don't know what the list might be in the your program, always use module copy:
python Syntax (Toggle Plain Text)
# make a true copy of a nested list import copy nested_list = [1, [2, 3], 4] copied_list = copy.deepcopy(nested_list) # a regular list copy looks alright at first copied_list2 = nested_list[:] print nested_list # [1, [2, 3], 4] print copied_list # [1, [2, 3], 4] print copied_list2 # [1, [2, 3], 4] print '-'*20 # change the orignal list nested_list[1][0] = 99 # but the test shows a surprise! print nested_list # [1, [99, 3], 4] print copied_list # [1, [2, 3], 4] # with simple copy the inner list is just an alias print copied_list2 # [1, [99, 3], 4] oops!
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Just a basic Python class example to show you how you can work with it:
python Syntax (Toggle Plain Text)
# basic experiments with Python class class Cat(object): # this is public cost = 100 # this is private to the class __price = cost + cost * 0.25 # constructor def __init__(self, num=1): self.num = num self.sound = "meow " * self.num print self.sound def own(self): print "I own", self.num, "cats" def paid(self): self.total = self.__price * self.num print "I paid", self.total, "for my cats" def kitten(self): self.kit = 5 print "One cat just had", self.kit, "kittens" return self.kit class Dog(object): # this is public cost = 400 # this is private to the class __price = cost + cost * 0.25 # constructor def __init__(self, num=1): self.num = num self.sound = "woof " * self.num print self.sound def own(self): print "I own", self.num, "dogs" def paid(self): self.total = self.__price * self.num print "I paid", self.total, "for my dogs" class Pets(Cat, Dog): """class Pets inherits class Cat and class Dog""" # constructor def __init__(self): self.num = cat.num + dog.num self.sound = cat.sound + dog.sound print self.sound def own(self): print "I own", self.num, "pets" def paid(self): print "I paid", dog.total + cat.total, "for my pets" def update(self): # notice how Pets inherited kitten() from class Cat self.kit = self.kitten() print "So now I have", self.num + self.kit, "pets" cat = Cat(3) cat.own() cat.paid() print '-'*30 dog = Dog(2) dog.own() dog.paid() print '-'*30 pets = Pets() pets.own() pets.paid() print '-'*30 pets.update() """ my output --> meow meow meow I own 3 cats I paid 375.0 for my cats ------------------------------ woof woof I own 2 dogs I paid 1000.0 for my dogs ------------------------------ meow meow meow woof woof I own 5 pets I paid 1375.0 for my pets ------------------------------ One cat just had 5 kittens So now I have 10 pets """
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
The module pygame is an SDL based GUI toolkit written for game development. It handles sound, images, animation and drawing objects like lines, circles, polygons. Here is a playful example to give you a taste of pygame code ...
python Syntax (Toggle Plain Text)
# draw random circles with module pygame # pygame free from: http://www.pygame.org/ import pygame as pg import random as rn # color rgb tuples black = 0, 0, 0 blue = 0, 0, 255 green = 0, 255, 0 olive = 128, 128, 0 orange = 255, 165, 0 magenta = 255, 0, 255 red = 255, 0, 0 yellow = 255, 255, 0 white = 255, 255, 255 color_list = [red, blue, green, yellow, olive, orange, magenta] # window/screen width and height w = 500 h = 500 screen = pg.display.set_mode((w, h)) pg.display.set_caption('Draw a number of random circles') screen.fill(black) # draw n circles n = 20 for k in range(n): x = rn.randint(10, w) y = rn.randint(10, h) radius = rn.randint(2, h//3) color = rn.choice(color_list) position = x, y # circle border width = 2 pg.draw.circle(screen, color, position, radius, 2) # update display pg.display.flip() # event loop ... running = True while running: for event in pg.event.get(): # quit when window corner x is clicked if event.type == pg.QUIT: running = False
May 'the Google' be with you!
The module gasp is a wrapper for pygame with a limited functionality. It is meant for beginners' game development and basic drawing:
Editor's note: For module gasp to work you need module pygame installed first.
python Syntax (Toggle Plain Text)
# using module gasp to draw an arc, a box, plots and circles # # info: GASP (Graphics API for Students of Python) # A library built on pygame that enables absolute beginners to # write 1980's style arcade games as an introduction to python. # # free download from: # http://dev.laptop.org/pub/gasp/releases/SOURCES/python-gasp-0.1.1.tar.bz2 # unpack python-gasp-0.1.1.tar.bz2 and copy the 'gasp' subdirectory # into your python path eg. C:\Python25\lib\site-packages\gasp from gasp import * # rgb color tuples black = 0, 0, 0 blue = 0, 0, 255 brown = 165, 42, 42 green = 0, 255, 0 orange = 255, 165, 0 red = 255, 0, 0 white = 255, 255, 255 yellow = 255, 255, 0 begin_graphics() t = Text("Huston, we have a problem!", (100,420), color=blue, size=40) # Line(from (x, Y), to (x, y)) q1 = Line((30, 400), (500, 400), color=black) q2 = Line((30, 395), (500, 395), color=yellow) q3 = Line((30, 390), (500, 390), color=black) # Arc(center (x, y), radius, degrees_start, degrees_end) # degrees relative to x axis (horizontal) a = Arc((100,200), 100, 30, 330, filled=True, color=red) # Box(lower_left_corner (x, y), width, height) b1 = Box((100, 100), 200, 200, color=blue, thickness=5) b2 = Box((10, 50), 500, 20, filled=True, color=brown) # Circle(center (x, y), radius) c1 = Circle((420,200), 100, filled=True, color=green) c2 = Circle((420,200), 120, color=orange, thickness=5) # Plot(center (x, y)) a filled rectangle of given size p1 = Plot((550,380), color=red, size=10) p2 = Plot((550,60), color=blue, size=10) sleep(5) # wait 5 seconds end_graphics()
Last edited by vegaseat; May 15th, 2008 at 6:13 pm. Reason: text
drink her pretty
Easy ways to break out of nested loops came up in the forum, so I played with it a little. Using break will only get you out its associated loop like this example shows ...
One solution would be to put the nested loops into a function and use return to break out ...
You can also raise an exception to get out ...
python Syntax (Toggle Plain Text)
w = h = d = 10 # for testing for x in range(0, w): for y in range(0, h): for z in range(0, d): print x, y, z stop = raw_input("Stop? y/n") # alas this will only break out of the z loop if stop == "y": break
python Syntax (Toggle Plain Text)
def nested_loop(): """use of return to exit a nested loop""" w = h = d = 10 # for testing for x in range(0, w): for y in range(0, h): for z in range(0, d): print x, y, z stop = raw_input("Stop? y/n") if stop == "y": return nested_loop()
python Syntax (Toggle Plain Text)
# use of try/except to exit a nested loop w = h = d = 10 # for testing try: for x in range(0, w): for y in range(0, h): for z in range(0, d): print x, y, z if raw_input("Stop? y/n") == "y": raise StopIteration() except StopIteration: pass
May 'the Google' be with you!
An interesting way to check if a letter is between A and Z:
python Syntax (Toggle Plain Text)
def has_cap(text): """return True if text contains a capital letter""" for ch in text: # character ch is between A and Z inclusive if 'A' <= ch <= 'Z': return True return False text1 = 'the Good die young, Pricks live forever!' text2 = 'the good die young, pricks live forever!' print 'text1 =', text1 print 'text2 =', text2 # test the function has_cap() if has_cap(text1): print "text1 has a capital letter" else: print "text1 has no capital letter" if has_cap(text2): print "text2 has a capital letter" else: print "text2 has no capital letter"
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
One of the features of Python3 will be that the division operator / will give a float result ( // is used for integer divisions as usual ). You can use this feature now by importing the __future__ module. Test it out with this example:
python Syntax (Toggle Plain Text)
# access Python3 features like / for float division from __future__ import division print "Enter a math statement like 355/113 or (2+3)/2 ..." while True: result = input("Statement: ") print result if raw_input("Continue? (y, n)").lower() == 'n': break
Last edited by Ene Uran; Jul 1st, 2008 at 9:57 am.
drink her pretty
![]() |
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: Decimal formatting
- Next Thread: Python - Using a text file to feed into a python dictionary
| Thread Tools | Search this Thread |
access ada anti api arax beginner blogger blogging bug c# c++ code combo csv cx-freeze daniweb data database development dictionary digital dropdownlist editcodesnippet embed event exam examples excel fanniemay file format function game gdata google gui images innovation input introduction itunes java joomla key linux list lists maze method microsoft module mouse mvcmodel2 mysqldb net news obexftp parameters password php problem program programming projects py2exe pygame python random reuse reverse rss script security servlet shebang shutdown skinning smtp source sprite sqlite string syntax table text threading tutorial ubuntu unicode url urllib urllib2 variable virus vista visual visualbasic6 web wxpython xml







