vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are some problems with Windows having Python27 and Python33 installed. Both executables are called Python.exe and one only can be the default.

You can force IDLE to run with a certain version using batch files ...

rem idle33.bat
rem run IDLE IDE with Python33
C:\Python33\pythonw.exe -u  C:\Python33\Lib\idlelib\idle.pyw

or ...

rem idle27.bat
rem run IDLE IDE with Python27
C:\Python27\pythonw.exe -u  C:\Python27\Lib\idlelib\idle.pyw

Best to use Portable Python for version 2.7.3 (it comes with a boatload of third party modules). You can move it to your hard drive or use it from a small USB-drive. Python 2.7.3 allows you to used many of the older example scripts, but you can bring in Python3 features with extra imports.

Installing IronPython and the SharpDevelop IDE does not give any registry problems with Windows. IronPython is version 2.7.3 Python syntax.

Above all, enjoy Python! It has a friendly syntax and is extremely powerful. The syntax is easy, the trick is to get to know the many well worked out modules.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Assuming you downloaded and installed Python with the python-2.7.3.msi installer, you can used a batch file like
c:/python27/python.exe -u c:/myscriptfolder/myscript.py

On a Windows machine you can also just double click on the script file. See:
http://www.daniweb.com/software-development/python/threads/20774/starting-python#post104865

Even better, download the portable version of Python and use the PyScripter IDE that comes with it. See:
http://www.portablepython.com/wiki/PortablePython2.7.3.1

IMHO, the problem with Eclipse and Pydev is that it's a hugely bloated and slow system.

If you want to do Windows GUI stuff you can use IronPython and the SharpDevelop IDE with a formbuilder that mimics the MS Studio IDE. Take a look at:
http://www.daniweb.com/software-development/python/threads/191210/python-gui-programming/11#post1888503

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

for d in data will give you list objects

Example ...

'''
contents of file or.csv:
1, 23.27, 23.21, 83.22
2, 34.25, 65.31, 34.75
'''

import csv

Or = csv.reader(open('Or.csv'))

for d in Or:
    print(d, type(d))

''' result ...
['1', ' 23.27', ' 23.21', ' 83.22'], <type 'list'>
['2', ' 34.25', ' 65.31', ' 34.75'], <type 'list'>
'''

You have to do something like this ...

'''
contents of file or.csv:
1, 23.27, 23.21, 83.22
2, 34.25, 65.31, 34.75
'''

import csv
import collections as co

def make_dict(data):
    return co.OrderedDict((d[0], d) for d in data if d)

Or = csv.reader(open('Or.csv'))
updated = make_dict(Or)
print(updated)

''' result ...
OrderedDict([('1', ['1', ' 23.27', ' 23.21', ' 83.22']), ('2', ['2', ' 34.25', ' 65.31', ' 34.75'])])
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you want a selected list of Fibonacci numbers, you can use this approach ...

''' fibo_selected_list1.py
get a selected list of Fibonacci numbers given start to end
'''

import itertools

def xfibo():
    '''
    a generator for Fibonacci numbers, goes
    to next number in series on each call
    '''
    current, previous = 0, 1
    while True:
        yield current
        # use a tuple swap
        current, previous = previous, current + previous

start = 1
end = 6
# get a selected list of Fibonacci numbers 1 - 6
print(list(itertools.islice(xfibo(), start, end+1)))

start = 5
end = 10
# get a selected list of Fibonacci numbers 5 - 10
print(list(itertools.islice(xfibo(), start, end+1)))

''' result ...
[1, 1, 2, 3, 5, 8]
[5, 8, 13, 21, 34, 55]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another look at format() and print() using local variable names ...

''' vars_format_printing1.py
using vars() in named formatted print
tested with Python273, Python33 and IronPython273
'''

name = 'Abigale'
age = 72

# vars() gives the local dictionary containing variables name and age as keys
# can be used for Python2 and Python3
print("Hello %(name)s, you are %(age)s years old." % vars())

# needs Python273 or Python3 and higher
print("Hello {name}, you are {age} years old.".format(**vars()))


''' result -->
Hello Abigale, you are 72 years old.
Hello Abigale, you are 72 years old.
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Get together with friends over some good chow and drink.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you are allowed to use join(), you can do this ...

mylist = [8, 7, 5, 4, 3, 2]
mystr = " ".join(str(n) for n in mylist)
print(mystr)

'''
8 7 5 4 3 2
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Without using join() you can do it this way ...

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

mystr = ""
space = " "
for n in mylist:
    mystr += str(n) + space

print(mystr)

'''
8 7 5 4 3 2 
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You will have to keep the PIL images in your list and convert them to something Tkinter can handle with photo=ImageTk.PhotoImage(image) just before you use them.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You have the pseudo code for your sort algorithm, so simply expand it to Python and test it ...

mylist = [5, 3, 7, 2, 8, 4]
print(mylist)
n = len(mylist)

for i in range(n):
    for j in range(1, n-i):
        # swap if prev value is less than current value
        # change < to > to reverse the order
        if mylist[j-1] < mylist[j]:
            # do a tuple swap
            (mylist[j-1], mylist[j]) = (mylist[j], mylist[j-1])

print(mylist)

''' result ...
[5, 3, 7, 2, 8, 4]
[8, 7, 5, 4, 3, 2]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nice approach! Here is another option to do this ...

''' tk_button_toggle2.py
use a list default argument to create a Tkinter toggle button
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def toggle(tog=[0]):
    '''
    a list default argument has a fixed address
    '''
    tog[0] = not tog[0]
    if tog[0]:
        t_btn.config(text='False')
    else:
        t_btn.config(text='True')

root = tk.Tk()

t_btn = tk.Button(text="True", width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()
BustACode commented: Good stuff. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A look at the Tkinter data Entry widget and the use of tk.StringVar() to handle the data ...

''' tk_StringVar_Entry1.py
use tk.StringVar() to handle Entry widget values
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def get_value():
    label['text'] = value.get()

def set_value():
    value.set("Hello DaniWeb")

def clear_value():
    value.set("")

root = tk.Tk()

value = tk.StringVar()

tk.Label(root, text='Enter something below: ').pack()
entry = tk.Entry(root, textvariable=value, bg='yellow')
entry.pack()
# put cursor in entry
entry.focus()

b1 = tk.Button(root, text="Show Entry Value", command=get_value)
b1.pack(pady=3)

b2 = tk.Button(root, text="Set Entry Value", command=set_value)
b2.pack(pady=3)

b3 = tk.Button(root, text="Clear Entry Value", command=clear_value)
b3.pack(pady=3)

# show get_value() results
label = tk.Label(root, text='<>'*5, fg='red')
label.pack(pady=3)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The California crunch really is the result of not enough power-generating plants and then not enough power to power the power of generating plants.
— George W. Bush

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The traditional Christmas dinner in England used to be a pig head prepared with a mustard sauce.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Lots of folks get married on the date. Easy wedding date for the husband to remember.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another approach to a circular list ...

'''' ringbuffer_function_deque1.py
using the Python deque module as a ringbuffer
as the buffer fills up first entries are dropped
tested wth Python27 and Python33
'''

import collections

def ringbuffer_10(mylist, dq=collections.deque(maxlen=10)):
    '''
    mimics a ringbuffer of default length 10
    you can change that to your needs
    '''
    for n in mylist:
        dq.append(n)
    return list(dq)

# testing ...
mylist = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
ringbuffer = ringbuffer_10(mylist)
print(ringbuffer)
print('-'*40)

# send more data
mylist = [22, 23, 24, 25]
ringbuffer = ringbuffer_10(mylist)
print(ringbuffer)

''' result ...
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
----------------------------------------
[16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can also move your lines on and off the canvas screen as shown in:
http://www.daniweb.com/software-development/python/code/442856/alternate-canvas-objects-tkinterpython

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can alternately show one of two lines drawn on the Tkinter canvas by simply moving them on and off the canvas screen. This beats a cumbersome create and delete cycle.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can also use the Tkinter canvas as a label...

''' tk_canvas_create_text1.py
show text at a given x, y location on a Tkinter canvas
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
root.title('Tkinter canvas text')

canvas = tk.Canvas(root, height=200, width=200, bg="yellow")
canvas.pack()

# select x, y cordinates for ulc start of text
x = 15
y = 20
sa = "Hello at x=%d, y+%d" % (x, y)
text_a = canvas.create_text(x, y, anchor='nw', text=sa)

x = 45
y = 80
sb = "Hello at x=%d, y+%d" % (x, y)
text_b = canvas.create_text(x, y, anchor='nw', text=sb)

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Comparing a number of different approaches to finding the closest pair of numeric elements in a list. The timing is done with the mpmath module, but you can also use Python module timeit.

Gribouillis commented: interesting test +13
snippsat commented: Thx for making a snippets with different approaches. +10
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Notice that a while loop mimics a recursive function rather closely. It should give you hints how to set it up ...

''' maxnum1.py
find the highest number in a list
not using Python's max(list) function
'''

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

maxnum = 0
index = 0
while True:
    num = mylist[index]
    # update maxnum to be the highest number
    if num > maxnum:
        maxnum = num
    # go to next index
    index += 1
    # exit condition
    if index >= len(mylist):
        break

print(maxnum)  # 7
# test
print(max(mylist))  # 7

Actually, while loops are faster then the high overhead recursive functions.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am glad you are using the __private option.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You could do something like this ...

# Guess the number game by Johnathan Millsap

import random

myName = input('Hello! What is your name? ')
level = int(input('Pick a level of difficulty (1 to 3): '))
# change range and number of allowed guesses with level
if level == 1:
    top = 100
    tries = 3
elif level == 2:
    top = 500
    tries = 6
else:
    top = 1000
    tries = 10
# create a '%' formatted string
sf = "Well, %s, I am thinking of a number between 1 and %d" 
print(sf % (myName, top))

# pick the random integer
number = random.randint(1, top)

print('Try to guess it!.')

guessesTaken = 0
while guessesTaken <= tries:
    guess = int(input('Take a guess: '))
    guessesTaken += 1
    if guess < number:
        print('Your guess is too low.')     
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break

if guess == number:
    # create a '%' formatted string
    sf = "Good job, %s! You guessed my number with %d guesses!"
    print(sf % (myName, guessesTaken))

if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An approach to create multiple GUI buttons (or other widgets) using list comprehension. In this case I used the Tkinter GUI toolkit that comes with the Python installation.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hmmm, I put it to the test ...

''' primelist_timing7.py
yet another primelist timing for speed
'''

import timeit

def time_function(stmt, setup):
    """use module timeit to time functions"""
    # to enable garbage collection start setup with 'gc.enable();'
    #setup = 'gc.enable();' + setup
    t = timeit.Timer(stmt, setup)
    # doing 10 passes * 100000 gives the time in microseconds/pass
    # (a little less precise but saves time)
    elapsed = (100000 * t.timeit(number=10))
    print("%-18s --> %0.2f microseconds/pass" % (stmt, elapsed))

def eras(n):
    """
    returns  a list of primes 2 to n n
    """    
    siv = range(n+1)
    siv[1] = 0
    sqn = int(round(n**0.5))
    for i in range(2, sqn+1):
        if siv[i] != 0:
            siv[2*i:n/i*i+1:i] = [0]*(n/i-1)
    return filter(None, siv)

def eras2(n):
    """
    returns  a list of primes 2 to n
    """    
    siv = range(n+1)
    siv[1] = 0
    sqn = int(round(n**0.5))
    for i in range(2, sqn+1):
        if siv[i] != 0:
            #siv[2*i:n/i*i+1:i] = [0]*(n/i-1)
            siv[i*i:n/i*i+1:i] = [0]*(n/i-i+1) 
    return filter(None, siv)

def eras_dns(n):
    """
    returns  a list of primes 2 to < n
    """
    sieve = [True] * (n>>1)
    for x in range(3, int(n**0.5)+1, 2):
        if sieve[x>>1]:
            sieve[(x*x)>>1::x] = [False] * ((n-x*x-1)//(x<<1)+1)
    return [2] + [(x<<1)+1 for x in range(1, n>>1) if sieve[x]]

# time the function
stmt = 'eras(1000000)'
setup = 'from __main__ import eras'
time_function(stmt, setup)

# time the function
stmt = 'eras2(1000000)'
setup = 'from __main__ import eras2'
time_function(stmt, setup)

# time the function
stmt = 'eras_dns(1000000)'
setup = 'from __main__ import eras_dns'
time_function(stmt, setup)

# extra test
print(eras(61))
print(eras2(61))
print(eras_dns(61))

''' result with …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would write the code like this ...

def newton_approx(x):
    """
    Newton's method to get the square root of x
    using successive approximations 
    """
    tolerance = 0.000001
    estimate = 1.0
    while True:
        estimate = (estimate + x / estimate) / 2
        difference = abs(x - estimate ** 2)
        if difference <= tolerance:
            break           
    return estimate

# test
x = 2
print("newton = %0.15f" % newton_approx(x))
print("x**0.5 = %0.15f" % (x**0.5))

'''
newton = 1.414213562374690
x**0.5 = 1.414213562373095
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The way sneekula has written the class code, it would be very easy to change for instance the name of the patient from outside the class ...

class Patient(object):
    # by convention class names are capitalized
    def __init__(self, ID, name, bdate, gender, phone, address):
        # assing class parameters to instance self
        self.ID = ID
        self.name = name
        self.address = address
        # and so on

    def get_name(self):
        "this is a class method, first arg is self"
        print("Patient name = %s" % self.name)

    def set_name(self, newname):
        "method to change the name"
        self.name = newname



# create an instance of the class
# data have to be in this order
# Patient(ID, name, bdate, gender, phone, address)
john = Patient("5640","John","8/8/88","m","334-456-7898","60 Hilltop")

# could be too easy to change the name by mistake
john.name = "Fred Flintstone"

john.get_name()  # Patient name = Fred Flintstone

To prevent this you can use the double underline prefix ...

class Patient(object):
    # by convention class names are capitalized
    def __init__(self, ID, name, bdate, gender, phone, address):
        # assing class parameters to instance self
        self.ID = ID
        # the double underline prefix keeps __name private to the class 
        self.__name = name
        self.address = address
        # and so on

    def get_name(self):
        "this is a class method, first arg is self"
        print("Patient name = %s" % self.__name)

    def set_name(self, newname):
        "method to change the name"
        self.__name = newname



# create an instance of the class
# data have to be in this order
# Patient(ID, name, bdate, gender, …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use certain pygame modules like the pygame mixer with Tkinter to play sounds.
However, IMHO for the application you want to use the pygame and the Tkinter event loops will clash.
You may have to use module threading to make this go.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You could use something like this ...

raw_data = '''\
10.25, 9.23, 8.97, 8.71, 8.40, 8.36, 8.30, 8.21
10.25, 9.23, 8.97, 8.71, 8.40, 8.36, 8.30, 8.61
0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15
0.60, 0.60, 0.60, 0.60, 0.50, 0.50, 0.50, 0.15
4.85, 2.85, 1.85, 1.25, 0.95, 0.85, 0.80, 0.45
1.35, 1.35, 1.35, 1.35, 1.10, 1.10, 1.10, 0.15
0.60, 0.60, 0.60, 0.60, 0.50, 0.50, 0.50, 0.15
0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.15
2.84, 1.84, 1.08, 0.58, 0.50, 0.25, 0.18, 0.15
26.85, 23.83, 21.57, 20.71, 19.85, 18.71, 17.60, 13.96
'''

space = ' '
csv_data = ""
for c in raw_data:
     if c != space:
         csv_data += c

print(csv_data)

'''result ...

10.25,9.23,8.97,8.71,8.40,8.36,8.30,8.21
10.25,9.23,8.97,8.71,8.40,8.36,8.30,8.61
0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15
0.60,0.60,0.60,0.60,0.50,0.50,0.50,0.15
4.85,2.85,1.85,1.25,0.95,0.85,0.80,0.45
1.35,1.35,1.35,1.35,1.10,1.10,1.10,0.15
0.60,0.60,0.60,0.60,0.50,0.50,0.50,0.15
0.40,0.40,0.40,0.40,0.40,0.40,0.40,0.15
2.84,1.84,1.08,0.58,0.50,0.25,0.18,0.15
26.85,23.83,21.57,20.71,19.85,18.71,17.60,13.96

'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one example ...

'''
show only the data lines that contain the search word
'''

# test data string
data = '''\
12347 10000 secretary James Harrison
12348 20000 secretary Jade Powell
12341 40000 consultant Adam Johnson'''

# pick a somewhat unique file name
fname = "aaatest123.txt"

# write out the data file
with open(fname, "w") as fout:
    fout.write(data)

search = 'secretary'

# read the data back in
with open(fname, "r") as fin:
    mylist = []
    for line in fin:
        line = line.rstrip()
        if search in line:
            mylist.append(line)

print(mylist)

'''result ...
['12347 10000 secretary James Harrison', '12348 20000 secretary Jade Powell']
'''

You can refine this to make it case insensitive or whole words only.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just experiment with this example ...

'''turtle_circle1.py
explore Python's turtle graphic circles

turtle.circle(radius, extent=None, steps=None)
turtle.color('red') --> set pen color and fill color

'''

import turtle as tu

tu.title('turtle circles and semi-circles')

# set turtle speed, default = 'normal'
# pick from ['fastest', 'fast', 'normal', 'slow', 'slowest']
tu.speed('fastest')

# optional ...
# turtle by default starts at (x=0, y=0) center of (~450x550) window
# to pick another center lift the pen up then move
# to the right x units and up y units or ...
# to the left -x units and down -y units
# now drop the pen down to start drawing
tu.up()
# move pen to x,y
tu.goto(0,-150)
tu.down()

# default pen width is 1
tu.width(2)

# draw a solid blue circle
tu.color('blue')
tu.begin_fill()
tu.circle(200)
tu.end_fill()

# adust center of semi circles
tu.up()
tu.goto(0,-100)
tu.down()

# extent=180 degrees implies a semi circle counter-clockwise from start
# draw a solid red semicircle
tu.color('red')
tu.begin_fill()
tu.circle(150, 180)
tu.end_fill()

# followed by a solid yellow semi circle
# beware of where the turtle points to
tu.color('yellow')
tu.begin_fill()
tu.circle(150, 180)
tu.end_fill()

# adust center of white circle
tu.up()
tu.goto(0,-50)
tu.down()

# draw a solid white circle
tu.color('white')
tu.begin_fill()
tu.circle(100)
tu.end_fill()

tu.done()

Display --> http://prntscr.com/kzmq9

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a small example showing how to draw circles with PySide (public PyQT). I used LightShot to capture the display, which gives you a link to the picture. http://prntscr.com/kw6b6

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Albert Einstein:
"Ich fürchte den Tag, an dem die Technologie unsere Menschlichkeit überholt. Die Welt wird dann eine Generation von Idioten sein."

"I fear the day technology will pass by humanity. The world will then be a generation of idiots."

Early signs ...
http://prntscr.com/kzf04

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This code shows how to obtain and display a GIF image from an internet website using the Tkinter GUI toolkit that comes with the Python installation.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's say you have a whole bunch of nicely named lists and want to save them all and their names in a pickle file. One solution can be to store these lists and their names in a Bag container class and pickle the bag instance object. Now you can use the lists and their names in another program, as long as you insert class Bag_Dict in that program and load the pickle file.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

BigPaw ...

wxPython is slowly ported to Python3 and is also modernized which takes time, the project is called 'Phoenix'. Look at this example:
http://www.daniweb.com/software-development/python/threads/191210/python-gui-programming/11#post1892083

Going from XP to Vista was a step back!

Going from Python2 to Python3 is a step foreward, much has been streamlined and modernized. For the time being using Python 2.7.3 will make your life easier, since you can use much of the older code samples without change. Python3 handles foreign characters better. There are some syntax changes, but the difference between strings and byte-strings will bite you the most.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

HiHe ...
The SharpDevelop IDE uses IronPython to produce executable files.
Here is a test ...

'''
code executed on SharpDevlop 4.2 IDE
Python console solution

used:
IronPython-2.7.3.msi
from:
http://ironpython.net/download/ 
and:
SharpDevelop_4.2.2.8818_Setup.msi
from:
http://www.icsharpcode.net/OpenSource/SD/Download/#SharpDevelop4x

the IDE was installed after the IronPython27 installation
the 'Run compiled exe' produced 2 files in folder
C:\SharpDevelop\sd_projects\py_version\py_version\bin\Debug
py_version.exe
py_version.dll

'''

import sys

print("Python version:\n %s\n" % sys.version)

# wait
raw_input("Press Enter to go on ...")

'''
Python version:
 2.7.3 (IronPython 2.7.3 (2.7.0.40) on .NET 4.0.30319.296 (32-bit))

Press Enter to go on ...

'''

See also:
http://www.daniweb.com/software-development/python/threads/191210/python-gui-programming/11#post1888503

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Well, why not?
I am hopping on the wxPython project Phoenix bandwagon with this example ...

'''wxp_StaticBitmap_image_b64_1.py

for smaller images it is best to embed the image as base64 encoded 
string and then convert this string to a bitmap

tested with Python 2.7.3 and Python 3.2.3 and wx/wx-phoenix by vegaseat
'''

import wx
import io
import base64
import sys


class ImagePanel(wx.Panel):
    """ create a panel with a wx.StaticBitmap """
    def __init__(self, parent, bmp):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        # show the static bitmap
        wx.StaticBitmap(self, wx.ID_ANY, bmp, pos=(50, 40))


# a typical base64 encoded image string
# see:
# http://www.daniweb.com/software-development/python/code/440446/python2python3-base64-encoded-image
rainbow_jpg_b64='''\
/9j/4AAQSkZJRgABAQEAyADIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAoACgDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoq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bytes = base64.b64decode(rainbow_jpg_b64)
    data_stream = io.BytesIO(jpg_bytes)
    bmp = wx.BitmapFromImage(wx.ImageFromStream(data_stream))
except TypeError:
    # Python3 wx-phoenix
    jpg_bytes = base64.b64decode(rainbow_jpg_b64.encode())
    data_stream = io.BytesIO(jpg_bytes)
    bmp = wx.Bitmap(wx.Image(data_stream))

# create window/frame
frame = wx.Frame(None, wx.ID_ANY, size = (400, 300))
# create the panel instance
ImagePanel(frame, bmp)
# show the frame
frame.Show()
# start the GUI event loop
app.MainLoop()

One complication is that you now you have to make sure that the code works with Python2 and Python3.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a smaller image, you can include it in your program as a base64 encoded string. This way you don't have to worry about an image file to go with your code. In your program you can then decode it back to the familiar bytes of an image and use it. This code snippet should work with Python2 and Python3 versions.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example how to compile the previous code example to a Windows .exe program ...

'''ip_compile_DataEntry1.py
compile an ironpython sript file to an executable file
creates a Windows .exe file and an associated .dll file

it is best to put this file into a special directory
together with the ironpython script file you want to compile
then run it with 
ipy.exe ip_compile_DataEntry1.py
I simply used the ConTEXT IDE configured to run IronPython.

----------------------------------------------------
info about pyc: The Command-Line Python Compiler

Usage: ipy.exe pyc.py [options] file [file ...]

Options:
/out:output_file    Output file name (default is main_file.<extension>)
/target:dll     Compile only into dll.  Default
/target:exe     Generate console executable stub for startup in addition to dll.
/target:winexe  Generate windows executable stub for startup in addition to dll.
/? /h               This message

EXE/WinEXE specific options:
/main:main_file.py       Main file of the project (module to be executed first)
/platform:x86            Compile for x86 only
/platform:x64            Compile for x64 only

Example:
ipy.exe pyc.py /main:myprogram.py myform.py /target:winexe

creates myform.exe and associated myform.dll
---------------------------------------------------
needs IronPython 2.7 or higher
'''

import subprocess

# the IronPython script file you want to convert ...
ip_scriptfile = "ip_DataEntry1.py"

# location of IronPython and compile utility
ipython = "C:/IronPython27/ipy.exe"
utility = "C:/IronPython27/Tools/Scripts/pyc.py",
main = "/main:" + ip_scriptfile
target = "/target:winexe"
subprocess.call([ipython, utility, main, target])    

The above program creates two files you need to run ...
ip_DataEntry1.exe (executable stub, size = 3k)
ip_DataEntry1.dll (size = 32k)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A generic data entry and processing program written in IronPython ...

'''ip_DataEntry1.py
a colorful IronPython generic data entry form
tested with IronPython 2.7 and MS.NET Framework 4.0
'''

import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

#
# start of code mostly created with the SharpDevelop4 IDE Formbuilder
#
import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

class MainForm(Form):
    def __init__(self):
        self.InitializeComponent()

    def InitializeComponent(self):
        self._groupBox1 = System.Windows.Forms.GroupBox()
        self._groupBox2 = System.Windows.Forms.GroupBox()
        self._button1 = System.Windows.Forms.Button()
        self._label1 = System.Windows.Forms.Label()
        self._label2 = System.Windows.Forms.Label()
        self._label3 = System.Windows.Forms.Label()
        self._textBox1 = System.Windows.Forms.TextBox()
        self._textBox2 = System.Windows.Forms.TextBox()
        self._textBox3 = System.Windows.Forms.TextBox()
        self._groupBox1.SuspendLayout()
        self._groupBox2.SuspendLayout()
        self.SuspendLayout()
        # 
        # groupBox1
        # 
        self._groupBox1.BackColor = System.Drawing.Color.YellowGreen
        self._groupBox1.Controls.Add(self._textBox2)
        self._groupBox1.Controls.Add(self._textBox1)
        self._groupBox1.Controls.Add(self._label2)
        self._groupBox1.Controls.Add(self._label1)
        self._groupBox1.Location = System.Drawing.Point(12, 12)
        self._groupBox1.Name = "groupBox1"
        self._groupBox1.Size = System.Drawing.Size(301, 133)
        self._groupBox1.TabIndex = 0
        self._groupBox1.TabStop = False
        self._groupBox1.Text = "Data Entry"
        # 
        # groupBox2
        # 
        self._groupBox2.BackColor = System.Drawing.Color.PowderBlue
        self._groupBox2.Controls.Add(self._textBox3)
        self._groupBox2.Controls.Add(self._label3)
        self._groupBox2.Location = System.Drawing.Point(12, 184)
        self._groupBox2.Name = "groupBox2"
        self._groupBox2.Size = System.Drawing.Size(301, 66)
        self._groupBox2.TabIndex = 1
        self._groupBox2.TabStop = False
        self._groupBox2.Text = "Result"
        # 
        # button1
        # 
        self._button1.BackColor = System.Drawing.Color.Bisque
        self._button1.Location = System.Drawing.Point(12, 155)
        self._button1.Name = "button1"
        self._button1.Size = System.Drawing.Size(301, 23)
        self._button1.TabIndex = 2
        self._button1.Text = "Press to process data"
        self._button1.UseVisualStyleBackColor = False
        self._button1.Click += self.Button1Click
        # 
        # label1
        # 
        self._label1.Location = System.Drawing.Point(6, 27)
        self._label1.Name = "label1"
        self._label1.Size = System.Drawing.Size(100, 23)
        self._label1.TabIndex = 0
        # change this text for your own use
        self._label1.Text = "Enter Name:"
        # 
        # label2
        # 
        self._label2.Location = System.Drawing.Point(6, 77)
        self._label2.Name = "label2"
        self._label2.Size = System.Drawing.Size(100, 23)
        self._label2.TabIndex = 1
        # change this text for your own use
        self._label2.Text = "Enter Age:"
        # …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can also go smart with this ...

'''count_vowels1.py
using class Counter to count vowels in a text
'''

from collections import Counter

text = '''
Python? That is for children. A Klingon Warrior
uses only machine code, keyed in on the front
panel switches in raw binary.
'''
vowels = 'aeiou'

# method most_common() sorts by most common vowel(s) first
vowels_count = Counter(c for c in text if c in vowels).most_common()

print(vowels_count)
print(vowels_count[0])

'''result ...
[('i', 9), ('e', 9), ('o', 8), ('a', 6), ('u', 1)]
('i', 9)
'''

You can also go all lower case with
text = text.lower()

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just in case you have a bum sound file. Does this work ...

'''pg_sound_wav.py
play a wave sound file with pygame
'''

import pygame
pygame.mixer.init()

sound = pygame.mixer.Sound('hey.wav')
# play the actual sound
sound.play()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another option ...

with open('PyTest.txt', 'w') as fout:
    for i in range(0, 105, 5):
        fout.write(str(i) + ' ')

'''content of file PyTest.txt ... 
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 
'''

If you want to use formatting, then do something like this ...

with open('PyTest.txt', 'w') as fout:
    for i in range(0, 105, 5):
        sf = "{} ".format(i)
        fout.write(sf)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python experiment to get an image from a web page and save it to an image file. Updated code to work with both Python versions ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would go with jlm699 ...

sys.path lists all the directories Python will check, so simply append it with the path of a directory you have created for all your modules.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

54% of jobs in San Jose, California fall within the area of IT, but only 2% of students in the area are graduating with IT degrees.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

“Computers are useless. They can only give you answers.”
... Pablo Picasso

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is another approach ...

'''card_deck_5.py
create a deck of cards, shuffle and draw a hand of five cards
suit: club=C, diamond=D, heart=H spade=S
rank: ace=A, 10=T, jack=J, queen=Q, king=K, numbers=2..9
ace of spade would be AS, 8 of heart would be 8H and so on ...
'''

import random

def create_deck():
    """
    create a full deck of cards as a list of codes
    """
    ranks = "A23456789TJQK"
    suits = "CDHS"
    deck = [rank + suit for rank in ranks for suit in suits]
    return deck

def shuffle_deck(deck):
    random.shuffle(deck)
    return deck

deck = create_deck()
shuff = shuffle_deck(deck)
# pull five cards and show
card5 = shuff[:5] 
print(card5)
print('-'*30)
# sorted by rank
print(sorted(card5))
# sorted by suit
print(sorted(card5, key=lambda x: x[1]))

'''possible result ...
['4S', '2D', '2H', 'QS', '4D']
------------------------------
['2D', '2H', '4D', '4S', 'QS']
['2D', '4D', '2H', '4S', 'QS']
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Nothing succeeds like the appearance of success."
... Christopher Lasch