ZZucker 342 Practically a Master Poster

Python 2.7.3 has all the features of Python2 and also allows you to bring in features of Python3. Python3 has a lot of changes when it comes to byte strings that can bite (no pun intended) a beginner trying to use older code examples.

ZZucker 342 Practically a Master Poster

I would stick with a list of tuples and module pickle to save/dump and load the container object. Use a list of lists if you want to edit the contents.

ZZucker 342 Practically a Master Poster

What does your file look like?
Did you save it as a CSV file from excel?

ZZucker 342 Practically a Master Poster

A code snippet to search a folder full of of C code files for a given keyword/searchword. Maybe add some wildcard options.

ZZucker 342 Practically a Master Poster

The Phoenx project at least makes an attempt to create a half way good documentation for wxPython.

ZZucker 342 Practically a Master Poster

Thanks Lardmeister for pointing out that the introduction of byte strings in Python3 makes quite a few changes to Python2 code. I guess it eliminates some of the unicode problems.

ZZucker 342 Practically a Master Poster

What are modules ogr and osr?

ZZucker 342 Practically a Master Poster

Generally:

import os

filename = "example.txt"
if os.path.exists(filename):
    print("file %s exists" % filename))
    # now do something with the file
ZZucker 342 Practically a Master Poster

After a hint from Snippsat and Lardmeister I tested out wxPython Phoenix, a project still in development that modernizes wxPython and also makes it work for Python3:

'''wxp_html.HtmlWindow_101.py
exploring wxPython's
wx.html.HtmlWindow(parent, id, pos, size, style, name)
to show colourful text using relatively simple html code

for Python32 download the new wx phoenix version
(still in development, but works fairly well)
here the Windows version dated 11/12/2012
wxPython-Phoenix-r72945-win32-py3.2.tar.gz
from
http://wxpython.org/Phoenix/snapshot-builds/
then simply extract the wx folder to
C:\Python32\Lib\site-packages
'''

import wx
import wx.html

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, html_code):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle,
            size=mysize)

        htmlwin = wx.html.HtmlWindow(self, wx.ID_ANY, style=wx.NO_BORDER)
        htmlwin.SetPage(html_code)


# simple HTML code ...
# text between <B> and </B> is bold
# <BR> inserts a line break (or new line)
# text between <FONT color="blue"> and </FONT> is that color
# text between <H3> and </H3> is header size
# etc. etc. just experiment with the <> tags
html_code = """\
This shows you how to display text in color
<BR>
<FONT color="blue">like blue text</FONT>
<FONT color="red"> or red text</FONT>
<B> or want to see it bold ...</B>
<BR>
<H3>or large size</H3><H2> or larger size</H2>
<BR>
<FONT size="+4">or even larger size</FONT>
<BR>
<FONT color="brown" size="+4">larger size and color</FONT>
<BR><BR>
... and yes, you can do scientific things like this ...
<BR>
H<sub>2</sub>O
<BR>
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
"""

app = wx.App(0)
mytitle =  "wx.html.HtmlWindow formatted text"
width = 450
height = 380
frame = MyFrame(None, mytitle, (width, height), html_code)
frame.Show(True)
frame.Center() …
ZZucker 342 Practically a Master Poster

If you quickly want to try your Python code (Python2 or Python3), you can use the online IDE at:
ideone.com

It also lets you use many other languages.

Examples:
http://ideone.com/nj2Tqo
http://ideone.com/Vwo7xR

ZZucker 342 Practically a Master Poster

Put a test print(f(guess)) after guess = 1.0 and see.

ZZucker 342 Practically a Master Poster

Generally the lines are read and tested with something like this:

for line in open ('test.txt', "r"):
    print line  # test
ZZucker 342 Practically a Master Poster

Then simply do something like this:

mylist = [0x123D, 0xFFFF, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
newlist = (mylist[:mylist.index(0xFFFF, 2)])[::-1]
ZZucker 342 Practically a Master Poster

Hint, in program 1 you need to read all the lines. Right now you are only reading one line.

ZZucker 342 Practically a Master Poster

Maybe this:

mylist = [0x123D, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
newlist = (mylist[:mylist.index(0xFFFF)])[::-1]
ZZucker 342 Practically a Master Poster

You can also try this:

    def incSpeed(self, event):
        print("Test", event.keysym)
ZZucker 342 Practically a Master Poster

Tkinter bind passes an event argument that you have to take care of even if you don't use it:

from tkinter import *

class App:

    def __init__(self, master):

        self.left = 0
        self.right = 0
        widget = Label(master, text='Hello bind world')
        widget.config(bg='red')
        widget.config(height=5, width=20)
        widget.pack(expand=YES, fill=BOTH)

        widget.bind('<Up>',self.incSpeed)
        widget.focus()

    def incSpeed(self, event):
        print("Test")

root = Tk()
app = App(root)
root.mainloop()
ZZucker 342 Practically a Master Poster

A little help:

name = "JHoneS."
print(name.upper())  # JHONES.
ZZucker 342 Practically a Master Poster

Maybe you mean something like this:

def create_string_list(mylist):
    string_list = ""
    for item in mylist:
        string_list += str(item) + '\n'
    return string_list


mylist = ['1','2','a','b']
string_list = create_string_list(mylist)
print(string_list)

'''result>>
1
2
a
b
'''
3e0jUn commented: Thanks! That was exactly what I wanted +1
ZZucker 342 Practically a Master Poster

To prevent some jerko to delete files from your disk with function eval(string), simply add this extra line:

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
if 'os' not in math_expression:
    result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))
ZZucker 342 Practically a Master Poster

You can also use the Python function eval():

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))
ZZucker 342 Practically a Master Poster

If you want to span over 2 rows (rows 4 and 5) use:
text.grid(row=4, column=1, rowspan=2)

ZZucker 342 Practically a Master Poster

You could add a few test prints:

# write a test file
data = '177'
with open('money.$','w') as fout:
    fout.write(data)

# read file back in
money_file = open('money.$','r').read()
# test print value and type
print money_file, type(money_file)

'''result >>
177 <type 'str'>
'''

if money_file:
    money = int(money_file)
    print money
ZZucker 342 Practically a Master Poster

A little bit more univeral:

def clear_screen():
    """
    clear the screen in the command shell
    works on windows (nt, xp, Vista) or Linux
    """
    import os
    os.system(['clear','cls'][os.name == 'nt'])
ZZucker 342 Practically a Master Poster

Ice cream and peppermint schnaps

ZZucker 342 Practically a Master Poster

Join the Air Force and bomb the beast called boredom.

ZZucker 342 Practically a Master Poster

In your if statement (i) is a string and (len(s) - 1) gives an integer.
Just a note, don't use sum and str, those are in the Python syntax. Also l gets easily confused with the number 1.

Since you are already using slicing, why not this:

# a simple palindrome function

def palindrome(mystr):
    # test prints
    print mystr
    # this is mystr reversed via slicing
    print mystr[::-1]
    if mystr == mystr[::-1]:
        print "is a palindrome"
    else:
        print "is not a palindrome"

# test the function
mystr = "racecar"
palindrome(mystr)

print '-'*30

mystr = "racecars"
palindrome(mystr)
ZZucker 342 Practically a Master Poster

Here is the modification of vegaseat's code that will work with both Python27 and Python32:

# create a sound file in AU format playing a sine wave
# of a given frequency, duration and volume
# vegaseat code modified to work with Python27 and Python32

from struct import pack
from math import sin, pi

def au_file(name='test.au', freq=440, dur=1000, vol=0.5):
    """
    creates an AU format sine wave audio file
    of frequency freq (Hz)
    of duration dur (milliseconds)
    and volume vol (max is 1.0)
    """
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write(pack('>4s5L', '.snd'.encode("utf8"), 24, 8*dur, 2, 8000, 1))
    factor = 2 * pi * freq/8000
    # write data
    for seg in range(8 * dur):
        # sine wave calculations
        sin_seg = sin(seg * factor)
        val = pack('b', int(vol * 127 * sin_seg))
        fout.write(val)
    fout.close()
    print("File %s written" % name)


# test the module ...
if __name__ == '__main__':
    au_file(name='sound440.au', freq=440, dur=2000, vol=0.8)

    # if you have Windows, you can test the audio file
    # otherwise comment this code out
    import os
    os.startfile('sound440.au')
ZZucker 342 Practically a Master Poster

You go to the store to buy a pound of Tshibo Java, your favorite coffee beans. There you are confronted with a dilema, the usual pound container costs $10. But the store offers you a choice, a new container with 33% more beans for $10 or the one pound container for a 33% discount.

Write a Python program to figure out which deal is the best, or are they the same?

vegaseat commented: economics 101 +14
ZZucker 342 Practically a Master Poster

Given the length of three sides, write a function that checks if it is possible to create a triangle.

ZZucker 342 Practically a Master Poster

The Eric5 IDE for Python has a built-in Icon Editor
(Extras/Tools/Icon Editor)

ZZucker 342 Practically a Master Poster

Once you learn which statement blocks belong together, then indentation makes more sense. Just think about it. It's all rather logical:

# Jason Edgel
# Program to find max value

def function_max(value1, value2):
    if value1 > value2:
        return value1
    else:
        return value2


# get the two integer values
value1 = input("Please enter first integer value: ")
value2 = input("Please enter second integer value: ")

# call the function
max_value = function_max(value1, value2)

# show the result
print "Max value = ", max_value
ZZucker 342 Practically a Master Poster

Try something like this:

# A program to calculate date of Easter

def calc_easter(year):

    if year in range(1982, 2049):
        a = year % 19
        b = year % 4
        c = year % 7
        d = ((19*a) + 24)%30
        e = ((2*b) + (4*c) + (6*d) + 5)%7
        f = 22 + d + e
        if f <= 31:
            print(" Easter in on March %d" % f)
        else:
            print("Easter is on April %d" % (f - 31))
    else:
        print("Year is not within range")

year = int(input('Enter a year between 1982-2048 '))
calc_easter(year)
ZZucker 342 Practically a Master Poster

A RAD GUI Building IDE for Python using wxPython:
http://sourceforge.net/projects/boa-constructor/

See also:
http://www.daniweb.com/software-development/python/threads/20774/starting-python/6#post400296

If you use Python3 you can go with the Eric5 IDE.
That program is free and uses the powerful PyQT GUI toolkit.
That in turn comes with a designer (form builder).
Google for Eric5

PyQT4 free from:
http://www.riverbankcomputing.co.uk/software/pyqt/download

See also:
http://www.daniweb.com/software-development/python/threads/419902/best-python-ide#post1798001

ZZucker 342 Practically a Master Poster

Is it true that the development of wxPython is dead?

ZZucker 342 Practically a Master Poster

The Python function range() handles only integers. Here is a range generator that handles floats:

# a floating point range generator with roundoff-fix
# works with Python2 and Python3

def frange(start, stop=None, step=1.0, delta=0.0000001):
    """
    a range generator that handles floating point numbers
    uses delta fuzzy logic to avoid float rep errors
    eg. stop=6.4 --> 6.3999999999999986 would slip through
    """
    # if start is missing it defaults to zero
    if stop == None:
        stop = start
        start = 0
    # allow for decrement
    if step <= 0:
        while start > (stop + delta):
            yield start
            start += step
    else:
        while start < (stop - delta):
            yield start
            start += step

# testing ...
# expect numbers 6.0 to 6.3
for k in frange(6.0, 6.4, 0.1):
    print("%f" % k)

'''my result -->
6.000000
6.100000
6.200000
6.300000   okay!
'''
ZZucker 342 Practically a Master Poster

Sometimes you have to flatten a deeply nested list or tuple:

# flatten a nested list

def flatten(seq):
    mylist = []
    for item in seq:
        if isinstance(item, (list, tuple)):
            # recursive function
            mylist.extend(flatten(item))
        else:
            mylist.append(item)
    return mylist

nested_list = [1, 2, [3, 4, [5, 6, [7, 8]]]]
print(nested_list)
print('nested list flattened:')
print(flatten(nested_list))

'''result-->
[1, 2, [3, 4, [5, 6, [7, 8]]]]
nested list flattened:
[1, 2, 3, 4, 5, 6, 7, 8]
'''
ZZucker 342 Practically a Master Poster

You can use Python to check the size of a given directory (folder):

# determine the size of a given folder in MegaBytes

import os

# pick a folder you have ...
folder = r'C:\Python32\DLLs'

folder_size = 0
for (path, dirs, files) in os.walk(folder):
    for file in files:
        filename = os.path.join(path, file)
        folder_size += os.path.getsize(filename)

print("Folder %s = %0.1f MB" % (folder, folder_size/(1024*1024.0)))

'''possible result -->
Folder C:\Python32\DLLs = 5.6 MB
'''
ZZucker 342 Practically a Master Poster

You can set up a function decorator using a class:

# using a Python class as a decorator

class StripCharacters:
    """
    a decorator class to strip given chrs from string text
    by default strip common punctuation marks --> ,.?!:;
    """
    def __init__(self, func, chrs=",.?!:;"):
        self.chrs = chrs
        self.func = func

    def __call__(self, text):
        """
        allows the class instance to be called as a function
        """
        # do the stripping
        new_text = ''.join(c for c in text if c not in self.chrs)
        return self.func(new_text)

@StripCharacters
def print_text(text):
    print(text)

text1 = 'If you are here, you are lost!'
print_text(text1)

print('-'*30)

text2 = 'common punctuation marks are ,.?!:;'
print_text(text2)

'''my result -->
If you are here you are lost
------------------------------
common punctuation marks are 
'''
ZZucker 342 Practically a Master Poster

You can use lambda to set up a function:

# works with Python27 and Python32

# a recursive denary to binary function via lambda
d2b = lambda d: (not isinstance(d,int) or (d==0)) and '0' \
    or (d2b(d//2)+str(d%2))


den = 255
print("denary = %d" % den)
binary = d2b(den)
print("binary = %s" % binary)
# check reult with function bin()
print("binary = %s via bin(%d)" % (bin(den), den))

'''result -->
denary = 255
binary = 011111111
binary = 0b11111111 via bin(255)
'''
ZZucker 342 Practically a Master Poster

Time a function with a timing decorator:

# time relatively time consuming functions
# with a decorator function
# apply the decorator right above the function
# you want to time, starting with a @
# works with Python27 and Python32
# (use module timeit for faster functions)

import time

def print_timing(func):
    """set up a decorator function for timing"""
    def wrapper(*arg):
        t1 = time.time()
        res = func(*arg)
        t2 = time.time()
        print('%s took %0.3f ms' % (func.__name__, (t2-t1)*1000.0))
        return res
    return wrapper

@print_timing
def get_primes(n):
    """
    standard optimized sieve algorithm to get a list
    of prime numbers from 2 to < n, prime numbers are
    only divisible by unity and themselves
    (1 is not considered a prime number)
    """
    if n < 2:  return []
    if n == 2: return [2]
    # do only odd numbers starting at 3
    s = list(range(3, n+1, 2))
    # n**0.5 simpler than math.sqr(n)
    mroot = n ** 0.5
    half = len(s)
    i = 0
    m = 3
    while m <= mroot:
        if s[i]:
            j = (m*m-3)//2
            s[j] = 0
            while j < half:
                s[j] = 0
                j += m
        i += 1
        m = 2*i+3
    # skip all zero items in list s
    return [2]+[x for x in s if x]


print( "prime numbers from 2 to <10,000,000 using a sieve algorithm")
prime_list = get_primes(10000000)

'''my result with Python32 -->
prime numbers from 2 to <10,000,000 using a sieve algorithm
get_primes took 2632.000 ms

just a note, result with Python27 -->
get_primes took 2394.000 ms
'''
ZZucker 342 Practically a Master Poster

One way to get your IP:

# get your ip
# Python32

import urllib.request

def get_external_ip():
    '''returns a string'''
    url = "http://automation.whatismyip.com/n09230945.asp"
    ipb = urllib.request.urlopen(url).read()
    # decode <class 'bytes'> to string
    ip = ipb.decode("utf8")
    return ip

print(get_external_ip())
ZZucker 342 Practically a Master Poster
# 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 342 Practically a Master Poster
# 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 342 Practically a Master Poster

A number of things wrong here, see the comments in the code:

# guess the number in a GUI

from tkinter import *
import random


class Application(Frame):
    ''' GUI guess the number application  '''
    def __init__(self, master):
        '''initialise frame'''
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
        # create the random number self.rnumber
        # notice the different name of this method
        self.pick_rnumber()

    def create_widgets(self):
        '''create widgets for GUI guess game'''
        #Create title label
        Label(self, text = 'Guess the number'
              ).grid(row = 0, column = 1, columnspan = 2, sticky = N)
        # create instruction labels
        Label(self, text = 'I am thinking of a number between 1 and 100'
              ).grid(row = 1, column = 0, columnspan = 3, sticky = W)

        Label(self, text = 'Try to guess in as few attempts as possible'
              ).grid(row = 2, column = 0, columnspan = 3, sticky = W)

        Label(self, text = 'I will tell you to go higher or lower after each guess'
              ).grid(row = 3, column = 0, columnspan = 3, sticky = W)
        # Create a label and number entry
        Label(self, text = 'Your guess: '
              ).grid(row = 4, column = 0, sticky = W)
        self.guess_ent = Entry(self)
        self.guess_ent.grid(row = 4, column = 1, sticky = W)
        # put cursor in entry
        self.guess_ent.focus()
        # create label and text box for number of tries
        Label(self, text = ' number of tries: '
              ).grid(row = 5, column = 0, sticky = W)
        self.no_tries_txt = Text(self, width = 2, height = 1, wrap = NONE)
        self.no_tries_txt.grid(row = 5, …
ZZucker 342 Practically a Master Poster

The proper way to save a dictionary object is with Python module pickle. Here is an example:

# use module pickle to save/dump and load a dictionary object
# or just about any other intact object
# use modes "wb" and "rb" to work with Python2 and Python3

import pickle

# create the test dictionary
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"

# pickle dump the dictionary to a file
fout = open("dict1.dat", "wb")
pickle.dump(before_d, fout)
fout.close()

# pickle load the dictionary from a file
fin = open("dict1.dat", "rb")
after_d = pickle.load(fin)
fin.close()

print(before_d)  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
print(after_d)   # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
HiHe commented: nice +4
ZZucker 342 Practically a Master Poster

Ah, I always wanted something like that:

# an input generator for strings
# works with Python2 or Python3

try:
    input = raw_input
except:
    pass

def input_generator(prompt='> ', stop=''):
    '''
    keep asking for input until stop value entered
    '''
    while True:
        inp = input(prompt)
        if inp.lower() == stop.lower():
            return
        yield inp

# test
print('Enter names you want in the list (press just Enter to end input loop): ')

mylist = [inp for inp in input_generator('>> ')]

print(mylist)

''' possible output:
Enter names you want in the list (press just Enter to end input loop): 
>> Fred
>> Karl
>> Paul
>> Helga
>> 
['Fred', 'Karl', 'Paul', 'Helga']
'''
ZZucker 342 Practically a Master Poster

You would be better off to use a Python IDE like IDLE (comes with Python) or Eric5.
Notepad++ is more geared for html development.

ZZucker 342 Practically a Master Poster

Barbara Bush and Willard Mitt Romney are firends?

ZZucker 342 Practically a Master Poster

The largets hailstone recovered in the USA was found in Aurora, Nebraska on June 22. 2003. It measured 7 inches in diameter. .The hailstone is now at the National Center for Atmospheric Research in Boulder, Colorado, where it is preserved in a special chiller.