| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() | 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 28 Days Ago
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!
•
•
Join Date: Nov 2009
Posts: 6
Reputation:
Solved Threads: 0
0
#197 17 Days Ago
well done!when i went about learning python ,i used the a byte of python . i recommand two websites which are filled with the good ebooks for python .
http://www.onlinecomputerbooks.com/
http://www.bookfm.com
http://www.onlinecomputerbooks.com/
http://www.bookfm.com
0
#198 Combinations and Permutations are closely linked. The function shown here is a recursive generator function that returns permutations with selectable sample size ...
Note: corrected post, see sneekula's post at ...
http://www.daniweb.com/forums/post10...ml#post1086335
python Syntax (Toggle Plain Text)
# a permutation or combination does not repeat sample items # Python3 has a non-recursive combination function # via itertools.combinations(iterable, sample_size) # and a non-recursive permutation function # via itertools.permutations(iterable, sample_size=None) # vegaseat def permutations(itr, n): """ permutations(items, n) is a recursive generator function where itr is an iterable object like a list or string n is the sample size returns a list of nonrepeating sample size items n = len(itr) is the max sample size """ if n == 0: yield [] else: for k in range(len(itr)): # a recursive function for c in permutations(itr[:k] + itr[k+1:], n - 1): yield [itr[k]] + c iterable = 'abc' sample_size = 2 perm_list = list(permutations(iterable, sample_size)) # show as a list of lists print( perm_list ) print( '-'*50 ) # show as a list of strings print( ["".join(item) for item in perm_list] ) """ my result (sample size max - 1) --> [['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']] -------------------------------------------------- ['ab', 'ac', 'ba', 'bc', 'ca', 'cb'] """
http://www.daniweb.com/forums/post10...ml#post1086335
Last edited by vegaseat; 12 Minutes Ago at 11:45 am. Reason: snee post
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: Colour picker problem
- Next Thread: try-except
Views: 89814 | Replies: 197
| Thread Tools | Search this Thread |
Tag cloud for code, hints, python, tricks, tutorial
7 10 access ada api arax beginner blogger blogging bug c++ code combo csv cx-freeze daniweb data database development dictionary digital dropdownlist editor error event exam examples excel file format function game gdata google gui html http images innovation input itunes java joomla linux list lists method microsoft module mvcmodel2 mysqldb net news obexftp parameters password php print problem program programming projects py2exe pygame python random recursive reuse reverse rss ruby script security server shebang shutdown skinning source sprite string syntax table text threading tkinter tutorial ubuntu url urllib urllib2 variable vb virus vista visual visualbasic6 web windows wxpython xml








