| | |
Starting Python
![]() | View First Unread |
This class can be used to toggle between True and False, but can easily be changed to count calls ...
python Syntax (Toggle Plain Text)
# a class to allow you to toggle between True and False class Static: """toggle between True and False""" flag = False # decorator allows you to simply call Static.toggle() @classmethod def toggle(self): self.flag = not self.flag return self.flag for k in range(6): print( '%d) flag = %s' % (k+1, Static.toggle()) ) """my output --> 1) flag = True 2) flag = False 3) flag = True 4) flag = False 5) flag = True 6) flag = False """
Last edited by vegaseat; Sep 6th, 2009 at 10:24 pm.
May 'the Google' be with you!
Still another way
python Syntax (Toggle Plain Text)
class Static(object): def __init__(self, **kwd): self.__dict__.update(kwd) def toggle(static=Static(flag=True)): static.flag = not static.flag return static.flag for i in range(5): print(toggle()) """ my output ---> False True False True False """
Just a little cosmetic code:
python Syntax (Toggle Plain Text)
# a simple way to display plural strings def visits(n): # adds an s to 'time' if n > 1 return "I visited you %d time%s" % (n, ['','s'][n>1]) for n in range(1, 4): print( visits(n) ) """my result --> I visited you 1 time I visited you 2 times I visited you 3 times """
No one died when Clinton lied.
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:
Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.
python Syntax (Toggle Plain Text)
# a Fahrenheit/Celsius program easy on the user # tested with Python25 # snee def f2c(t): """given t Fahrenheit return Celsius""" return 5/9.0 * (t - 32) def c2f(t): """given t Celsius return Fahrenheit""" return 9/5.0 * t + 32 def extract_number(s): """ extract the numeric value from string s (the string can contain only one numeric value) return the number or None """ ts = "" for c in s: if c in '1234567890.-': ts += c if ts: # convert number to int or float return eval(ts) else: return None def pick_cf(s): """given a numeric string s select f or c calculation""" t = extract_number(s) print('') if not t: print("***need a number***") return False if 'f' in s.lower(): print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) ) else: print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) ) return True prompt = """ Enter a temperature ending with an F to calculate Celsius otherwise the temperature is assumed to be Celsius and will give the result in Fahrenheit (press just enter to quit): """ while True: s = raw_input(prompt) if not s: break s = pick_cf(s)
Last edited by sneekula; Sep 21st, 2009 at 6:56 pm.
No one died when Clinton lied.
Here is an example how to present the elements of a list or tuple in a nice tabular format ...
python Syntax (Toggle Plain Text)
# create a table string from a list def create_table(mylist, itemsperline=5): """ given a list mylist return a string containing itemsperline of the list items in each line """ table = "" for ix, element in enumerate(mylist): # add new line character after every itemsperline elements if ix % itemsperline == 0 and ix != 0: table += '\n' # use string formatting (adjust to your needs) # if length of element varies from 1 to 10 use for instance # table += "%-12s" % element table += "%-4s" % element return table # create the test list mylist = [x+y for x in 'abcdef' for y in '1234'] #print mylist # test ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', ... ] itemsperline = 4 table = create_table(mylist, itemsperline) print(table) """my result --> a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4 d1 d2 d3 d4 e1 e2 e3 e4 f1 f2 f3 f4 """
May 'the Google' be with you!
0
#196 Here is an example of how you can create a C type switch/case construct using a Python dictionary ...
python Syntax (Toggle Plain Text)
# a simple reverse polish notation calculator def do_operation(a, b, op): """ here a dictionary combined with the lambda inline function acts like C switch/case a and b are numbers and op is a string """ return {'+': lambda: a + b, '-': lambda: a - b, '*': lambda: a * b, '/': lambda: a / b }[op]() # evaluate a reverse Polish notation string rev_pol = "12 3 *" a, b , op = rev_pol.split() result = do_operation(float(a), float(b) , op) print( "%s --> %s" % (rev_pol, result) ) # 12 3 * --> 36.0
May 'the Google' be with you!
![]() |
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: need help
- Next Thread: Python - Using a text file to feed into a python dictionary
| Thread Tools | Search this Thread |
access ada advanced anti api arax array beginner blogger blogging bug c++ code combo convert csv cx-freeze daniweb data database development dictionary digital dropdownlist embed event exam examples excel fanniemay file format function game gdata google gui images innovation input introduction itunes java joomla keycontrol linux list lists maze method microsoft module mouse mvcmodel2 net news obexftp parameters password php post problem program programming projects py2exe pygame pyopengl python random reuse reverse rss ruby script security shutdown skinning source sprite string syntax terminal text threading tutorial ubuntu url urllib urllib2 variable vb virus vista visual visualbasic6 web web-scrape wxpython xml








