The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread! The creators of Python are very active, improving the language all the time. Here is a little of the…
Questions about threading come up many times on the forum, so here some help ...
# running a function in the background with threading
# apply threading to a function with a function decorator
# without the threading decorator the function counter2
# would tick off first, then the other prints would show
import time
import threading
def background(f):
"""
a threading decorator
use @background above the function you want to thread
(run in the background)
"""
def bg_f(*a, **kw):
threading.Thread(target=f, args=a, kwargs=kw).start()
return bg_f
@background
def counter2(n):
"""show the count every second"""
for k in range(n):
print("counting %d" % k)
time.sleep(1)
# start the counter
counter2(7)
time.sleep(0.9)
print('hello') # prints hello, before counter prints 1
time.sleep(3)
print('world') # prints world, before counter prints 4
''' result ...
counting 0
hello
counting 1
counting 2
counting 3
world
counting 4
counting 5
counting 6
'''
vegaseat
DaniWeb's Hypocrite
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37
maninaction
Junior Poster in Training
76 posts since Jun 2011
Reputation Points: 1
Solved Threads: 7
Skill Endorsements: 0
Easy to overlook, random.choice() is usually used to pick an item from a list. However, it does apply to any sequence ...
import random
# pick a random letter out of a string
print(random.choice('abcdefg'))
vegaseat
DaniWeb's Hypocrite
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37
A simple way to display a list of lists/tuples as a table in your browser ...
# make_html_table.py
# create an html table from a data list
def make_html_table(mylist):
"""
use a list of data tuples and create the html code
of a html formatted table containing the data items
"""
rows = ['<td>'+'</td><td>'.join(xx)+'</td>'+'\n' for xx in mylist]
table = '<table border=2><tr>'
table += '<tr>'.join(rows)
table += '</tr></table>'
return table
# a list of (name, age, weight) tuples (or lists)
# the first tuple is the header
data_list = [
('Name', 'Age', 'Weight'),
('Sarah Gellar', '26', '121'),
('Alec Baldwin', '47', '214'),
('Mandy Moore', '22', '135'),
('Matthew Goode', '29', '167'),
('Amanda Bynes', '19', '112'),
('James Kirk', '24', '175')
]
html_table = make_html_table(data_list)
print(html_table) # test
# save as html file and show in your browser
with open('html_table.htm', 'w') as fout:
fout.write(html_table)
You can use this simple code to show the above html file in your web browser ...
# use Python's webbrowser module to show an html code file
import webbrowser
# open your web browser to run the html file
webbrowser.open('html_table.htm')
vegaseat
DaniWeb's Hypocrite
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37
The named tuple is a versatile container similar to a tuple but with named indexes replacing the numeric ones ...
# named tuples have named indexes that behave similar to class
# instances but require no more memory than regular tuples
# tested with Python27 and Python32 by vegaseat
import collections as co
import pprint
def create_nt_dict(data_list, Person):
"""
load the named tuple with the data list and
create a dictionary of the named tuple
where the instance name is the key
"""
nt_dict = {}
for name, age, weight in data_list:
# use lower first name + initial letter of last name
# as key to avoid name collisions
first, last = name.split()
instance_name = first.lower() + last[0]
nt_dict[instance_name] = Person(name, age, weight)
return nt_dict
# a test list of (name, age, weight) tuples
data_list = [
('Sarah Gellar', 26, 121),
('Alec Baldwin', 47, 214),
('Mandy Moore', 22, 135),
('Matthew Goode', 29, 167),
('Amanda Bynes', 19, 112),
('James Kirk', 24, 175)
]
# create the named tuple
# does behave like a Python class so use name 'Person'
Person = co.namedtuple('movie_star', 'name, age, weight')
# load the named tuple and get a dictionary of instances
nt_dict = create_nt_dict(data_list, Person)
# add nt_dict to dictionary local to __main__
locals().update(nt_dict)
# test_prints only ...
pprint.pprint(nt_dict)
print('<>'*35)
pprint.pprint(locals())
print('<>'*35)
# work with the named tuple ...
print("names of instances =\n%s" % sorted(nt_dict.keys()))
'''
names of instances =
['alecB', 'amandaB', 'jamesK', 'mandyM', 'matthewG', 'sarahG']
'''
# pick one instance ...
print(mandyM.name) # Mandy Moore
print(mandyM.age) # 22
print('<>'*35)
print("Movie stars under 25 years of age:")
for star in nt_dict:
star = eval(star)
if star.age < 25:
print(star.name, star.age, star.weight)
''' Python32 result ...
Movie stars under 25 years of age:
James Kirk 24 175
Mandy Moore 22 135
Amanda Bynes 19 112
'''
vegaseat
DaniWeb's Hypocrite
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37
# one short look at counters/accumulators
# tested with Python 3.2.1
def xcounter():
"""
generator function (yield replaces return)
increments by one each call
"""
k = 0
while True:
k += 1
yield k
# next is needed with generator functions
# with Python2 use .next
# with Python3 use .__next__
counter = xcounter().__next__
for k in range(5):
print(counter())
'''
1
2
3
4
5
'''
bumsfeld
Posting Virtuoso
1,512 posts since Jul 2005
Reputation Points: 409
Solved Threads: 238
Skill Endorsements: 1
# one short look at counters/accumulators
# tested with Python 3.2.1
class Count:
k = 0
def counter(self):
self.k += 1
return self.k
# this allows you to simply call Count.counter()
counter = classmethod(counter)
# test ...
for k in range(5):
print(Count.counter())
'''
1
2
3
4
5
'''
bumsfeld
Posting Virtuoso
1,512 posts since Jul 2005
Reputation Points: 409
Solved Threads: 238
Skill Endorsements: 1
Looks interesting and fun. Thanks for the introduction vegaseat. If i may ask, what good books would you recommend for starters?
Netcode
Veteran Poster
1,037 posts since Jun 2009
Reputation Points: 43
Solved Threads: 70
Skill Endorsements: 0
I have 'how to think like a computer scientist' in my library. Maybe i would start with that then go on to thers.
Thanks
Netcode
Veteran Poster
1,037 posts since Jun 2009
Reputation Points: 43
Solved Threads: 70
Skill Endorsements: 0
bumsfeld
Posting Virtuoso
1,512 posts since Jul 2005
Reputation Points: 409
Solved Threads: 238
Skill Endorsements: 1
A quick look at the one line conditional expression:
# using a conditional expression
# tested with Python27 and Python32
y = 1
# written as a common conditional expression
if y == 1:
x = 5
else:
x = 3
print( "if y = %d then x = %d" % (y, x ) )
print("--- using one-line conditional expression ---")
# can be written as a one-line conditional expression
x = 5 if y == 1 else 3
print( "if y = %d then x = %d" % (y, x ) )
y = 77
x = 5 if y == 1 else 3
print( "if y = %d then x = %d" % (y, x ) )
"""my result -->
if y = 1 then x = 5
--- using one-line conditional expression ---
if y = 1 then x = 5
if y = 77 then x = 3
"""
I am using the Eric5 Python IDE that allows you to test your code with different versions of Python.
Under Preferences I set the Debugger to use Python27 for code with extension .py2
Lardmeister
Posting Virtuoso
1,940 posts since Mar 2007
Reputation Points: 465
Solved Threads: 73
Skill Endorsements: 5
Print 10 numbers per row:
# avoids print(),
# works with Python2 and Python3
import sys
for k in range(100):
# print 10 numbers per row
# ('\t', '\n')[k % 10 == 9] selects '\t' or '\n'
str1 = "%3d%s" % (k, ('\t', '\n')[k % 10 == 9])
sys.stdout.write(str1)
sys.stdout.flush()
print('-'*40) # 40 dashes, cosmetic
for k in range(100):
# print 10 numbers per row
# use one-line conditional if/else
str1 = "%3d%s" % (k, ('\n' if k % 10 == 9 else '\t'))
sys.stdout.write(str1)
sys.stdout.flush()
'''my output >>>
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
----------------------------------------
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
'''
Lardmeister
Posting Virtuoso
1,940 posts since Mar 2007
Reputation Points: 465
Solved Threads: 73
Skill Endorsements: 5
@ZZucker:
I would like to point out that the code snippet of mine http://www.daniweb.com/software-development/python/code/422450/input-generator has use case example allmost same as ZZucker first example, as it capitalizes first letters of each word (as title casing does), just join the first letter of words instead of list of capitalized words.
The buble sort in two orders I do not like so much, because the second list is just reverse of other one and completely redundant. I also like to keep index play in minimum, here is my bubble sort for comparison
def bubble(seq):
seq = seq[:]
for thisfar in reversed(range(len(seq))):
done = True
for pos in range(thisfar):
if seq[pos] > seq[pos+1]:
seq[pos], seq[pos+1] = seq[pos+1], seq[pos]
done = False
if done:
#print thisfar
return seq
pyTony
pyMod
6,330 posts since Apr 2010
Reputation Points: 879
Solved Threads: 989
Skill Endorsements: 27