vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

“Until we're educating every kid in a fantastic way, until every inner city is cleaned up, there is no shortage of things to do.”
-- Bill Gates

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Innovation has nothing to do with how many R&D dollars you have. When Apple came up with the Mac, IBM was spending at least 100 times more on R&D. It's not about money. It's about the people you have, how you're led, and how much you get it."
-- Steve Jobs

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hide the root window with:
root.withdraw()

Bring the root window back up with:
root.update()
root.deiconify()

Remove root window border and title bar with:
root.overrideredirect(True)

Bring the border and title bar back after 5000 milliseconds:
root.after(5000, root.overrideredirect, False)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Actually 22/7 is pretty crude. The Chinese Approximation of pi is much better. Simply use 355/113. You can remember this by looking at the first three odd integers written this way 113355.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This program uses the Python win32 extension module to get information on disk or flash drives for Windows machines. Specify the drive with its letter. If no drive letter is specified, the current drive is applied.

scru commented: Nice post +4
Gribouillis commented: Nice +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Take a look at this recent thread:
http://www.daniweb.com/forums/thread241860.html
were we discussed functions and parameter passing.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Tkinter is Python's wrapper of the GUI toolkit Tk, originally written in a computer language called TCL. Tkinter has the advantage of a small footprint, also IDLE, the IDE that ships with Python, is written in Tkinter. Whatever program you have has to deal with the Operating System of your computer to be able to do anything.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Don't overlook the fact that the Python installer you use is specific for the Operating System. If you install Python on a Windows OS, the GUI toolkits will use the Windows GUI. A similar thing goes for Linux or the Mac OSX.

Python source code is largely cross platform, but the actual interpreter is specific to each OS. The GUI toolkits follow the same rule.

lrh9 commented: Good point. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Okay, i think i understand. Basically you pass a variable from one function to another by 'returning' it ?

And the next functions parameters are supposed to include the variable(s) name(s)?

You pass variables as need as function arguments and/or returns.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Anyone who has the power to make you believe absurdities has the power to make you commit injustices.
-- François-Marie Arouet a.k.a. Voltaire

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a rather simple example of a number of functions working together from:
http://www.daniweb.com/forums/showthread.php?p=104853#post104853

def get_name():
    """this function only returns arguments"""
    first = "Fred"
    last = "Ferkel"
    return first, last

def show_name(name):
    """this function only receives an argument"""
    print( name )

def process_name(first, last):
    """this function reveives 2 arguments, returns 1 argument"""
    name = "Mr. " + first +" " + last
    return name

def main():
    """
    this function handles the other functions in order
    and deals with the arguments received and to be passed
    """
    first, last = get_name()
    name = process_name(first, last)
    show_name(name)

# start the program with this function call
main()
Ene Uran commented: nice example +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The function main() can be simplified ...

def main():
    while True:
        fahrenheit2celsius()
        cont = raw_input('Continue converting? (yes/no): ')
        if 'n' in cont.lower():
            break

while True forms an endless loop and the n in no or NO will break out of the loop.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This language sure has no diacritical marks and should be ok for everybody, because nobody can really claim it as his. Except for some people, who live far away from Earth...

I am surprised the Klingons had no F. Imagine a language without F words!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Being young is a fault which improves daily.
-- 4,000

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Someone who lies for you will also lie against you.
-- 3,999

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Clean your own yard first before asking others to clean theirs.
-- Bosnian Proverb

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In the end a needle weighs heavy.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Truth seldom finds a home.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Never let what you don't know disturb your faith in what you do know.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A bad workman always blames his tools.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Our faults irritate us most when we see them in others.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Patience is a tree whose root is bitter, but its fruit is very sweet.
-- APS motto

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Darn, another meaningless question!

Here I though I would stimulate somebody's thought process.

jasimp commented: Haha. Nice try ;) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Two eggs over easy and fried potatoes and onions. A mug of breakfast stout.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

use temp = self.set_greyLevel(grayScale)

vsagarmb commented: thanks a lot +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I prefer design 1. We don't know anything about the algorithms that you have in mind, so there is no obvious benefit for introducing the classes Search and Edit. With design 1, the Library object appears as a facade behind which you can implement arbitrary complex and flexible algorithms.
Also I don't think it's a good idea to use nested classes in general. There is no gain in nesting classes and they will be more accessible if you implement them linearly at module level.

I tend to agree with Gribouillis. As your program grows you can split out some classes in a linear fashion. Later on, as the bugs are worked out, turn them into modules

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Xmas spirits.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Every sperm is sacred
Every sperm is great
If a sperm is wasted
God gets quite irate.
-- Monty Python (The Meaning of Life, 1983)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

after pylab.show() I don't get the >>> in IDLE!
The program stalls on that last pylab.show() statement.

For heaven sake don't run the code from the Python shell!
Run it from the editor!

The python shell is used for testing very short Python code concepts, mostly one-liners!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I tried the latest version of Eric (4.3.9). It assiste with PyQT syntax, but does not accept the newer connect style used with PyQT 4.5+. Somewhat irritating!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

__str__() does operator overloading in a class and "hijacks" str() in any class instance operation that uses str(). So print crit1 will use it, because it uses str() to make it printable. Whereas crit1.name is already printable.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This simple wxPython slide show uses the wx.PaintDC surface as a canvas that can be cleared between pictures ...

# create a simple image slide show using the
# wx.PaintDC surface as a canvas and
# DrawBitmap(bitmap, x, y, bool transparent)
# vegaseat

import wx
import os

class ShowPic(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.ID_ANY, 'MyFrame', 
            size=(773,632))
        self.panel = wx.Panel(self)
        
        # seconds per slide
        self.delay = 2
        # number of loops per slide show
        self.loops = 2 
        
        # list of image files you have in the working directory
        self.images = ["Pic1.png", "Pic2.png", "Pic3.png"]

        # create a list of bitmap image objects
        self.image_list = []
        for image_file in self.images:
            if os.path.exists(image_file):
                print(image_file)  # test
                self.image_list.append(wx.Bitmap(image_file))
            else:
                self.SetTitle("No pictures found!")

        # bind the panel to the paint event
        wx.EVT_PAINT(self.panel, self.onPaint)

    def onPaint(self, event=None):
        # this is the wxPython drawing surface/canvas
        dc = wx.PaintDC(self.panel)
        while self.loops:
            self.loops -= 1
            for ix, bmp in enumerate(self.image_list):
                # clear the canvas
                dc.Clear()
                # optionally show image name
                self.SetTitle(self.images[ix])
                # draw the image
                dc.DrawBitmap(bmp, 10, 10, True)
                # wait self.delay seconds to show next slide
                wx.Sleep(self.delay)


if __name__=='__main__':
    app = wx.App(0)
    frame = ShowPic(parent=None)
    frame.Show()
    app.MainLoop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Tkinter can be used to write programs that use pop-up dialogs for input and output. The nice thing is that the input dialogs can restrict data input to integer, float or string input with options for initial, min and max values. Here is a small example ...

# use Tkinter popup dialogs for input and output
# see:
# http://www-acc.kek.jp/WWW-ACC-exp/KEKB/control/Activity/Python/
#   TkIntro/introduction/intro08.htm
# simple dialogs are:
# askfloat, askinteger, and askstring
# messagebox dialogs are:
# showinfo, showwarning, showerror, askquestion, askokcancel,
# askyesno, askretrycancel
# vegaseat

try:
    # Python2
    import Tkinter as tk
    import tkSimpleDialog as tksd
    import tktkMessageBox as tkmb
except ImportError:
    # Python3
    import tkinter as tk
    import tkinter.simpledialog as tksd
    import tkinter.messagebox as tkmb

def get_data():
    # tksd.askfloat(title, prompt [,options])
    miles = tksd.askfloat('Miles', 'Enter miles driven')
    # give minvalue to avoid division by zero errors
    gal = tksd.askfloat('Petrol', 'Enter gallon of petrol consumed',
        minvalue=0.1)
    str_result = "Your milage is %0.2f miles/gallon" % (miles/gal)
    # tkmb.showinfo(title, message [, options])
    tkmb.showinfo('Result:', str_result)

root = tk.Tk()
str_var = tk.StringVar()

tk.Button(root, text="Get data", command=get_data).pack(pady=5)

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

I assume the question is:
Who is foolish enough to do my homework for me?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple way to add color highlighted text to the Tkinter Text() widget ...

# multiple color text with Tkinter using widget Text() and tags
# vegaseat

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

def color_text(edit, tag, word, fg_color='black', bg_color='white'):
    # add a space to the end of the word
    word = word + " "
    edit.insert('end', word)
    end_index = edit.index('end')
    begin_index = "%s-%sc" % (end_index, len(word) + 1)
    edit.tag_add(tag, begin_index, end_index)
    edit.tag_config(tag, foreground=fg_color, background=bg_color)


root = tk.Tk()
root.geometry("600x200")

edit = tk.Text(root)
edit.pack()

text = "Up the hill went Jack and Jill, down fell Jill and cried!"
# create a list of single words
word_list = text.split()
#print( word_list )  # test

# pick word to be colored
myword1 = 'Jack'
myword2 = 'Jill'
# create a list of unique tags
tags = ["tg" + str(k) for k in range(len(word_list))]
for ix, word in enumerate(word_list):
    # word[:len(myword)] for word ending with a punctuation mark
    if word[:len(myword1)] == myword1:
        color_text(edit, tags[ix], word, 'blue')
    elif word[:len(myword2)] == myword2:
        color_text(edit, tags[ix], word, 'red', 'yellow')
    else:
        color_text(edit, tags[ix], word)

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

When you use a.extend(b) or a.sort() then list a is changed, since both are inplace functions. Also when you pass a list to a function argument, be aware that the list is a mutable object and changes of a mutable object within the function will feed back. The reason is that with mutable objects the address is passed rather than the value. This often surprises beginning programmers.

Adding two lists without changing any of the original list ...

def add_lists(a, b):
    """add lists a and b without changing list a"""
    # make a true copy of a to avoid any chance of feedback
    t = list(a)
    return t + b

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = add_lists(a, b)

print( c )  # ['a', 'b', 'c', 1, 2, 3]

Split a list in half ...

def half_list(a):
    """split a list in half using slicing"""
    h = len(a)//2
    return a[:h], a[h:]

a = [1, 2, 3, 4, 5, 6]
b, c = half_list(a)

print( b )  # [1, 2, 3]
print( c )  # [4, 5, 6]

The function sorted() was introduced with Python24 and does not sort inplace ...

arr = [1, 2, 4, 3, 2]

# sort arr without changing arr
b = sorted(arr)

print( b )  # [1, 2, 2, 3, 4]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Pumpkin icecream (a real treat usually sold around Thanksgiving in the US).

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It is a beggar's pride that he is not a thief.
-- Thai Proverb

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An accomplishment sticks to a person.
-- Japanese Proverb

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

When the can of frozen Orange juice says "Concentrate" and you do.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Eggs, sunny side up, toasted English muffin with plum jelly.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Why don't you just run the sample code I gave you with the image_file = "mars.jpg" and make sure you have the image file in the working directory or give it the full path.

Avoid the crap you added to the start of the code!!!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The C function getch() will return a byte string in Python3, so you have to decode it.

Something like that ...

# windows console only
# C:\Windows\System32\msvcrt.dll contains C functions

from msvcrt import getch

while True:
    # Python3 byte string to string
    print( getch().decode("utf8") )
e-papa commented: straight to the point. +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Pygame can load quite a number of image formats. Here is an example ...

# experiments with module pygame
# free from: http://www.pygame.org/
# load and display an image using pygame

import pygame as pg

# initialize pygame
pg.init()

# pick an image you have (.bmp  .jpg  .png  .gif)
# if the image file is not in the working folder,
# use the full pathname like "C:/Images/gifs/Pooh.gif"
image_file = "Pooh.gif"

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

# create a 300x300 white screen
screen = pg.display.set_mode((300,300),  pg.RESIZABLE )
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
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

OK, I read the paper that was linked to above and the comments in this thread so far.

So back in the old days, before Python 2.3 we only had Classic Classes and we created them using this syntax

class Gato:
    def __init__(self):
        self.name="fluffy"

But now we're supposed to use the new style of classes which uses this syntax:

class Gato(object):
    def __init__(self):
        self.name="fluffy"

And then starting in Python 3.0 we will go back to declaring our classes the way we did back in the old days, but we will still get new style classes.

Am I right on this so far?

Correct. Don't you admire the beauty of Python version changes? Right out of a Monty Python show!

Actually, most computer languages have had their fair share of version changes, they are always for the better!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You could do something simple like this ...

from graphics import *
import random

def drawCircle(win, centre, radius, colour):
    circle = Circle(centre, radius)
    circle.setFill(colour)
    circle.setWidth(2)
    circle.draw(win)

def drawEye(win, centre):
    drawCircle(win, centre, 40, "green")
    drawCircle(win, centre, 20, "brown")
    drawCircle(win, centre, 10, "blue")

def createWin():
    w = 250
    h = 250
    win = GraphWin("Click Spooky Eyes", w, h)
    while True:
        # center should be at 1/2 width and height
        # but give it a random offset
        x = random.randint(-w//2, w//2)
        y = random.randint(-h//2, h//2)
        centre = Point(w//2+x, h//2+y)
        drawEye(win, centre)
        # click the mouse for next eye
        win.getMouse()

createWin()

I need to warn you that very few people use the Zelle module graphics and it only works with Python2.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Back to the original code, this would have made more sense ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        self.name = playername

    def getName(self):
        return "I am %s" % self.name

# create the class instance bob
bob = Player("Bob")

print(bob.name)      # Bob
print(bob.getName()) # I am Bob

... or making the name private to the class ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        # double underline prefix makes 
        # __name private to the class
        self.__name = playername

    def getName(self):
        return self.__name

# create the class instance bob
bob = Player("Bob")
try:
    # you cannot access a private class variable
    # so it would be an error, nothing will print
    print(bob.__name)
except:
    pass
# now you have to use the method to get the name
print(bob.getName())  # Bob
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe Windows is simply too unsafe for Go.

Actually the syntax looks a lot like a mix of Object Pascal and C++, not sure where the beauty of Python went.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The nice thing about Xydric's approach is that it doesn't lose the important connectivity with the original dictionary via the keys ...

data = {
'1234': ['Matt', '2.5', 'CS'],
'1000': ['John', '4.0', 'Music'],
'1023': ['Aaron', '3.1', 'PreMed'],
'1001': ['Paul', '3.9', 'Music'],
'9000': ['Kris', '3.5', 'Business']
}

# sort by index in value, here GPA values at index 1
# gives a list of keys in that specified order
key_list = sorted(data, key=lambda x: data[x][1])

gpa_list = [data[key][1] for key in key_list]

print( gpa_list )  # ['2.5', '3.1', '3.5', '3.9', '4.0']

# now if you wanted to know who got the 2.5
# it should be the first key in the key_list too (at index=0)
print( data[key_list[0]] )     # ['Matt', '2.5', 'CS']
# or ...
print( data[key_list[0]][0] )  # Matt
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

When you have a project like this, it is best to test each shape you want to draw before you combine it all. Let's start out with a pygame template that you can use for each shape ...

import pygame
import random

pygame.init()
w = 640
h = 480
screen = pygame.display.set_mode((w, h))

# set (r, g, b) color tuple
color = (random.randrange(255), random.randrange(255), 
    random.randrange(255))


# ... your shape code goes here ...


# update display
pygame.display.flip()

# event loop ...
running = True
while running:
    for event in pygame.event.get():
        # quit when window corner x is clicked
        if event.type == pygame.QUIT:
            running = False

Now let's test the rectangle shape ...

import pygame
import random

pygame.init()
w = 640
h = 480
screen = pygame.display.set_mode((w, h))

# set (r, g, b) color tuple
color = (random.randrange(255), random.randrange(255), 
    random.randrange(255))


# set rect corner coordiates to draw a rectangle
# (x1, y1, x2, y2) upper left and lower right corner coordinates
rect = (random.randrange(w), random.randrange(h), 
    random.randrange(w), random.randrange(h))
# pygame.draw.rect(Surface, color, Rect, width=0)
# if width=0 (or not given) the rectangle is filled with color
pygame.draw.rect(screen, color, rect)


# update display
pygame.display.flip()

# event loop ...
running = True
while running:
    for event in pygame.event.get():
        # quit when window corner x is clicked
        if event.type == pygame.QUIT:
            running = False

... next test the line ...

import pygame
import random

pygame.init()
w = 640
h = 480
screen = pygame.display.set_mode((w, h))

# set (r, g, b) color tuple
color …