sneekula 969 Nearly a Posting Maven

If you send unicode strings out, please notice that:

# a string with \u unicode characters
mystring = '\u00bfC\u00f3mo es usted?'
# or ...
mystring = "¿Cómo es usted?"
bytestring = mystring.encode("utf8")

This gives the same bytestring that can be used with quopri.encodestring(bytestring) in the code I mentioned. Bytestrings (bytearrays) are probably the reason why the unicode() function has been dropped from Python3.

sneekula 969 Nearly a Posting Maven

Here is a mildly better example:

# using Python module quopri for MIME strings used in emails
# Python 3.1

import quopri

mystring = '\u00bfC\u00f3mo es usted?'
bytestring = mystring.encode("utf8")

# the MIME string you send
enctext = quopri.encodestring(bytestring)
print(enctext)
print(type(enctext))

# the MIME string you receive
dectext = quopri.decodestring(enctext)
print(dectext)
print(type(dectext))

# convert to printable regular string
print(dectext.decode("utf8"))

"""my result -->
b'=C2=BFC=C3=B3mo es usted?'
<class 'bytes'>
b'\xc2\xbfC\xc3\xb3mo es usted?'
<class 'bytes'>
¿Cómo es usted?
"""

Just imagine that the escaped bytes could be from an image source.

sneekula 969 Nearly a Posting Maven

The source string has to be a string of bytes, just like you would get from a binary read of a file.
So try:

import quopri

enctext = quopri.encodestring(b'hello')
print(enctext)
print(type(enctext))
sneekula 969 Nearly a Posting Maven

Here is a basic template of a window, 2 buttons and a label using the pygtk toolkit:

# a very basic pygtk window template
# with two buttons and one label
# snee

import pygtk
pygtk.require('2.0')
import gtk

class MyWindow(object):
    def __init__(self):
        # type=gtk.WINDOW_TOPLEVEL is default
        self.window = gtk.Window()
        # pygtk needs this
        # attach destroy signal to terminate application properly
        self.window.connect("destroy", lambda w: gtk.main_quit())
        # title bar caption
        self.window.set_title("gtk.Window template")
        # put upper left corner on display coordinates (x, y)
        self.window.move(100, 80)
        # resize(width, height)
        self.window.resize(350, 150)
        
        # create 2 button widgets and a label widget
        button1 = gtk.Button("Button 1")
        # connect mouse click to a callback
        button1.connect("clicked", self.callback, "Tom")
        button2 = gtk.Button("Button 2")
        # connect mouse click to a callback
        button2.connect("clicked", self.callback, "Frank")
        self.label = gtk.Label("Hello!")

        # create a vertical box to pack the widgets into
        box_v = gtk.VBox(False, 0)
        self.window.add(box_v)
        # now pack the widgets into the box (top to bottom order)
        box_v.pack_start(button1, False, False, 0)
        box_v.pack_start(button2, False, False, 0)
        box_v.pack_start(self.label, True, True, 0)

        # now show all the widgets including the window
        button1.show()
        button2.show()
        self.label.show()
        box_v.show()
        self.window.show()

    def callback(self, widget, data=None):
        s = "You clicked %s's button" % data
        self.window.set_title(s)
        if data == "Tom":
            self.label.set_text("Major Tom")
        else:
            self.label.set_text("Major Frank Burns")
        

MyWindow()
gtk.main()
sneekula 969 Nearly a Posting Maven

The very test numbers I gave you wont work with just rounding! It will miss the one penny change.

sneekula 969 Nearly a Posting Maven

Is the directory there and do you have access to it?

sneekula 969 Nearly a Posting Maven

# optionally scroll to the bottom of the listbox
lines = listbox.size()
listbox.yview_scroll(lines, 'units')

sneekula 969 Nearly a Posting Maven

Here is an example of a scrolled Tkinter canvas to display a series of drawn objects or pictures:

# example of a Tkinter scrolled canvas class
# snee

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

class ScrolledCanvas(tk.Frame):
    def __init__(self, parent=None, color='brown'):
        tk.Frame.__init__(self, parent)
        self.pack(expand='yes', fill='both')
        self.parent = parent
        
        canvas = tk.Canvas(self, bg=color, relief='sunken')
        #canvas.config(width=300, height=200)
        canvas.config(scrollregion=(0, 0, 300, 1000))
        canvas.config(highlightthickness=0)

        sbar = tk.Scrollbar(self)
        # vertical scrollbar
        sbar.config(command=canvas.yview)
        canvas.config(yscrollcommand=sbar.set)
        sbar.pack(side='right', fill='y')
        canvas.pack(side='left', expand='yes', fill='both')

        # put in some text for testing ...
        for k in range(10):
            s = 'now calling #' + str(k)
            canvas.create_text(150, 50+(k*100), text=s, fill='beige')
        # for testing canvas (x, y)
        canvas.bind('<Double-1>', self.onDoubleClick)
        self.canvas = canvas
        
    def onDoubleClick(self, event):
        """show location (x, y) of double click on canvas"""
        #print( event.x, event.y )
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)
        s = "x = %s  y = %s" % (x, y)
        self.parent.title(s)

if __name__ == '__main__':
    root = tk.Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    root.geometry("%dx%d+%d+%d" % (350, 250, 100, 80))
    root.title('testing the scrolled canvas')
    ScrolledCanvas(root).mainloop()
sneekula 969 Nearly a Posting Maven

To take care of the ever present binary roundoff error that is associated with floating point numbers (most any computer language) do this:

# compensate for the binary roundoff error
        while change >= (m - 0.001):

In the matter of fact you can streamline your code to this:

# change_calc.py
# calculate the change given to a customer using the least
# amount of bills and coins (US currency)

#cost = input("Cost of item: ")
#paid = input("Money paid:   ")
# for testing ...
cost = 262.99
paid = 500.00

# dictionary storing the amount of each bill/coin needed
m_d = {100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 1: 0, 0.25: 0, 0.1: 0, 0.05: 0, 0.01: 0}

if paid < cost:
    print "You have not paid enough"
else:
    # round off to the penny
    change = round((paid - cost), 2)
    print "Change: $" + str(change)
    for m in sorted(m_d, reverse=True):
        # compensate for the binary roundoff error
        while change >= (m - 0.001):
            m_d[m] += 1
            change -= m

    # print the currency options
    print "100's:",m_d[100]
    print " 50's:",m_d[50]
    print " 20's:",m_d[20]
    print " 10's:",m_d[10]
    print "  5's:",m_d[5]
    print "  1's:",m_d[1]
    print "  Q's:",m_d[0.25]
    print "  D's:",m_d[0.1]
    print "  N's:",m_d[0.05]
    print "  P's:",m_d[0.01]

Note, it is the == in >= that will cause the problem with floating point values.

sneekula 969 Nearly a Posting Maven

What is your problem? How does it manifest itself?

sneekula 969 Nearly a Posting Maven

Set up a formatted string before you send it to the Textbox. Here is an example:

# example to set up a table formatted string

import math

# set up the format strings (use - for left justified)
header  = "%-12s %-12s %-12s \n"
line_fs = "%-12f %-12.4f %-12.4f \n"

table = ''
table += (header % ('radians', 'sine', 'cosine'))
for x in range(0, 11):
    rad = math.radians(x)
    table += (line_fs % (rad, math.sin(rad), math.cos(rad)))

print(table)

"""my output (use a fixed font like Courier) -->
radians      sine         cosine
0.000000     0.0000       1.0000
0.017453     0.0175       0.9998
0.034907     0.0349       0.9994
0.052360     0.0523       0.9986
0.069813     0.0698       0.9976
0.087266     0.0872       0.9962
0.104720     0.1045       0.9945
0.122173     0.1219       0.9925
0.139626     0.1392       0.9903
0.157080     0.1564       0.9877
0.174533     0.1736       0.9848
"""
catcit commented: Thanks! +1
vegaseat commented: very nice +13
sneekula 969 Nearly a Posting Maven

Most computer languages would give you the same problem. The computer tries to represent a floating point number as a binary internally. To compare floating point numbers you need to use fuzzy logic. Here as an function to use:

def fuzzyequals(a, b, delta=0.0000001):
    """
    returns True if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta
sneekula 969 Nearly a Posting Maven

Be aware that sorting strings will not necessarily behave as you would expect:

myfiles = [
'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt', 'a5.txt',
'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt', 'a10.txt', 'a11.txt'
]

print(myfiles)
print('-'*60)

myfiles_sorted = sorted(myfiles)
print(myfiles_sorted)

"""my result -->
['a1.txt', 'a2.txt', 'a3.txt', 'a4.txt', 'a5.txt', 
'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt', 'a10.txt', 'a11.txt']
------------------------------------------------------------
['a1.txt', 'a10.txt', 'a11.txt', 'a2.txt', 'a3.txt', 
'a4.txt', 'a5.txt', 'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt']
"""

For this to work you would have to name your files something like a02.txt and a12.txt

sneekula 969 Nearly a Posting Maven

The solution depends on the GUI toolkit you are using.

sneekula 969 Nearly a Posting Maven

Most likely maintenance time, those are scheduled most often on weekends.

sneekula 969 Nearly a Posting Maven

In Python most everything is an objects, so you are using OOP from the start.
If you talking about the use of classes, then basically you have another tool to organize larger programs.

You can collect functions that belong together under the class header. These function are commonly called methods of a class. This way you can create several different instances of the class, each containing the same methods. That is where the power comes in, since you don't have to rewrite the class every time. Python keeps track of which instance you are using. Here is an example:

# a look at a simple Python class

class Animal(object):
    # uses newer class style, inheriting very basic class 'object'
    def __init__(self, animal, sound):
        # __init__() is the 'constructor' of the class instance
        # when you create an instance of Animal you have to supply
        # it with the name and the sound of the animal
        # 'self' refers to the instance
        # if the instance is dog, then
        # name and sound will be that of the dog
        # 'self' also makes name and sound available
        # to all the methods within the class
        self.name = animal
        self.sound = sound
        
    def speak(self):
        # a method's arguments always start with self
        print( "The %s goes %s" % (self.name, self.sound) )


# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = …
vegaseat commented: very nice example +13
sneekula 969 Nearly a Posting Maven

Just a note:
avoid using 'file' for an identifier, since it is a built-in Python function.

sneekula 969 Nearly a Posting Maven

For those of you who want experience vegaseat's sweet Tinter tkk example at:
http://www.daniweb.com/forums/post921416-25.html
on your Linux machines, in my case Ubuntu (Python 3.1 is not in the repository yet), here is an easy installation of Python 3.1:

Download ActivePython-3.1.0.1-linux-x86.tar.gz via
http://downloads.activestate.com/ActivePython/linux/3.1/ActivePython-3.1.0.1-linux-x86.tar.gz
from:
http://www.activestate.com/activepython/python3/

Extract to the Desktop

In the terminal change to the proper directory:

cd ~/Desktop/ActivePython-3.1.0.1-linux-x86/

Then run:

sudo ./install.sh

As install directory I entered something easy like:

/home/dell/python/3.1

The installation takes a short time. Now create a symbolic link:

sudo ln -s /home/dell/python/3.1/bin/python3.1 /usr/local/bin/python3.1

Now you are ready to enjoy Python 3.1

# to run a scripts with Python3.1
# with the Geany IDE you can set 'Build'/'Set Includes and Arguments'
# 'Execute' to python3.1 "%f"

sneekula 969 Nearly a Posting Maven

Write a program that goes through a folder of source/text files and lists all the file names that contain a given search word (or combination of search words).

sneekula 969 Nearly a Posting Maven

Some options with a basic Tkinter window:

# set position and size of a Tkinter window

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

#root = tk.Tk()
root = tk.Tk(className="My Title")  # sets title too
# or give it your title this way
#root.title("My Title")

w = 300
h = 200
x = 50
y = 100
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# make Tk window not resizable, also disables the maximize button
#root.resizable(width=FALSE, height=FALSE)
# or ...
#root.resizable(0, 0)

# or make root window full screen
#root.state('zoomed')

# give it a colorful frame
frame = tk.Frame(root, bg='green')
frame.pack(fill='both', expand='yes')

root.mainloop()
sneekula 969 Nearly a Posting Maven

It would be nice to get the game going and put in some test prints or send it through a debugger. However, without the module gameobjects it is hard to get the needed vector2 stuff. Also looks like there is a mixed tab/space indentation issue.

sneekula 969 Nearly a Posting Maven

This code shows you how to get file information of a given folder into a table. It also is modified to work with Linux or Windows, as these Operating Systems have differences in some of the file functions and folder syntax:

# File_Info2.py
# show some file details in a table
# note that Linux file names are case sensitive
# Linux uses different folder syntax and getctime() for last changes
# Windows uses getmtime() for last changes/modifications
# this program has been written to accept Windows or Linux
# tested with Python 2.5.4

import os
import time
import sys

# check if your OS is linux or windows
# pick an appropriate folder/directory you have
if sys.platform[:5] == "linux":
    folder = "/home/dell/Atest25/Chemistry"
    win_flag = False
else:
    folder = 'C:/Python25/Atest25/Chemistry'
    win_flag = True

#print(win_flag)  # test

# create list of (fname, size, date_time) tuples
file_info = []
for item in os.listdir(folder):
    # get full path for isdir() to work
    path = os.path.join(folder, item)
    # make sure item is a filename
    if os.path.isdir(path):
        continue  # skip any folder names
    if win_flag:
        change = os.path.getmtime(path)  # Windows
    else:
        change = os.path.getctime(path)  # Linux
    # (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dlsflag)
    # eg. (2009, 7, 31, 21, 37, 6, 4, 212, 1)
    change_tuple = time.localtime(change)
    date_time24 = time.strftime("%m/%d/%Y %H:%M:%S", change_tuple)
    size = os.path.getsize(path)
    # convert to kb
    if size > 999:
        size = round(size/1024.0, 1)
    else:
        size = round(size/1024.0, 3)
    file_info.append((os.path.basename(path), size, date_time24))
    
# show result as formatted table ...
# for longer file names use eg. …
sneekula 969 Nearly a Posting Maven

Maybe you need to give full path names.

sneekula 969 Nearly a Posting Maven

Read the docs of Python3:
http://docs.python.org/3.1/whatsnew/3.0.html?highlight=callable

Removed callable(). Instead of callable(f) you can use hasattr(f, '__call__'). The operator.isCallable() function is also gone.

You can run this program to check what you have available:

# print all builtin functions/methods

# do a case insensitive sort then print ...
print( '\n'.join(sorted(dir(__builtins__), key=str.lower)) )

# or send to a file ...
fout = open('Builtins.txt', 'w')
print( '\n'.join(sorted(dir(__builtins__), key=str.lower)), file=fout)

"""my result with Python 3.1 -->
__build_class__
__debug__
__doc__
__import__
__name__
__package__
abs
all
any
ArithmeticError
ascii
AssertionError
AttributeError
BaseException
bin
bool
BufferError
bytearray
bytes
BytesWarning
chr
classmethod
compile
complex
copyright
credits
delattr
DeprecationWarning
dict
dir
divmod
Ellipsis
enumerate
EnvironmentError
EOFError
eval
Exception
exec
exit
False
filter
float
FloatingPointError
format
frozenset
FutureWarning
GeneratorExit
getattr
globals
hasattr
hash
help
hex
id
ImportError
ImportWarning
IndentationError
IndexError
input
int
IOError
isinstance
issubclass
iter
KeyboardInterrupt
KeyError
len
license
list
locals
LookupError
map
max
MemoryError
memoryview
min
NameError
next
None
NotImplemented
NotImplementedError
object
oct
open
ord
OSError
OverflowError
PendingDeprecationWarning
pow
print
property
quit
range
ReferenceError
repr
reversed
round
RuntimeError
RuntimeWarning
set
setattr
slice
sorted
staticmethod
StopIteration
str
sum
super
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
True
tuple
type
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
vars
Warning
ZeroDivisionError
zip
"""
sneekula 969 Nearly a Posting Maven

Since Pygame does not have a file dialog, we can use Tkinter's file dialog and withdrawing the root so it doesn't clash with Pygame's eventloop:

# experiments with module pygame
# free from: http://www.pygame.org/
# load and display an image using pygame and Tkinter's file dialog

import pygame as pg

# initialize pygame
pg.init()

#---------- uses Tkinter to open an image filename ------------------
import Tkinter as tk
import tkFileDialog as tkfd
root = tk.Tk()
root.withdraw()
dirname = tkfd.askdirectory()
mask = [("GIF and JPEG files","*.gif *.jpg")]
image_file = tkfd.askopenfilename(initialdir=dirname, filetypes=mask)
#--------------------------------------------------------------------

# RGB color tuple used by pygame
white = (255, 255, 255)

# create a 300x300 white screen
screen = pg.display.set_mode((300,300))
screen.fill(white)

# load the image from a file
image = pg.image.load(image_file)

# draw image, position the image ulc at x=50, y=20
screen.blit(image, (50, 20))

# nothing gets displayed until one updates the screen
pg.display.flip()

# start event loop and wait until
# the user clicks on the window corner x
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            raise SystemExit
sneekula 969 Nearly a Posting Maven

With the advent of Python3 Tkinter has turned into a package called tkinter. I usually add a try/except to pick the right import:

# a simple Tkinter number guessing game
# shows how to create a window, an entry, a label, a button,
# a button mouse click response, and how to use a grid for layout

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

def click():
    """the mouse click command response"""
    global rn
    # get the number from the entry area
    num = int(enter1.get())
    # check it out
    if num > rn:
        label2['text'] = str(num) + " guessed too high!"
    elif num < rn:
        label2['text'] = str(num) + " guessed too low!"
    else:
        s1 = str(num) + " guessed correctly!"
        s2 = "\n Let's start a new game!"
        label2['text'] = s1 + s2
        # pick a new random number
        rn = random.randrange(1, 11)
    enter1.delete(0, 2)


# create the window and give it a title
root = tk.Tk()
root.title("Heidi's Guess A Number Game")

# pick a random integer from 1 to 10
rn = random.randrange(1, 11)

# let the user know what is going on
label1 = tk.Label(root, text="Guess a number between 1 and 10 -->")
# layout this label in the specified row and column of the grid
# also pad with spaces along the x and y direction
label1.grid(row=1, column=1, padx=10, pady=10)

# this your input area
enter1 = tk.Entry(root, width=5, bg='yellow')
enter1.grid(row=1, column=2, padx=10)
# …
sneekula 969 Nearly a Posting Maven

If Sound Recorder has a command-line option, then you can send the arguments along to start it etc.

sneekula 969 Nearly a Posting Maven

Salem has a very good point, it would be very confusing to the user to show ***** that does not match the password string in length.

sneekula 969 Nearly a Posting Maven

Your carlist is a list of instances of the class carType. To compare the car's name you have to use the instance.name as shown here:

class carType:
   def __init__(self, name, brand, price):
      self.name = name
      self.brand = brand
      self.price = price
      
carlist = [
   carType("Viper", "Dodge", 80000),
   carType("Mustang", "Ford", 25000),
   carType("Silhouette", "Oldsmobile", 26000),
   carType("Croma", "Fiat", 15000),
   carType("RL", "Acura", 46000),
   carType("Axiom", "Isuzu", 24000)
   ]

print(carlist)  # shows a list of class instances

car_name = "Mustang"
for instance in carlist:
    print(instance.name)  # test
    if car_name == instance.name:
        print("%s is in the list" % car_name)

As you study some more about Python classes, it all will make sense to you.

sneekula 969 Nearly a Posting Maven

Does anyone know a good internet site where I can 'park' my Python code?
Easy download, upload, and search.

sneekula 969 Nearly a Posting Maven

You need to use one of the GUI toolkits for the 2 frames to respond to each other.

sneekula 969 Nearly a Posting Maven

You post makes no sense to me!

sneekula 969 Nearly a Posting Maven

List values are accessed by their index.
Dictionary values are accessed by their key. To allow for high speed key searches, the keys are in a hash order. So a dictionary sorted alphabetically by it's keys would make no sense and would defeat the whole dictionary idea.

The best you can do is to present the contents of a dictionary the way snippsat did it, as a list of (key, value) tuples. Also as a table (sorted by key) in your program:

name_age = {'Joe': 18, 'Frank': 45, 'Udo': 56, 'Tom': 34}
# as a table sorted by name (key)
for name in sorted(name_age):
    print( "%-10s %d" % (name, name_age[name]) )

"""
my output -->
Frank      45
Joe        18
Tom        34
Udo        56
"""
sneekula 969 Nearly a Posting Maven

You can use Hide() and Show() as explained here:

# create two frames with wxFrame, only one is showing

import wx

class Frame1(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
        self.SetBackgroundColour("green")
        # pass frame1 to frame2 as instance self
        self.frame2 = Frame2(None, 'Frame1', self)

        # create input widgets
        self.button1 = wx.Button(self, wx.ID_ANY, label='Frame2')
        self.button2 = wx.Button(self, wx.ID_ANY, label='Button2')
        self.button3 = wx.Button(self, wx.ID_ANY, label='Button3')
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.button1Click)

        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.button1, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.button2, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.button3, 0, flag=wx.ALL, border=10)
        self.SetSizer(sizer_v)

        # size the frame so all the widgets fit
        self.Fit()

    def button1Click(self, event):
        """button1 has been left clicked"""
        # self is instance frame1
        self.Hide()
        self.frame2.Show()


class Frame2(wx.Frame):
    def __init__(self, parent, mytitle, frame1):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle)
        self.SetBackgroundColour("brown")
        self.frame1 = frame1

        # create input widgets
        self.button1 = wx.Button(self, wx.ID_ANY, label='Frame1')
        self.button2 = wx.Button(self, wx.ID_ANY, label='Button2')
        self.button3 = wx.Button(self, wx.ID_ANY, label='Button3')
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.button1Click)
        # responds to exit symbol x on frame2 title bar
        self.Bind(wx.EVT_CLOSE, self.button1Click)

        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.button1, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.button2, 0, flag=wx.ALL, border=10)
        sizer_v.Add(self.button3, 0, flag=wx.ALL, border=10)
        self.SetSizer(sizer_v)

        # size the frame so all the widgets fit
        self.Fit()

    def button1Click(self, event):
        """button1 has been left clicked"""
        # self is instance frame2
        self.Hide()
        self.frame1.Show()


app = wx.App(0)
# create a MyFrame instance and show the …
sneekula 969 Nearly a Posting Maven

Here is an example that actually creates a jpeg image file of your labor:

# drawing with PIL (Python Image Library)
# draw and save a small French flag (blue, white, red)

from PIL import Image, ImageDraw

# create a new 24x16 pixel image surface (default is black bg)
img = Image.new("RGB", (24, 16))

# set up the new image surface for drawing
draw = ImageDraw.Draw (img)

# draw a blue rectangle
# x1, y1 are upper left corner coordinates here
w = 8
h = 16
x1 = 0
y1 = 0
draw.polygon([(x1,y1),
(x1+w,y1), (x1+w,y1+h), (x1,y1+h)], fill='blue')

# draw a white rectangle
w = 8
h = 16
x1 = 8
y1 = 0
draw.polygon([(x1,y1),
(x1+w,y1), (x1+w,y1+h), (x1,y1+h)], fill='white')

# draw a red rectangle
w = 8
h = 16
x1 = 16
y1 = 0
draw.polygon([(x1,y1),
(x1+w,y1), (x1+w,y1+h), (x1,y1+h)], fill='red')

img.save("french_flag.jpg")

# optionally look at the image you have drawn
img.show()
sneekula 969 Nearly a Posting Maven

Here is a Python output with an image:

# draw a flower with module turtle

import turtle as tu

tu.title('I call this one Flower')

# values for speed are 'fastest' (no delay), 'fast', (delay 5ms),
# 'normal' (delay 10ms), 'slow' (delay 15ms), and 'slowest' (delay 20ms)
tu.speed('fastest')

#turtle.color((.3,.5,.3))
tu.color('red')
tu.width(2)

radius = 180  # size of circle --> length of petal
extent = 70   # number of degrees in arc --> width of petal
angle = 0     # start out with a horizontal petal
x1 = 0        # location in X direction
y1 = -20      # location in Y direction

def flower():
    tu.up()
    tu.goto(x1,y1)
    tu.setheading(angle)
    tu.left(extent/2)
    tu.down()

    tu.circle(-radius, extent)
    tu.up()
    tu.goto(x1,y1)
    tu.down()
    tu.setheading(angle)
    tu.right(extent/2)
    # fills half the flower petal
    tu.begin_fill()
    tu.circle(radius, extent)
    tu.end_fill()

    tu.up()
    tu.goto(x1,y1)
    tu.setheading(angle)
    tu.down()

for angle in range(-45, 135, 45):
    radius = radius + 20
    flower()

for angle in range(135, 270, 45):
    radius = radius - 20
    flower()

tu.color('blue')
tu.up()
tu.goto(-60, -170)
tu.write("Fowers are beautiful!")

tu.up()
tu.setheading(90)
tu.goto(0, -15)

# keep showing until corner x is clicked
tu.done()
sneekula 969 Nearly a Posting Maven

In one day, a human sheds 10 billion skin flakes. This amounts to approximately two kilograms in a year.

sneekula 969 Nearly a Posting Maven

Market capitalism is sustainable. Everybody getting rich is not!

sneekula 969 Nearly a Posting Maven

If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.
~~~ John von Neumann

sneekula 969 Nearly a Posting Maven

Looks like you have a wife that lets you play with the computer. Hang on to her for another 47years!!

sneekula 969 Nearly a Posting Maven

Hmm, this little test program works just fine:

# a small re and Tkinter program to display lines from
# a data file that contain the word "searchword"

from Tkinter import *
import re

# create a test data file
data = """\
this line has the searchword
this line does not
searchword is in this line too
"""
filename = "mytestdata.txt"
fout = open(filename, "w")
fout.write(data)
fout.close()


root = Tk()

text = Text(root, width=50, height=12, bg='yellow')
text.pack()

keyword = re.compile("searchword")

for line in file(filename):
    result = keyword.search (line)
    if result:
        text.insert(INSERT, '\n' + line)


root.mainloop()

BTW, don't use 'file' as a name for a variable, since there is a Python function named file()

sneekula 969 Nearly a Posting Maven

I would use module subprocess:

# os.system() does not allow the Python program 
# to run in the background, whereas subprocess does

import subprocess

# remove  "arg1", "arg2" if you don't have any command line args
subprocess.call(["C:/Python25/Python.exe", "Skripta.py", "arg1", "arg2"])
sneekula 969 Nearly a Posting Maven

Looks like they want you to flatten the list.

sneekula 969 Nearly a Posting Maven

Like snippsat so wisely said,
"do not change a list that your are iterating over"
this will upset the indexing of the list during the iteration process.

snippsat also recommended to iterate over a copy of mylist:

mylist = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
mylist_copy = list(mylist)  # or mylist[:]
for x in mylist_copy:
    print '--------------'
    print x
    if x[0] == 'a':
        print "Removing ",x
        mylist.remove(x)

print mylist

"""
my output -->
--------------
bunnies
--------------
apples
Removing  apples
--------------
animals
Removing  animals
--------------
fruit
--------------
amsterdam
Removing  amsterdam
['bunnies', 'fruit']
"""
sneekula 969 Nearly a Posting Maven

How do you import Tkinter?

sneekula 969 Nearly a Posting Maven

Look through your code and test print some of your variables to see what is going on.

Create a word list then something like this will work:

s = 'he said why'
word_list = s.split()
n = 0
for word in word_list:
    if word[0] == 'w':
        print word_list[n]
    n += 1
sneekula 969 Nearly a Posting Maven

I have the Geany IDE originally installed under Python2.5 on my Ubuntu machine.
To run a script with Python3.1 with the Geany IDE you can set 'Build' --> 'Set Includes and Arguments' --> 'Execute' to python3.1 "%f"

For some odd reason my shebang line
#!/usr/local/bin/python3.1
doesn't seem to respond.

sneekula 969 Nearly a Posting Maven

I have a /user/bin/python2.5 link to that version's executable, also /user/bin/python links to there. There is no /user/bin/python3.1 link or a /user/bin/idle-python3.1. How do I create such a link?

sneekula 969 Nearly a Posting Maven

This would give you the sum of digits:

def sum_digits(n):
    total = 0
    for digit in str(n):
        total += int(digit)
    return total

Now expand this function so you multiply int(digit) with each other.
Notice that I didn't use 'sum' because sum() is a Python function.

sneekula 969 Nearly a Posting Maven

Arrorn, thanks for your info.

I download Python-3.1.tar.bz2 from:
http://www.python.org/download/releases/3.1/

Extracted to the Desktop

On the Terminal I did a:
cd ~/Desktop/Python-3.1/

Then I followed the readme file for the installation on Linux

All of it worked great!

Now I need friendly advice on running idle.pyw in directory
/usr/local/lib/python3.1/idlelib with Python3.1