User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 429,998 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,505 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: Programming Forums
Views: 55153 | Replies: 150
Reply
Join Date: Jul 2005
Location: France
Posts: 1,019
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 45
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Veteran Poster

Re: Starting Python

  #131  
Apr 17th, 2008
Get your lotto numbers here, simple with Python:
  1. # select 6 unique lotto numbers from 1 - 49
  2.  
  3. import random
  4.  
  5. lotto_list = random.sample(range(1, 50), 6)
  6.  
  7. print lotto_list
  8. print sorted(lotto_list)
  9.  
  10. """
  11. possible result --->
  12. [49, 43, 8, 42, 1, 33]
  13. [1, 8, 33, 42, 43, 49]
  14. """
Should you find Irony, you can keep her!
Reply With Quote  
Join Date: Aug 2005
Posts: 1,142
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #132  
Apr 17th, 2008
You can run the command window from python and obtain the results and error messages:
  1. # run DOS cmd.exe from Python code
  2. # works on XP, but may not work on Windows Vista
  3.  
  4. import subprocess
  5.  
  6. cmd = "cmd.exe"
  7. command = "dir c:"
  8.  
  9. p = subprocess.Popen(cmd,
  10. shell=True,
  11. #bufsize=1,
  12. stdin=subprocess.PIPE,
  13. stdout=subprocess.PIPE,
  14. stderr=subprocess.PIPE)
  15.  
  16. # the \n is important to flush buffer
  17. p.stdin.write("%s\n" % command)
  18.  
  19. p.stdin.close()
  20. # give it enough time to respond
  21. p.wait()
  22.  
  23. # optional check (0 = success)
  24. print p.returncode
  25.  
  26. # read the result to a string
  27. result = p.stdout.read()
  28. print result
  29.  
  30. # optionally read any error message returned
  31. error = p.stderr.read()
  32. print "error =", error
drink her pretty
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,477
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #133  
Apr 22nd, 2008
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 ...
  1. # read each digit of a phone number using module pyglet
  2. # download module pyglet from: http://www.pyglet.org/download.html
  3. # soundfiles 0.wav ... 9.wav are in subdirectory num
  4. # extract the Numbers.zip file into your working directory
  5.  
  6. import pyglet
  7. import time
  8.  
  9. #window = pyglet.window.Window(640, 480)
  10.  
  11. # read all the sound sources into a list
  12. sound = []
  13. for n in range(0, 10):
  14. # soundfiles 0.wav ... 9.wav are in subdirectory num
  15. sound_file = "num/%s.wav" % n
  16. #print sound_file
  17. sound.append(pyglet.media.load(sound_file, streaming=False))
  18.  
  19. # create an instance of the media player class
  20. # for better control
  21. s = pyglet.media.Player()
  22. # optional volume setting 0.0 to 1.0
  23. s.volume = 0.8
  24.  
  25. # read out a phone number string
  26. phone_number_str = '734-344-9941'
  27. for n in phone_number_str:
  28. if n.isdigit():
  29. s.queue(sound[int(n)])
  30. s.play()
  31. # give each digit play() time to finish properly
  32. # you might have to experiment with sleep seconds
  33. time.sleep(0.8)
  34. s.next()
  35. time.sleep(0.4)
  36.  
  37. pyglet.app.run()
Last edited by vegaseat : Apr 22nd, 2008 at 11:49 pm. Reason: spell
Attached Files
File Type: zip Numbers.zip (104.6 KB, 1 views)
May 'the Google' be with you!
Reply With Quote  
Join Date: Jan 2008
Posts: 606
Reputation: ZZucker is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 21
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

  #134  
Apr 26th, 2008
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:
  1. # make a true copy of a nested list
  2.  
  3. import copy
  4.  
  5. nested_list = [1, [2, 3], 4]
  6. copied_list = copy.deepcopy(nested_list)
  7.  
  8. # a regular list copy looks alright at first
  9. copied_list2 = nested_list[:]
  10.  
  11. print nested_list # [1, [2, 3], 4]
  12. print copied_list # [1, [2, 3], 4]
  13. print copied_list2 # [1, [2, 3], 4]
  14.  
  15. print '-'*20
  16.  
  17. # change the orignal list
  18. nested_list[1][0] = 99
  19.  
  20. # but the test shows a surprise!
  21. print nested_list # [1, [99, 3], 4]
  22. print copied_list # [1, [2, 3], 4]
  23. # with simple copy the inner list is just an alias
  24. 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.
Reply With Quote  
Join Date: Jan 2008
Posts: 606
Reputation: ZZucker is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 21
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

  #135  
Apr 26th, 2008
Just a basic Python class example to show you how you can work with it:
  1. # basic experiments with Python class
  2.  
  3. class Cat(object):
  4. # this is public
  5. cost = 100
  6. # this is private to the class
  7. __price = cost + cost * 0.25
  8. # constructor
  9. def __init__(self, num=1):
  10. self.num = num
  11. self.sound = "meow " * self.num
  12. print self.sound
  13.  
  14. def own(self):
  15. print "I own", self.num, "cats"
  16.  
  17. def paid(self):
  18. self.total = self.__price * self.num
  19. print "I paid", self.total, "for my cats"
  20.  
  21. def kitten(self):
  22. self.kit = 5
  23. print "One cat just had", self.kit, "kittens"
  24. return self.kit
  25.  
  26.  
  27. class Dog(object):
  28. # this is public
  29. cost = 400
  30. # this is private to the class
  31. __price = cost + cost * 0.25
  32. # constructor
  33. def __init__(self, num=1):
  34. self.num = num
  35. self.sound = "woof " * self.num
  36. print self.sound
  37.  
  38. def own(self):
  39. print "I own", self.num, "dogs"
  40.  
  41. def paid(self):
  42. self.total = self.__price * self.num
  43. print "I paid", self.total, "for my dogs"
  44.  
  45.  
  46. class Pets(Cat, Dog):
  47. """class Pets inherits class Cat and class Dog"""
  48. # constructor
  49. def __init__(self):
  50. self.num = cat.num + dog.num
  51. self.sound = cat.sound + dog.sound
  52. print self.sound
  53.  
  54. def own(self):
  55. print "I own", self.num, "pets"
  56.  
  57. def paid(self):
  58. print "I paid", dog.total + cat.total, "for my pets"
  59.  
  60. def update(self):
  61. # notice how Pets inherited kitten() from class Cat
  62. self.kit = self.kitten()
  63. print "So now I have", self.num + self.kit, "pets"
  64.  
  65.  
  66. cat = Cat(3)
  67. cat.own()
  68. cat.paid()
  69.  
  70. print '-'*30
  71.  
  72. dog = Dog(2)
  73. dog.own()
  74. dog.paid()
  75.  
  76. print '-'*30
  77.  
  78. pets = Pets()
  79. pets.own()
  80. pets.paid()
  81.  
  82. print '-'*30
  83.  
  84. pets.update()
  85.  
  86. """
  87. my output -->
  88. meow meow meow
  89. I own 3 cats
  90. I paid 375.0 for my cats
  91. ------------------------------
  92. woof woof
  93. I own 2 dogs
  94. I paid 1000.0 for my dogs
  95. ------------------------------
  96. meow meow meow woof woof
  97. I own 5 pets
  98. I paid 1375.0 for my pets
  99. ------------------------------
  100. One cat just had 5 kittens
  101. So now I have 10 pets
  102. """
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,477
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #136  
May 14th, 2008
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 ...
  1. # draw random circles with module pygame
  2. # pygame free from: http://www.pygame.org/
  3.  
  4. import pygame as pg
  5. import random as rn
  6.  
  7. # color rgb tuples
  8. black = 0, 0, 0
  9. blue = 0, 0, 255
  10. green = 0, 255, 0
  11. olive = 128, 128, 0
  12. orange = 255, 165, 0
  13. magenta = 255, 0, 255
  14. red = 255, 0, 0
  15. yellow = 255, 255, 0
  16. white = 255, 255, 255
  17. color_list = [red, blue, green, yellow, olive, orange, magenta]
  18.  
  19. # window/screen width and height
  20. w = 500
  21. h = 500
  22. screen = pg.display.set_mode((w, h))
  23. pg.display.set_caption('Draw a number of random circles')
  24. screen.fill(black)
  25.  
  26. # draw n circles
  27. n = 20
  28. for k in range(n):
  29. x = rn.randint(10, w)
  30. y = rn.randint(10, h)
  31. radius = rn.randint(2, h//3)
  32. color = rn.choice(color_list)
  33. position = x, y
  34. # circle border width = 2
  35. pg.draw.circle(screen, color, position, radius, 2)
  36.  
  37. # update display
  38. pg.display.flip()
  39.  
  40. # event loop ...
  41. running = True
  42. while running:
  43. for event in pg.event.get():
  44. # quit when window corner x is clicked
  45. if event.type == pg.QUIT:
  46. running = False
  47.  
May 'the Google' be with you!
Reply With Quote  
Join Date: Aug 2005
Posts: 1,142
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #137  
May 14th, 2008
The module gasp is a wrapper for pygame with a limited functionality. It is meant for beginners' game development and basic drawing:
  1. # using module gasp to draw an arc, a box, plots and circles
  2. #
  3. # info: GASP (Graphics API for Students of Python)
  4. # A library built on pygame that enables absolute beginners to
  5. # write 1980's style arcade games as an introduction to python.
  6. #
  7. # free download from:
  8. # http://dev.laptop.org/pub/gasp/releases/SOURCES/python-gasp-0.1.1.tar.bz2
  9. # unpack python-gasp-0.1.1.tar.bz2 and copy the 'gasp' subdirectory
  10. # into your python path eg. C:\Python25\lib\site-packages\gasp
  11.  
  12. from gasp import *
  13.  
  14. # rgb color tuples
  15. black = 0, 0, 0
  16. blue = 0, 0, 255
  17. brown = 165, 42, 42
  18. green = 0, 255, 0
  19. orange = 255, 165, 0
  20. red = 255, 0, 0
  21. white = 255, 255, 255
  22. yellow = 255, 255, 0
  23.  
  24. begin_graphics()
  25.  
  26. t = Text("Huston, we have a problem!", (100,420), color=blue, size=40)
  27.  
  28. # Line(from (x, Y), to (x, y))
  29. q1 = Line((30, 400), (500, 400), color=black)
  30. q2 = Line((30, 395), (500, 395), color=yellow)
  31. q3 = Line((30, 390), (500, 390), color=black)
  32.  
  33. # Arc(center (x, y), radius, degrees_start, degrees_end)
  34. # degrees relative to x axis (horizontal)
  35. a = Arc((100,200), 100, 30, 330, filled=True, color=red)
  36.  
  37. # Box(lower_left_corner (x, y), width, height)
  38. b1 = Box((100, 100), 200, 200, color=blue, thickness=5)
  39. b2 = Box((10, 50), 500, 20, filled=True, color=brown)
  40.  
  41. # Circle(center (x, y), radius)
  42. c1 = Circle((420,200), 100, filled=True, color=green)
  43. c2 = Circle((420,200), 120, color=orange, thickness=5)
  44.  
  45. # Plot(center (x, y)) a filled rectangle of given size
  46. p1 = Plot((550,380), color=red, size=10)
  47. p2 = Plot((550,60), color=blue, size=10)
  48.  
  49. sleep(5) # wait 5 seconds
  50.  
  51. end_graphics()
Editor's note: For module gasp to work you need module pygame installed first.
Last edited by vegaseat : May 15th, 2008 at 5:13 pm. Reason: text
drink her pretty
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,477
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #138  
May 18th, 2008
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 ...
  1. w = h = d = 10 # for testing
  2. for x in range(0, w):
  3. for y in range(0, h):
  4. for z in range(0, d):
  5. print x, y, z
  6. stop = raw_input("Stop? y/n")
  7. # alas this will only break out of the z loop
  8. if stop == "y":
  9. break
One solution would be to put the nested loops into a function and use return to break out ...
  1. def nested_loop():
  2. """use of return to exit a nested loop"""
  3. w = h = d = 10 # for testing
  4. for x in range(0, w):
  5. for y in range(0, h):
  6. for z in range(0, d):
  7. print x, y, z
  8. stop = raw_input("Stop? y/n")
  9. if stop == "y":
  10. return
  11.  
  12. nested_loop()
You can also raise an exception to get out ...
  1. # use of try/except to exit a nested loop
  2. w = h = d = 10 # for testing
  3. try:
  4. for x in range(0, w):
  5. for y in range(0, h):
  6. for z in range(0, d):
  7. print x, y, z
  8. if raw_input("Stop? y/n") == "y":
  9. raise StopIteration()
  10. except StopIteration:
  11. pass
May 'the Google' be with you!
Reply With Quote  
Join Date: Jan 2008
Posts: 606
Reputation: ZZucker is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 21
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

  #139  
Jun 28th, 2008
An interesting way to check if a letter is between A and Z:
  1. def has_cap(text):
  2. """return True if text contains a capital letter"""
  3. for ch in text:
  4. # character ch is between A and Z inclusive
  5. if 'A' <= ch <= 'Z':
  6. return True
  7. return False
  8.  
  9. text1 = 'the Good die young, Pricks live forever!'
  10. text2 = 'the good die young, pricks live forever!'
  11. print 'text1 =', text1
  12. print 'text2 =', text2
  13.  
  14. # test the function has_cap()
  15. if has_cap(text1):
  16. print "text1 has a capital letter"
  17. else:
  18. print "text1 has no capital letter"
  19.  
  20. if has_cap(text2):
  21. print "text2 has a capital letter"
  22. else:
  23. 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.
Reply With Quote  
Join Date: Aug 2005
Posts: 1,142
Reputation: Ene Uran is an unknown quantity at this point 
Rep Power: 6
Solved Threads: 66
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Veteran Poster

Re: Starting Python

  #140  
Jul 1st, 2008
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:
  1. # access Python3 features like / for float division
  2.  
  3. from __future__ import division
  4.  
  5. print "Enter a math statement like 355/113 or (2+3)/2 ..."
  6. while True:
  7. result = input("Statement: ")
  8. print result
  9. if raw_input("Continue? (y, n)").lower() == 'n': break
Last edited by Ene Uran : Jul 1st, 2008 at 8:57 am.
drink her pretty
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Python Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 12:56 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC