We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,307 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion
Page 15 of Article: Starting Python
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
Moderator
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37

Thanks a Lot for sharing

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
Moderator
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
Moderator
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
Moderator
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

Great thread on Python.... Thanks for sharing.

robrg1836
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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

Looks interesting and fun. Thanks for the introduction vegaseat. If i may ask, what good books would you recommend for starters?

How to think like a computer scientist is great for beginners as is Python programming for the absolute beginner. If you already have experience with a programming language head first python and dive into python 3 are also very good.

pyguy62
Posting Whiz
353 posts since Aug 2011
Reputation Points: 34
Solved Threads: 19
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

nice post ,thanks

adrianfrederic
Newbie Poster
Banned
2 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

does anybody knows how should I deal with Jython interpreter? it's making me crazy.
where is jython.exe ? where is jython command line?
what about JES?

mimi2
Newbie Poster
1 post since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This could help you to get started with Jython (Java based Python):
http://www.daniweb.com/software-development/python/threads/191210/1565073#post1565073

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
# create an acronym

str1 = "Senior health inFormation development"

# just in case it isn't all lower case
str2 = str1.lower()

# make a title-cased copy
str3 = str2.title()

# now build the acronym from the capitalized letters
str4 = ""
for char in str3:
    if char.isupper():
        str4 += char

print("Original string : %s" % str1)
print("All lower case  : %s" % str2)
print("All words titled: %s" % str3)
print("Simple acronym  : %s" % str4)

'''
Original string : Senior health inFormation development
All lower case  : senior health information development
All words titled: Senior Health Information Development
Simple acronym  : SHID
'''
ZZucker
Master Poster
784 posts since Jan 2008
Reputation Points: 342
Solved Threads: 60
Skill Endorsements: 1
# bubble sort a list in either direction

def bubblesort2(q):
    """
    test the bubble sort of a list of numbers
    returns asc and des lists
    asc is the list in ascending order
    des is the list in descending order
    """
    # make copies of the list
    asc = list(q)
    des = list(q)
    for passes in range(len(q)-1, 0, -1):
        for index in range(passes):
            # ascending order
            if asc[index] > asc[index + 1]:
                # do a tuple swap
                asc[index], asc[index + 1] = asc[index + 1], asc[index]
            # descending order
            if des[index] < des[index + 1]:
                des[index], des[index + 1] = des[index + 1], des[index]
    return asc, des

mylist = [4, 2, 7, 9, 25]
asc_list, des_list = bubblesort2(mylist)

print("original  : %s" % mylist)
print("ascending : %s" % asc_list)
print("descending: %s" % des_list)

'''
original  : [4, 2, 7, 9, 25]
ascending : [2, 4, 7, 9, 25]
descending: [25, 9, 7, 4, 2]
'''
ZZucker
Master Poster
784 posts since Jan 2008
Reputation Points: 342
Solved Threads: 60
Skill Endorsements: 1

@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
Moderator
6,330 posts since Apr 2010
Reputation Points: 879
Solved Threads: 989
Skill Endorsements: 27
# everyone likes TGIF
# so loop through a whole year day by day and show all the dates that are Fridays

import datetime

# pick a year
year = 2012

# create date objects
begin_year = datetime.date(year, 1, 1)
end_year = datetime.date(year, 12, 31)
one_day = datetime.timedelta(days=1)

print("These are all the Fridays of %d:" % year)
next_day = begin_year
for day in range(0, 366):
    if next_day > end_year:
        break
    # week starts with monday = 0, so friday = 4
    if next_day.weekday() == 4:
        print("%s is a Friday" % next_day)
    # increment date object by one day
    next_day += one_day
HiHe
Posting Whiz
332 posts since Oct 2008
Reputation Points: 177
Solved Threads: 35
Skill Endorsements: 4

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.1430 seconds using 2.88MB