sneekula 969 Nearly a Posting Maven

Guess I won't worry too much about Christmas shopping that year.

Good thinking! There is a silver-lining in every cloud.

sneekula 969 Nearly a Posting Maven

If the first code you showed is part of a function you have to tell it that gold is a global variable, start your function code with

global gold
sneekula 969 Nearly a Posting Maven

This must be specific to the Mac OSX. I wonder if PIL has a users forum, or a place you can ask.

sneekula 969 Nearly a Posting Maven

Somewhere above your lines shown you have to give gold a starting value, most likely:
gold = 0

sneekula 969 Nearly a Posting Maven

I am really not a mind reader, so show us some code that gives the error!

sneekula 969 Nearly a Posting Maven

Be aware that there is a namspace conflict with class Image:

# load and display an image with Tkinter
# Tkinter only reads gif and ppm images
# use Python Image Library (PIL) for other image formats
# give Tkinter a namespace to avoid conflicts with PIL
# (they both have class Image) PIL is free from:
# http://www.pythonware.com/products/pil/index.htm

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
cv1 = tk.Canvas(root, width=500, height=500)
cv1.pack(fill='both', expand='yes')

# open a jpeg file into an image object
# image should be in the source folder or give full path name
image1 = Image.open("flowers.jpg")
# convert image object to Tkinter PhotoImage object
tkimage1 = ImageTk.PhotoImage(image1)

# tk.NW anchors upper left corner of image
# at canvas coordinates x=10, y=20
cv1.create_image(10, 20, image=tkimage1, anchor=tk.NW)

root.mainloop()
sneekula 969 Nearly a Posting Maven

But, why would someone choose Java over Python? Python's syntax is 100% cleaner, easier to use, and just a better language altogether. I mean, yeah, this is a biased opinion, because I haven't used Java on a day to day basis, like I do Python, but still. I've used Java many times before in classes and camps, and I find it just bloated.

Java has been taught by college CS departments for many years. The typical inertia shown by CS staff makes certain that Java will be taught for many more years to come. There are hordes of Java programmers out there. Also Java, being more complex, ensures job security since development is slower and more programmers are needed to do the job.

Python, being easier and quicker to teach, would of course reduce the number of instructors too. Oh my!

sneekula 969 Nearly a Posting Maven

I have found some bugs just using the Python debugger module pdb:

# test the built-in Python Debugger (Pdb in the Python reference)
# at the debugger's '(Pdb)' prompt you can type  h  for help or
# more specifically use   h step  or   h next

import pdb

#help('pdb')

# once the '(Pdb)' prompt shows, you are in the debugger
# and you can trace through by entering:
#
# next (or n) which goes line by line and does not get
# into functions or into every iteration of a loop
#
# step (or s) which is more detailed and for instance
# loops through an entire range()
#
# so use next to get where you want to be and then use step,
# once you have all the details you need, use next again

pdb.set_trace()

# now you can test the following code

def hasCap(s):
    """returns True if the string s contains a capital letter"""
    for num in range(65, 91):
        capLetter = chr(num)
        if capLetter in s:
            return True
    return False

str1 = 'Only pick up strings without Capital letters!'
str2 = 'only pick up strings without capital letters!'

# test the function hasCap()
if hasCap(str1):
    print "str1 has a capital letter"
else:
    print "str1 has no capital letter"

if hasCap(str2):
    print "str2 has a capital letter"
else:
    print "str2 has no capital letter"
vegaseat commented: very nice +8
sneekula 969 Nearly a Posting Maven

Then there is Boo, has a Python like syntax and ties in with C#. Vegaseat left a code snippet of Boo code at:
http://www.daniweb.com/code/snippet429.html

sneekula 969 Nearly a Posting Maven

Here is an example that should get most of the way there. All you need to do is to supply the search string from the listbox selection:

# searching a long text for a string and scrolling to it
# use ctrl+c to copy, ctrl+x to cut selected text,
# ctrl+v to paste, and ctrl+/ to select all

import Tkinter as tk

def display(data):
    """creates a text display area with a vertical scrollbar"""
    scrollbar = tk.Scrollbar(root)
    text1 = tk.Text(root, yscrollcommand=scrollbar.set)
    text1.insert(0.0, data)
    scrollbar.config(command=text1.yview)
    scrollbar.pack(side='right', fill='y')
    text1.pack(side='left', expand=0, fill='both')
    
    # could bring the search string in from a listbox selection
    pattern = "Chapter 3"
    # line.char(lines start at 1, characters at 0)
    start = "1.0"
    # returns eg. "31.0" --> line 31, character 0
    index = text1.search(pattern, start)
    # scroll text until index line is visible
    # might move to the top line of text field
    text1.see(index)
    
    
root = tk.Tk()

str1 = """\
Chapter 1
.
.
.
.
.
.
.
.
.
.
.
.
.
Chapter 2
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Chapter 3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The End
"""

display(str1)

root.mainloop()
sneekula 969 Nearly a Posting Maven

I always thought you were some kind of car buff. What happened?

Okay, I am still a car buff, but I thought that sounded too Lithuanian.

sneekula 969 Nearly a Posting Maven

Spending time with my family and my GF
Cooking
Walking

sneekula 969 Nearly a Posting Maven

Here is the spiel:

a += b  Roughly equivalent to a = a + b 
a -= b  Roughly equivalent to a = a - b  
a *= b  Roughly equivalent to a = a * b  
a /= b  Roughly equivalent to a = a / b  
a //= b  Roughly equivalent to a = a // b 
a %= b  Roughly equivalent to a = a % b  
a **= b  Roughly equivalent to a = a ** b   
a &= b  Roughly equivalent to a = a & b  
a |= b  Roughly equivalent to a = a | b  
a ^= b  Roughly equivalent to a = a ^ b  
a >>= b  Roughly equivalent to a = a >> b  
a <<= b  Roughly equivalent to a = a << b
rysin commented: Helped a lot, answered question. +1
sneekula 969 Nearly a Posting Maven

Sounds like you want something lke this:

def ask_hours():
    return input ("How many hours do you want to convert? ")

def calc_minutes(hours):
    minutes = hours * 60
    print "There are", minutes, "minutes in", hours, "hours."

def main() :
    hours = ask_hours()
    calc_minutes(hours)


main()

You have ywo types of functions here, ask_hours() returns something and calc_minutes(hours) needs an argument (hours), but shows the result and does not return anything.

sneekula 969 Nearly a Posting Maven

A lot of programmers use both Java and Python. Python has the advantage of a much more rapid learning and program development phase. So I would learn Python first. Once you learn Python you can access Java libaries easily with Jython, also open source.

sneekula 969 Nearly a Posting Maven

Please stick to established Python coding rules, you code is hard to read:

import Tkinter as tk
from PIL import Image, ImageTk

def show_image():
    """image object image1 created in main"""
    canvas.create_image(250, 250, image=image1)
    #canvas.update()

frame = tk.Frame()
frame.pack()

canvas = tk.Canvas(frame, bg='white', width=500, height=500)
canvas.pack()

button = tk.Button(frame, fg="blue", text="Insert Image",
    activebackground='red', font=('verdana', 10, 'bold'), command=show_image)
button.pack(padx=50, side="left")

# create the image object here, not in the function
imageFile = "map.png"
image1 = ImageTk.PhotoImage(Image.open(imageFile))

"""
# default is center the image
canvas.create_image(250, 250, image=image1)
canvas.update()
"""

frame.mainloop()
sneekula 969 Nearly a Posting Maven

Even simpler:

sum([int(i) for i in raw_input("Enter integer: ")])
sneekula 969 Nearly a Posting Maven

I think it behaves perfectly fine, here is my output:

1.0 1.0 1.0  0.0
2.0 1.41421356237 1.41421356237  1.59472435257e-012
3.0 1.73205081001 1.73205080757  2.44585018905e-009
4.0 2.00000000003 2.0  2.62145860574e-011
5.0 2.23606798501 2.2360679775  7.51019246792e-009
6.0 2.44948974278 2.44948974278  6.2172489379e-015
7.0 2.64575131106 2.64575131106  3.66817687336e-013
8.0 2.82842712475 2.82842712475  6.9610983644e-012
9.0 3.00000000007 3.0  6.61648513756e-011

Also remember that most computer languages represent a floating point number in such a way that there is the possibility of a tiny last-digit error.

To get a better output of your results you should do some formatting:

def square_root(a):
    if a > 1.0:
        x = a - 1.0
    elif a == 1.0:
        return 1.0
    else:
        pass
    while True:
        y = (x + a/x)/2
        if math.fabs(y-x) < 0.0000001:
            break
        x = y
    return x



import math
i = 1.0
while i <= 9.0:
    sqrt = square_root(i)
    math_sqrt = math.sqrt(i)
    difference = math.fabs(math_sqrt - sqrt)
    print "%0.1f %0.9f %0.9f %0.9f" % (i, sqrt, math_sqrt, difference)
    i = i + 1

"""
my output --->
1.0 1.000000000 1.000000000 0.000000000
2.0 1.414213562 1.414213562 0.000000000
3.0 1.732050810 1.732050808 0.000000002
4.0 2.000000000 2.000000000 0.000000000
5.0 2.236067985 2.236067977 0.000000008
6.0 2.449489743 2.449489743 0.000000000
7.0 2.645751311 2.645751311 0.000000000
8.0 2.828427125 2.828427125 0.000000000
9.0 3.000000000 3.000000000 0.000000000
"""
sneekula 969 Nearly a Posting Maven

Function wget() is not part of Python. However you can extract a picture from a URL easily, as shown in this code snippet:
http://www.daniweb.com/code/snippet563.html

sneekula 969 Nearly a Posting Maven

Something one can wear on his hand and use it to rip out someones' intestines.

A surgical tool?

sneekula 969 Nearly a Posting Maven

Python30 introduces quite a number of major changes to the Python code syntax. I would not use it at this point until it is the official release (end of 2008 projected release date).

sneekula 969 Nearly a Posting Maven

You need to convert your integer into a string, iterate the string and sum up the string's numeric characters as integers.

If n is your integer, then str(n) is the string.
If c is the string's numeric character, then int(c) is its numeric/integer value.
Use a for loop to iterate the string.

sneekula 969 Nearly a Posting Maven

Take a look at this Tkinter GUI Builder:
http://spectcl.sourceforge.net/spectcl.html

I downloaded the Windows exe file and it works quite well. The target lanuages of the produced code are TCL, Java, HTML, Perl or Python. As with most builders the code is a little wordy, but it works!

sneekula 969 Nearly a Posting Maven

You major problem is that __init__() uses double underlines prefix and postfix.

Also, remember that the module name and its file name are case sensitive!

Here is an example:

# save module as tank.py  (file name is case sensitive!)

class Tank (object):
    def __init__(self, name):
        self.name = name
        self.alive = True
        self.ammo = 5
        self.armor = 60

# test the module
if __name__ == '__main__':
    mytank = Tank("Bob")
    print mytank.name, mytank.armor  # Bob 60

Your program should import the modules like this:

# module was saved as tank.py (case sensitive)

import tank

mytank = tank.Tank("Bob")

print mytank.name  # Bob

Please make your thread title more specific, instead of "Python Problem" use "Problem with Python Class"

sneekula 969 Nearly a Posting Maven

Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:

food = 'bread'

vars()[food] = 123

print bread  # --> 123

You can print out vars() to see what's going on.

sneekula 969 Nearly a Posting Maven

Your code is loaded with errors. I assume this is something like you want, it actually works:

import Tkinter as tk
import time

def generate():
    for i in range(0,100,5):
        time.sleep(0.3)
        canvas.create_oval(200-i, 300-i, 210+i, 310+i)
        # needed after time.sleep
        canvas.update()
        # for testing only
        print i
    canvas.create_oval(200, 300, 210, 310, fill='red')


frame = tk.Frame()
frame.pack()

canvas = tk.Canvas(frame, bg='white', width=500, height=500)
canvas.pack()

button = tk.Button(frame, fg="blue", text="GENERATE", command=generate)
button.pack()

frame.mainloop()
sneekula 969 Nearly a Posting Maven

I am working on an expert system to replace our lying and cheating political leadership with a lying and cheating computer system. :)

majestic0110 commented: hehe +1
Ancient Dragon commented: LOL :) Didn't we have a prototype in the 2000 election ? +24
sneekula 969 Nearly a Posting Maven

Please use the proper code tags around your code. Don't quote the whole thing or your code tags won't work.

Proper code tags are
[code=python]
your code here

[/code]

Please format your code so it is somewhat readable. Also, since your ovals are equal, how would you know the difference?

This how you might do it:

import Tkinter as tk

def generate():
    oval1()
    frame.after(2000, oval2)

def oval1():
    canvas.create_oval(200, 300, 210, 310, fill='red')

def oval2():
    canvas.create_oval(200, 300, 210, 310, fill='blue')

frame = tk.Frame()
frame.pack()

canvas = tk.Canvas(frame, bg='white', width=500, height=500)
canvas.pack()
            
button = tk.Button(frame, fg="blue", text="GENERATE", command=generate)
button.pack()

frame.mainloop()
sneekula 969 Nearly a Posting Maven

If you want to familarize yourself with a function, it helps to print some of the results:

# enumerating over a string or list returns the index and the element

s = 'help'

for ix, c in enumerate(s):
    print ix, c

"""
my result -->
0 h
1 e
2 l
3 p
"""
sneekula 969 Nearly a Posting Maven

Please use code tags around your code so it will retain the indentations!

You are also unpacking clist wrong, also
write() writes a string to file, so concatinate first.

sneekula 969 Nearly a Posting Maven

The function sqrt(x) returns a float:

import math

x = 9
y = math.sqrt(x)

print y, type(y)  # 3.0 <type 'float'>

If you want the result to be an integer use int(y).

sneekula 969 Nearly a Posting Maven

A program called Boa Constructor is wxDev-CPP's couterpart for Python programming. It uses wxPython and has a drag and drop frame builder.

See the post at:
http://www.daniweb.com/forums/post400296-107.html

sneekula 969 Nearly a Posting Maven

We used the DrPython IDE at school too. I like it.

sneekula 969 Nearly a Posting Maven

graphics.py is a simple wrapper for Tkinter written by the author of a Python book. It mostly contains renamed canvas routines.

I would stick with Tkinter itself. You get more help this way since only a few folks know about this Zelle wrapper.

sneekula 969 Nearly a Posting Maven

There is an old Python to C conversion program (2001):
http://sourceforge.net/projects/py2cmod/

Another program is this Python to C++ converter (2007):
http://sourceforge.net/projects/shedskin/

Also a Python for Delphi program exsist (2007):
http://mmm-experts.com/Products.aspx?ProductId=3
These are the folks that wrote the PyScripter IDE.

sneekula 969 Nearly a Posting Maven

Why not use code tags so the indentations are preserved in your Python code?

This should work:

def delete(self):
    fname = raw_input("First Name:> ")
    for ix, item in enumerate(self.list):
        if (item.name == fname):
            del self.list[ix]
sneekula 969 Nearly a Posting Maven

It looks like fixed means that variable1 value has to come from dlist1 and is fixed to the Server and variable2 value comes from dlist2 and is fixed to the Client. At least that is the way I understand this.

sneekula 969 Nearly a Posting Maven

Try this small change:

import sys

class Person:

    def __init__(self):
        self.list = []

    def AddContact(self):
        fname = raw_input("First Name:> ")
        lname = raw_input("Last Name:> ")
        street = raw_input("Street:> ")
        self.list = [ fname, lname, street]

    def ListAll(self):
        print ""


    def DeleteContact():
        print ""


class NewPerson():

    def __init__(self):
        self.v = Person()   # change here
        self.option()

    def option(self):
        print "--------- Options ---------\n"
        print " |1) Add/Update |\n"
        print " |2) List All |\n"
        print " |3) Delete Contact |\n"
        print " |4) Exit |\n"
        opt = raw_input(":> ").lower()
        if opt == '1':
            self.v.AddContact()   # change here
        elif opt == '2':
            self.v.ListAll()   # change here
        elif opt =='3':
            self.v.DeleteContact()   # change here
        elif opt == '4':
            sys.exit
        else:
            print "Invalid choice."
        self.option()

if __name__ == '__main__':
    v = NewPerson()
    v.option()

Also, enclose your code in code tags to preserve the indents. Temporarily click on "REPLY W/QUOTE" to see how I did it.

sneekula 969 Nearly a Posting Maven

This forum could stand a balanced moderator like you AD! Please do us all a favor and apply for it.

sneekula 969 Nearly a Posting Maven

Put the code between code tags. Read the lightgray message in the background of the Quick Reply field below.

Or read:
http://www.daniweb.com/forums/announcement114-3.html

sneekula 969 Nearly a Posting Maven

Here is one example:

# put two different size panels into a wxBoxSizer

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(250, 70))
        panel = wx.Panel(self, -1)
        panel1 = wx.Panel(panel, -1, size=(50, 30))
        panel1.SetBackgroundColour('blue')
        panel2 = wx.Panel(panel, -1, size=(200, 30))
        panel2.SetBackgroundColour('green')
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(panel1, 1)
        box.Add(panel2, 1)
        panel.SetSizer(box)
        self.Centre()

class MyApp(wx.App):
     def OnInit(self):
         frame = MyFrame(None, -1, 'wxBoxSizer.py')
         frame.Show(True)
         return True

app = MyApp(0)
app.MainLoop()
sneekula 969 Nearly a Posting Maven

Are we talking about the earth? I have always looked at "world" as something larger than "earth".

sneekula 969 Nearly a Posting Maven

In the US, we also have Soul Food or Southern Cooking:

Soul Food originated from slaves' diet. For vegetables slaves used basically plants that were in those days considered weeds like collard greens, kale, cress, mustard, and pokeweed. Their recipes used discarded meat from the plantation, such as pig’s feet, beef tongue or tail, ham hocks, chitterlings (pig small intestines), pig ears, hog jowls, tripe and skin. Cooks added onions, garlic, thyme, and bay leaf to enhance the flavors.

sneekula 969 Nearly a Posting Maven

Have you ever gotten your code to do anything? The way it is now it will not work, even in its simplest form.

sneekula 969 Nearly a Posting Maven

There is 'Starting Python' right here to give you a taste:
http://www.daniweb.com/techtalkforums/thread20774.html

A good starter tutorial:
http://bembry.org/technology/python/index.php

Another good starter tutorial:
http://www.ibiblio.org/g2swap/byteofpython/read/

And of course there is always the latest update:
http://www.python.org/doc/current/tut/tut.html

Now watch out, Python takes an open mind and is addictive!

iamthwee commented: Good info matey +9
sneekula 969 Nearly a Posting Maven

I think there is a logic flaw in either code, since you are not using the result of the recursion call. It seems to pile up in a return stack somewhere! If you uncomment Bumsfeld's internal print statement, it will print a whole bunch (counted 31) of sixes

sneekula 969 Nearly a Posting Maven

I didn't have a file, so I used just a text string for testing, but here is one way you can solve this:

text = "I love to work, but not paying my taxes!"
 
# text to word list
words = text.split()
print words  # testing the word list
 
# now comes the processing part
new_words = []
for word in words:
    # remove certain punctuations
    for c in '?!,.;:':
        if c in word:
            word = word.replace(c, '')
    # it's a 4 letter word, replace with 'xxxx'
    if len(word) == 4:
        word = 'xxxx'
    new_words.append(word)
 
# list back to text
print ' '.join(new_words)
sneekula 969 Nearly a Posting Maven

You can also use module numpy:

import numpy
v1 = numpy.array([1, 2, 3, 4])
v2 = numpy.array([4, 3, 2, 1])
# product
print v1*v2                    # [4 6 6 4]
# scalar product
print numpy.add.reduce(v1*v2)  # 20

Numpy is a free high speed numeric extension module used by engineers and scientists.

sneekula 969 Nearly a Posting Maven

I think your print to the display will be by far the slowest operation.

sneekula 969 Nearly a Posting Maven

This re stuff makes my head spin! I can see that it is very powerful for text processing, but also seemingly very complex! Almost another language within Python.