Starting Python

Reply   View First Unread View First Unread

Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #191
Sep 6th, 2009
This class can be used to toggle between True and False, but can easily be changed to count calls ...
  1. # a class to allow you to toggle between True and False
  2.  
  3. class Static:
  4. """toggle between True and False"""
  5. flag = False
  6. # decorator allows you to simply call Static.toggle()
  7. @classmethod
  8. def toggle(self):
  9. self.flag = not self.flag
  10. return self.flag
  11.  
  12. for k in range(6):
  13. print( '%d) flag = %s' % (k+1, Static.toggle()) )
  14.  
  15. """my output -->
  16. 1) flag = True
  17. 2) flag = False
  18. 3) flag = True
  19. 4) flag = False
  20. 5) flag = True
  21. 6) flag = False
  22. """
Last edited by vegaseat; Sep 6th, 2009 at 10:24 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 901
Reputation: Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough 
Solved Threads: 212
Gribouillis's Avatar
Gribouillis Gribouillis is online now Online
Posting Shark

Re: Starting Python

 
1
  #192
Sep 8th, 2009
Still another way
  1. class Static(object):
  2. def __init__(self, **kwd):
  3. self.__dict__.update(kwd)
  4.  
  5. def toggle(static=Static(flag=True)):
  6. static.flag = not static.flag
  7. return static.flag
  8.  
  9. for i in range(5):
  10. print(toggle())
  11.  
  12. """ my output --->
  13. False
  14. True
  15. False
  16. True
  17. False
  18. """
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #193
Sep 17th, 2009
Just a little cosmetic code:
  1. # a simple way to display plural strings
  2.  
  3. def visits(n):
  4. # adds an s to 'time' if n > 1
  5. return "I visited you %d time%s" % (n, ['','s'][n>1])
  6.  
  7. for n in range(1, 4):
  8. print( visits(n) )
  9.  
  10. """my result -->
  11. I visited you 1 time
  12. I visited you 2 times
  13. I visited you 3 times
  14. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
1
  #194
Sep 21st, 2009
The ultimate user friendly Temperature Converter program. If you put an 'F' or 'f' on the end of the temperature you enter it will give you Celsius. Otherwise it simply assumes you entered a Celsius value and want Fahrenheit:
  1. # a Fahrenheit/Celsius program easy on the user
  2. # tested with Python25
  3. # snee
  4.  
  5. def f2c(t):
  6. """given t Fahrenheit return Celsius"""
  7. return 5/9.0 * (t - 32)
  8.  
  9. def c2f(t):
  10. """given t Celsius return Fahrenheit"""
  11. return 9/5.0 * t + 32
  12.  
  13. def extract_number(s):
  14. """
  15. extract the numeric value from string s
  16. (the string can contain only one numeric value)
  17. return the number or None
  18. """
  19. ts = ""
  20. for c in s:
  21. if c in '1234567890.-':
  22. ts += c
  23. if ts:
  24. # convert number to int or float
  25. return eval(ts)
  26. else:
  27. return None
  28.  
  29. def pick_cf(s):
  30. """given a numeric string s select f or c calculation"""
  31. t = extract_number(s)
  32. print('')
  33. if not t:
  34. print("***need a number***")
  35. return False
  36. if 'f' in s.lower():
  37. print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) )
  38. else:
  39. print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) )
  40. return True
  41.  
  42. prompt = """
  43. Enter a temperature ending with an F to calculate Celsius
  44. otherwise the temperature is assumed to be Celsius and will
  45. give the result in Fahrenheit (press just enter to quit): """
  46.  
  47. while True:
  48. s = raw_input(prompt)
  49. if not s:
  50. break
  51. s = pick_cf(s)
Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.
Last edited by sneekula; Sep 21st, 2009 at 6:56 pm.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
1
  #195
Sep 22nd, 2009
Here is an example how to present the elements of a list or tuple in a nice tabular format ...
  1. # create a table string from a list
  2.  
  3. def create_table(mylist, itemsperline=5):
  4. """
  5. given a list mylist return a string containing
  6. itemsperline of the list items in each line
  7. """
  8. table = ""
  9. for ix, element in enumerate(mylist):
  10. # add new line character after every itemsperline elements
  11. if ix % itemsperline == 0 and ix != 0:
  12. table += '\n'
  13. # use string formatting (adjust to your needs)
  14. # if length of element varies from 1 to 10 use for instance
  15. # table += "%-12s" % element
  16. table += "%-4s" % element
  17. return table
  18.  
  19.  
  20. # create the test list
  21. mylist = [x+y for x in 'abcdef' for y in '1234']
  22.  
  23. #print mylist # test ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', ... ]
  24.  
  25. itemsperline = 4
  26. table = create_table(mylist, itemsperline)
  27.  
  28. print(table)
  29.  
  30. """my result -->
  31. a1 a2 a3 a4
  32. b1 b2 b3 b4
  33. c1 c2 c3 c4
  34. d1 d2 d3 d4
  35. e1 e2 e3 e4
  36. f1 f2 f3 f4
  37. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
0
  #196
1 Day Ago
Here is an example of how you can create a C type switch/case construct using a Python dictionary ...
  1. # a simple reverse polish notation calculator
  2.  
  3. def do_operation(a, b, op):
  4. """
  5. here a dictionary combined with the
  6. lambda inline function acts like C switch/case
  7. a and b are numbers and op is a string
  8. """
  9. return {'+': lambda: a + b,
  10. '-': lambda: a - b,
  11. '*': lambda: a * b,
  12. '/': lambda: a / b
  13. }[op]()
  14.  
  15. # evaluate a reverse Polish notation string
  16. rev_pol = "12 3 *"
  17.  
  18. a, b , op = rev_pol.split()
  19. result = do_operation(float(a), float(b) , op)
  20.  
  21. print( "%s --> %s" % (rev_pol, result) ) # 12 3 * --> 36.0
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC