A print format hint given by our friend Gribouillis ...

''' print_format101.py
tested with Python27, Ironpython27 and Python33
'''

# print a given value in different numeric formats
# each field is 10 characters wide, precision of 2 digits
sf = "{val:^10.2e}{val:^10.2f}{val:^10.2g}{val:^10.2n}{val:^10.2%}"

print(sf.format(val=0.1))

''' result ...
 1.00e-01    0.10      0.1       0.1      10.00%
'''

Python 3.4.0 has just been released and has a nice new module called statistics. Here is a test ...

''' statistics_test101.py
testing Python 3.4.0 and its module statistics
'''

import statistics as st  # needs Python 3.4 and higher

mylist = [1, 2, 3, 5, 7, 4, 2, 8]

print(mylist)
print('-'*30)
print("mean               = {:2.5f}".format(st.mean(mylist)))
print("variance           = {:2.5f}".format(st.variance(mylist)))
print("standard deviation = {:2.5f}".format(st.stdev(mylist)))

''' result ...
[1, 2, 3, 5, 7, 4, 2, 8]
------------------------------
mean               = 4.00000
variance           = 6.28571
standard deviation = 2.50713
'''
commented: it looks great +14

The print function is full of surprises (at least for me) ...

''' list_print3.py
printing out a list
tested with Python27 and Python34
'''

# optional, allows Python27 to use Python3 print() options
# needs to be at beginning of your program code
from __future__ import print_function

mylist = ['Fred', 'Lisa', 'Anton']

print(*mylist, sep='\n')
print('-'*5)
print(*mylist, sep=', ')

''' result ...
Fred
Lisa
Anton
-----
Fred, Lisa, Anton
'''

If you have a Windows machine, it might be worth to investigate
Portable Python that allows you to run Python from the hard drive, or any USB flash card that can be used on a Windows computer that does not have Python installed. It comes with just about all the extra (third party) modules you need.

For instance
http://portablepython.com/wiki/PortablePython2.7.6.1/
now gives you a choice of some nice IDEs like
PyScripter v2.5.3
or
PyCharm Community Edition 3.1.2

The Python3 version is also available.

Just a note:
QPython is a script engine running on Android devices like phone or tablet, It embeds the python interpreter, console, editor, SL4A library for android, which can make your android device run python script or project.

See ...
http://qpython.com/

Just a little number trick ...

''' decimal_number_sequence101.py
after the decimal point there is a sequence of numbers from 000 to 022
you can go higher by increasing the precision
'''

import decimal

# set the precision
decimal.getcontext().prec = 64

# for convenience ...
dd = decimal.Decimal

x = dd(1)/dd(998001)
print(x)

'''
0.000001002003004005006007008009010011012013014015016017018019020021022
'''

A closer look at some of Python's functions ...

''' zip_unzip_lists101.py
exploring Python's zip() function
dns
'''

numbers = [1, 2, 3, 4, 5]
letters = ['a', 'b', 'c', 'd', 'e']

# zip the two lists
numlet = zip(numbers, letters)

print(numlet)

''' result ...
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
'''

# this will actually unzip the zipped numlet
print(zip(*numlet))

''' result ...
[(1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', 'e')]
'''

Not used very often, but has possibilities ...

''' str_templating101.py
exploring Python module string
dns
'''

import string

def change_text(template, sub_dictionary):
    t = string.Template(template)
    return t.substitute(sub_dictionary)

# variables to be substituted begin with a $, use $$ to literalize $
template = 'The $animal says "$sound, my name is $name!"'

# create dictionaries for each animal
d_cow = dict(animal='cow', sound='mooh', name='Hilda')
d_dog = dict(animal='dog', sound='woof', name='Rover')
d_cat = dict(animal='cat', sound='meow', name='George')

for animal_dict in (d_cow, d_dog, d_cat):
    print(change_text(template, animal_dict))


''' result ...
The cow says "mooh, my name is Hilda!"
The dog says "woof, my name is Rover!"
The cat says "meow, my name is George!"
'''

Module pprint (PrettyPrint) has been improved in Python34 ...

''' pprint34.py
pprint.pprint(object, stream=None, indent=1, width=80,
    depth=None, *, compact=False)
compact=True will print as many sequence elements as will fit within
the given width (default is 80) on each line
parameter compact is new in Python34
'''

import pprint

mylist = list(range(1000, 1100))

pprint.pprint(mylist, compact=True)

''' result ...
[1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012,
 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025,
 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038,
 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051,
 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064,
 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077,
 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090,
 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099]
'''

A look at module fractions:

import fractions
import math

fractional_pi = fractions.Fraction(str(math.pi))

# limit the denominator to 999 or less
fractional_pi_999 = fractional_pi.limit_denominator(999)

# show result
sf = "pi = {} as a fraction with a max. denominator of 999 is {}"
print(sf.format(math.pi, fractional_pi_999))

''' my result -->
pi = 3.14159265359 as a fraction with a max. denominator of 999 is 355/113
'''

A little Python history:

Python 1.0 - January 1994
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000

Python 2.0 - October 16, 2000
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010

Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014

Can anyone please check out my post about solving my code? I am new to python and cant get this code to run. I had been working with it for hours and still no luck. Also, if this is the wrong place to post this I am sorry--just let me know, i am new to this forum. thanks!!

Editor's Note:
You are right, it does not belong here!

Generate the Python byte code of

n = 5
n = n + 3

Here we go:

import codeop, dis

code_obj = codeop.compile_command("n = 5; n = n + 3")

disasm = dis.dis(code_obj)

print(disasm)

''' result -->
  1           0 LOAD_CONST               0 (5)
              3 STORE_NAME               0 (n)
              6 LOAD_NAME                0 (n)
              9 LOAD_CONST               1 (3)
             12 BINARY_ADD
             13 STORE_NAME               0 (n)
             16 LOAD_CONST               2 (None)
             19 RETURN_VALUE
None
'''

Looks like assembly code and shows you some of the internal workings of Python.

A Python dictionary from a string example ...

''' Nato_alphabet_dict101.py
create a dictionary for the
standard NATO phonetic alphabet for English
'''

# copied from a nato war manual
nato_alphabet_str = '''\
A = Alpha
B = Bravo
C = Charlie
D = Delta
E = Echo
F = Foxtrot
G = Golf
H = Hotel
I = India
J = Juliet
K = Kilo
L = Lima
M = Mike
N = November
O = Oscar
P = Papa
Q = Quebec
R = Romeo
S = Sierra
T = Tango
U = Uniform
V = Victor
W = Whiskey
X = Xray
Y = Yankee
Z = Zulu'''

# convert to a dictionary
nato_alphabet_dict = {}
for line in nato_alphabet_str.split('\n'):
    k, v = line.split('=')
    # build the dictionary
    nato_alphabet_dict[k.strip()] = v.strip()

# testing
import pprint
pprint.pprint(nato_alphabet_dict)

''' result ...
{'A': 'Alpha',
 'B': 'Bravo',
 'C': 'Charlie',
 'D': 'Delta',
 'E': 'Echo',
 'F': 'Foxtrot',
 'G': 'Golf',
 'H': 'Hotel',
 'I': 'India',
 'J': 'Juliet',
 'K': 'Kilo',
 'L': 'Lima',
 'M': 'Mike',
 'N': 'November',
 'O': 'Oscar',
 'P': 'Papa',
 'Q': 'Quebec',
 'R': 'Romeo',
 'S': 'Sierra',
 'T': 'Tango',
 'U': 'Uniform',
 'V': 'Victor',
 'W': 'Whiskey',
 'X': 'Xray',
 'Y': 'Yankee',
 'Z': 'Zulu'}
'''

Another number oddity ...

''' perfect_digit-to-digit_invariant.py
the Canouchi number is a natural number that is equal to the
sum of its digits each raised to a power equal to the digit

there are only two Canouchi numbers in the decimal system,
3435 and 438579088 

see ...
http://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant
'''

# number 3435 implies 3**3 + 4**4 + 3**3 + 5**5 = 3435
# test it ...
print(3**3 + 4**4 + 3**3 + 5**5)   # 3435

Ah, the old convert grades problem ...

''' grades_via_bisect101.py
using module bisect to determine grades A to F
from 100 to 0 score points
'''

import bisect

# both sequences have to be sorted or be in order
# A is 85 or higher, B is 75 to 84 etc.
grades = "FEDCBA"
breakpoints = [30, 44, 66, 75, 85]

def grade(total):
    return grades[bisect.bisect(breakpoints, total)]

print(grade(66))  # C
print(grade(33))  # E
print(grade(85))  # A
print(grade(77))  # B
print(grade(27))  # F

A chemical string ...

# string fun

str1 = 'helicopter'
char_list = list(str1)
k = 0
for char in char_list[::2]:
    char_list[k] = char.upper()
    k = k + 2

str2 = "".join(char_list)
print(str1)
print(str2)
print("Notice the five chemical elements!")

A little play with lotto numbers ...

''' lotto_list101.py
select 6 unique lotto numbers from 1 - 49
'''

import random

lotto_list = random.sample(range(1, 50), 6)

print(lotto_list)
print(sorted(lotto_list))

''' possible result ...
[49, 43, 8, 42, 1, 33]
[1, 8, 33, 42, 43, 49]
'''

Interesting ...

""" Misspell1.py
The Misspell class takes a string and slightly mangles it by randomly
transposing two adjacent characters while leaving the first and last
characters intact. The resulting text is almost completely misspelled but
still very readable. Words less than four characters, numbers, email
addresses and URLs are untouched. Each run will produce a message with a
different signature (checksum).
"""

import random
import re
import io

class Misspell(object):
    """
    a class to misspell words in a sentence so they can still be readable
    """
    def __init__(self):
        """
        create a regex to match a word with ending punctuation
        """
        self.punctuation = re.compile('\S+[' + re.escape(",'.:;!?") + ']$')

    def misspell(self, text):
        self.text = io.StringIO(text).readlines()
        misspelled = []
        for line in self.text:
            # split hyphenated words into independent words
            line = re.sub(r'(\S+)\-(\S+)', r'\1 \2', line)
            # split each line in a list of words
            tokens = line.split()
            for token in tokens:
                # don't misspell a number
                if token.isdigit():
                    misspelled.append(token + ' ')
                    continue
                # don't misspell an email address or URL
                if '@' in token or '://' in token:
                    misspelled.append(token + ' ')
                    continue
                # does the word end with punctuation?
                has_punc = re.match(self.punctuation, token)
                # explode the word to a list
                token = list(token)
                # word doesn't end in punctuation and is longer than 4 chars
                if not has_punc and len(token) >= 4:
                    start = random.randint(1,len(token) - 3)
                    stop = start + 2
                    f,s = token[start:stop]
                    token[start:stop] = s,f
                # word ends in punctuation and is longer than 5 chars
                elif has_punc and len(token) >=5:
                    start = random.randint(1,len(token) - 4)
                    stop = start + 2
                    f,s = token[start:stop]
                    token[start:stop] = s,f
                # add the word to the line
                misspelled.append((''.join(token) + ' '))
            # end the line
            misspelled.append('\n')
        return ''.join(misspelled)


# testing the class ...
if __name__ == '__main__':
    text = """
    According to research at an English University, it doesn't matter
    in what order the letters in a word are, the only important thing is
    that the first and last letters be in the right places. The rest can
    be a total mess and you can still read it without problem. This is
    because the human mind does not read every letter by itself, but
    the word as a whole."""

    goof = Misspell()
    print(goof.misspell(text))


''' possible result ...
Accroding to reserach at an Egnlish Univresity, it deosn't mtater 
in waht oredr the letetrs in a wrod are, the olny imoprtant thnig is 
taht the fisrt and lsat letters be in the rgiht plaecs. The rset can 
be a ttoal mses and you can sitll raed it wihtout probelm. Tihs is 
beacuse the hmuan mnid deos not raed evrey letter by istelf, but 
the wrod as a wohle
'''

Create a list of evenly spaced numeric values, given the starting value, the increment (step) and the size ...

import itertools as it

def spaced_list(start, step, size):
    '''
    create an evenly spaced list of a given size
    start and step can be integers or floats
    '''
    return list(it.islice(it.count(start, step), size))

start = 2.5
step = 0.5
size = 10
mylist = spaced_list(start, step, size)
print(mylist)

''' result ...
[2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
'''

For a listing of all installled modules use ...

''' modules_pip101.py
list all your installed modules and version numbers

Python 2.7.9 (and later) and Python 3.4 (and later) include pip by default

On Windows download installer from ...
http://www.lfd.uci.edu/~gohlke/pythonlibs/

On Debian or Ubuntu use ...
sudo apt-get install python-pip
'''

import pip

for item in pip.get_installed_distributions():
    print(item)

''' possible result ...

backports.ssl-match-hostname 3.4.0.2
conda 3.5.5
cx-Freeze 4.3.3
gmpy2 2.0.3
iep 3.5
imageio 0.5.1
ipython 2.1.0
Jinja2 2.7.3
MarkupSafe 0.18
matplotlib 1.3.1
nose 1.3.3
numpy 1.8.1
pandas 0.14.0
Pillow 2.5.2
psutil 2.1.1
pycosat 0.6.1
Pygments 1.6
PyOpenGL 3.1.0b3
pyparsing 2.0.1
pyreadline 2.0
PySide 1.2.2
python-dateutil 2.1
pytz 2014.4
PyYAML 3.11
pyzmq 14.3.1
pyzolib 0.3.3
requests 2.3.0
scikit-image 0.10.0
scikit-learn 0.15.0b2
scipy 0.14.0
six 1.7.3
sympy 0.7.5
tornado 3.2.2
visvis 1.9.1
'''

In case you need to know ...

''' np_version.py
get the version of numpy you have installed
'''

import numpy

print(numpy.__version__)

''' possible result ...
1.9.0
'''

Some interesting itertools applications ...

''' itertools_groupby101.py
exploring the Python itertools module
itertools.count(start=0, step=1)
itertools.groupby(iterable, key)

'''

import itertools as it
import string

# us an iterable string for testing
# use string.ascii_lowercase for Python3
iterable = string.lowercase
print(iterable)
print('-'*26)

block_size = 5

# key is a function computing a key value for each element in iterable
key = lambda _, w=it.count(): next(w)//block_size

for number, rows in it.groupby(iterable, key):
    print("{} {}".format(number, list(rows)))

''' result ...
abcdefghijklmnopqrstuvwxyz
--------------------------
0 ['a', 'b', 'c', 'd', 'e']
1 ['f', 'g', 'h', 'i', 'j']
2 ['k', 'l', 'm', 'n', 'o']
3 ['p', 'q', 'r', 's', 't']
4 ['u', 'v', 'w', 'x', 'y']
5 ['z']
'''

You can use Python module json to save (dump) and read (load) certain Python objects ...

''' json_dictionary1.py
Python module json can be used to dump and load dictionay objects
json --> JavaScript Object Notation
You can also dump and load list objects
'''

import json

pfolio_dict = {
'GOOG': ('Google', 200, 549.85), 'YHOO': ('Yahoo', 900, 16.81),
'AAPL': ('Apple', 400, 188.0), "MSFT": ('Microsoft', 300, 26.5)
}

fname = "portfolio.jsn"
# dump the dictionary object to file
# you can look at the .jsn file with an editor
with open(fname, "w") as fout:
    json.dump(pfolio_dict, fout)

# read the dictionary object back in from file
with open(fname) as fin:
    pfolio_dict2 = json.load(fin)

# testing ...
print(type(pfolio_dict2))
print('-'*20)
print(pfolio_dict2)

''' result (Python34) ...
<class 'dict'>
--------------------
{'AAPL': ['Apple', 400, 188.0], 'MSFT': ['Microsoft', 300, 26.5], ... }
'''

# pretty print with json.dumps()
s = json.dumps(pfolio_dict2, sort_keys=True, indent=2)
print(type(s))
print('-'*20)
print(s)

''' result (Python34) ...
<class 'str'>
--------------------
{
  "AAPL": [
    "Apple",
    400,
    188.0
  ],
  "GOOG": [
    "Google",
    200,
    549.85
  ],
  "MSFT": [
    "Microsoft",
    300,
    26.5
  ],
  "YHOO": [
    "Yahoo",
    900,
    16.81
  ]
}

'''

print("Oct{0:o} = Dec{0:d}".format(25))

Counting days ...

''' datetime_diff_days103.py
get the difference in days between 2 given dates
'''

import datetime as dt

# user enters dates in yyyy-mm-dd format
dt_str1='2014-05-11'
dt_str2='2014-09-11'

date1 = dt.datetime.strptime(dt_str1, "%Y-%m-%d")
date2 = dt.datetime.strptime(dt_str2, "%Y-%m-%d")

date_diff = date2 - date1
print('Difference in days = {}'.format(date_diff.days))

''' result ...
Difference in days = 123
'''

Talking about "friggatriskaidekaphobia" the irrational fear of Friday the 13th ...

''' friday13th.py
find all the Friday the 13th of a given year
'''

import datetime as dt
import calendar as cd

# pick a year
year = 2015

begin_year = dt.date(year, 1, 1)
end_year = dt.date(year, 12, 31)

oneday = dt.timedelta(days=1)

friday_list = []
next_day = begin_year
for k in range(0, 366):
    if next_day > end_year:
        break
    if next_day.weekday() == cd.FRIDAY and next_day.day == 13:
        friday_list.append(next_day.strftime("%d%b%Y"))
    next_day += oneday

print("All Friday the 13th for {}:".format(year))
for item in friday_list:
    print(item)

''' result ...
All Friday the 13th for 2015:
13Feb2015
13Mar2015
13Nov2015
'''
more info
help("calendar")
help("datetime")

is there anyway to interup the current execution at anytime to do something and then resume the execution?

Editor's note:
Please start your own thread!

# SI prefixes
yotta = 1e24
zetta = 1e21
exa = 1e18
peta = 1e15
tera = 1e12
giga = 1e9
mega = 1e6
kilo = 1e3
hecto = 1e2
deka = 1e1
deci = 1e-1
centi = 1e-2
milli = 1e-3
micro = 1e-6
nano = 1e-9
pico = 1e-12
femto = 1e-15
atto = 1e-18
zepto = 1e-21

There is always room for one more word frequency program ...

''' Word_frequency2.py
experiments with string processing
preprocess the string and do a word frequency count

remove punctuation/whitespace with re
sort by frequency then word
dns
'''

from collections import Counter
import re
import pprint    


def sort_freq_word(tup):
    '''
    helper function for sorting of a list of (word, freq) tuples
    sort by looking at freq tup[1] first then word tup[0]
    the minus sign indicates reverse order sort for freq
    '''
    return (-tup[1], tup[0])


# sample text for testing (could come from a text file)
text = """\
A young executive was leaving the office at 6 pm when he found the CEO 
standing in front of a shredder with a piece of paper in hand. "Listen," 
said the CEO, "this is important, and my secretary has left. Can you
make this thing work?"

"Certainly," said the young executive. He turned the machine on, 
inserted the paper, and pressed the start button.

To the young executive's surprise the CEO said: 
"Excellent, excellent!" as his paper disappeared inside the machine. 
"I just need one copy."
"""

# convert text to all lower case
text = text.lower()

# use re to select words (remove punctuations and whitespace)
# \w+ means match 1 or more alphanumeric characters
# returns a list
words = re.findall(r'\w+', text)

# select the 10 most common words
# sorted by fequency (default)
common10 = Counter(words).most_common(10)

#print(Counter(words))
print("10 most common words sorted by frequency:")
for word, freq in common10:
    print("{:3d}  {}".format(freq, word))

print('-'*20)

print("10 most common words sorted by frequency then word:")
for word, freq in sorted(common10, key=sort_freq_word):
    print("{:3d}  {}".format(freq, word))


''' result ...
10 most common words sorted by frequency:
 10  the
  3  paper
  3  ceo
  3  a
  3  said
  3  young
  3  executive
  2  machine
  2  excellent
  2  and
--------------------
10 most common words sorted by frequency then word:
 10  the
  3  a
  3  ceo
  3  executive
  3  paper
  3  said
  3  young
  2  and
  2  excellent
  2  machine
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.