Ene Uran 638 Posting Virtuoso

If you think VB, C, C++, C# or Java is really great stuff, then it's too late.

Ene Uran 638 Posting Virtuoso

The proof is in the pudding. Take a small project like creating a monthly calendar and try to do it with Java and then with Python.

Ene Uran 638 Posting Virtuoso

Dancing
Jazz
Wines
History
Politics

Ene Uran 638 Posting Virtuoso

We learned that it is only used for function arguments, and ** indicates a dictionary of variable number of key:val arguments.

Ene Uran 638 Posting Virtuoso

Nice clean code there Lardmeister. Did you switch from C# to Python?

Ene Uran 638 Posting Virtuoso

Hey Henri, thanks for the info on Python30.

Ene Uran 638 Posting Virtuoso

Python has list, tuple, and array containers.
What is your definition of a safearray?

Ene Uran 638 Posting Virtuoso

There is no simple dictionary function build in, since values may not be unique, but you can use this:

# search a dictionary for key or value

def find_key(dic, val):
    """return the key of dictionary dic given the value"""
    return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
    """return the value of dictionary dic associated with a given key"""
    return dic[key]

# test it out
if __name__ == '__main__':
    # dictionary of chemical symbols
    symbol_dic = {
    'C': 'carbon',
    'H': 'hydrogen',
    'N': 'nitrogen',
    'Li': 'lithium',
    'Be': 'beryllium',
    'B': 'boron'
    }

    print find_key(symbol_dic, 'boron')  # B
    print find_value(symbol_dic, 'B')    # boron

I used functions for both searches naming them so it's easier to read.

ZZucker commented: nice clean code +1
Ene Uran 638 Posting Virtuoso

Another suggestion would be not to use the IDLE IDE but something like the popular DrPython IDE (needs wxPython) or the PyScripter IDE.

I agree, IDLE is a leftover from the early days of Python and is still in the Python distribution. It has some issues with some of the Vista settings, even though on my Vista computer I got it to work once or twice after many initial problems.

To me the DrPython IDE has always been the most stable.

Ene Uran 638 Posting Virtuoso

To me the Tkinter GUI toolkit is about as simple as it comes. If you really want to get into fancy widgets (html, plotting, sound), then switch to wxPython. That however is somewhat of a steep learning curve.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

Wikipedia is wrong. A JDK is a full SDK, so it's an implementation of the concept of
"SDK" rather than a subset of it.

The wikipedia is selfcorrecting, give it a try.

Ene Uran 638 Posting Virtuoso

I think the end of the world will be more like 2013. There is always a delay in such big events.

Ene Uran 638 Posting Virtuoso

Yeah Irish!
I think it is regular and good beer with some green food coloring added, just a fun way to feel Irish away from home and get stoned! You guys at home have the green island to look at.

Ene Uran 638 Posting Virtuoso

Are you sure you are Irish? In the good old USA everybody with Irish blood flowing in their veins, or living in a mildly Irish neighborhood, drinks green beer to honor St. Patrick on March 17!

Ene Uran 638 Posting Virtuoso

I am with you there, love Irish stew made from browned lamb, potatoes, onions, a shot of whisky, some parsley and spices! mmmmmm! Goes well with a glass of Guinness stout with a nice thick creamy head.

Of course on St. Patricks Day it has to be green beer and a steamy plate of corned beef and cabbage.

Ene Uran 638 Posting Virtuoso

... no one can know the End of the world except God ...

Will that be the day HE considers the experiment failed and throws all of mankind into the trash?

Ene Uran 638 Posting Virtuoso

no offense, but this just sounds like some people who are very paranoid made this up...

It's on the Internet, so it must be true!

Ene Uran 638 Posting Virtuoso

The Antichrist is meant to pave the way for the second coming of Jesus and does not cause the end of the world.

So Jesus causes the end of the world? Isn't there supposed to be an enormous blood bath?

Ene Uran 638 Posting Virtuoso

End of the world: "Where is the Antichrist in all of this?"

Logo: "Well, it's different! Sort a like cat poop on a fancy meal!"

Ene Uran 638 Posting Virtuoso
>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Haha! Favorite error ever! All versions of python have this "hidden feature." It's obviously making fun at C. : P

A very funny discovery, thank you!

Ene Uran 638 Posting Virtuoso

If you have empty strings in the list you can change BearofNH's code simply:

mylist  = ["CAnADA", "hELLO", "", "CAN"]
# use list comprehension
newlist = [ x[0]+x[1:].lower() for x in mylist if x ]
print newlist
"""
my output -->
['Canada', 'hello', 'Can']

a list comprehension is a more efficient way of coding this ...
newlist =[]
for x in mylist:
    if x != "":
        newlist.append(x[0]+x[1:].lower())
"""
Ene Uran 638 Posting Virtuoso

SOS is right! You can find peons in every field of endeavour. That goes from a farmer, teacher, soldier, priest, scientist all the way to a country's leader.

Ene Uran 638 Posting Virtuoso

This would be a very basic pygame program, see if you can get that to work:

# fooling around with pygame --> draw/fill some rectangles

import pygame as pg

# initiate pygame first
pg.init()

#create a 400x300 window
screen = pg.display.set_mode((400, 300))
# give it a title
pg.display.set_caption('Draw/fill rectangles using pygame')

# some color constants
white = 0xFFFFFF
red = 0xFF0000
green = 0x00FF00
blue = 0x0000FF
yellow = 0xFFFF00

#draw/fill a 77x33 rectangle in position x=250, y=50 (NW corner)
screen.fill(white, (250, 50, 77, 33))

# more rectangles, vary color, size, position ...
screen.fill(red, (30, 20, 70, 120))
screen.fill(red, (140, 70, 90, 80))
screen.fill(green, (150, 80, 70, 60))
screen.fill(yellow, (200, 170, 150, 60))
screen.fill(blue, (70, 200, 100, 70))

# hey, nothing gets displayed until one updates the screen
pg.display.update()

# create the event loop to get things going
# and specify an exit action (clicking on the window x)
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            raise SystemExit
Ene Uran 638 Posting Virtuoso

This will show the even integers between 2 and limit, then it is up to you to show the product:

#include <stdio.h>

int main()
{
  int x;
  int limit = 30;
  
  for(x = 2; x <= limit; x=x+2)
  {
    printf("%d\n", x);
  }
  
  getchar();  // wait for enter
  return 0;
}
Ene Uran 638 Posting Virtuoso

"Is Python any good?"
I don't think this person really wants to know, so my question is:
"Is iamthwee any good?"

Ene Uran 638 Posting Virtuoso

Soemthing like that?

s = "c:/hello/scot"
if s.endswith("scot"):
    s = s.replace("scot", "bob")

print s  # c:/hello/bob
Ene Uran 638 Posting Virtuoso

The hardware should achieve microsecond resolution, but the layers of software you have to go through will negate that!

Even if the Python interpreter has a high priority level, the timing will change, since the operating sytems runs plenty of other programs in the background (keyboard, mouse, screen updates, virus, active malware, spyware etc.).

If you want to achieve just millisecond resolution amongst samples, you will have to average a fair number of samples. That holds true for many things you do in the sciences.

Ene Uran 638 Posting Virtuoso

The datetime module will do micro-seconds

import datetime 
print datetime.datetime.now()
time_now = datetime.datetime.now()
print time_now

Not really! If you look at the output, the digits that correspond to microseconds will always be zeroes. But you could hope for millisecond resolution.

Ene Uran 638 Posting Virtuoso

I modified mawe's code so you don't have to worry about the date of the day:

# using just time and not date ...
import datetime

lunch_start = datetime.time(11, 30)
lunch_end = datetime.time(12, 45)
now = datetime.datetime.now().time()

# testing
print lunch_start  # 11:30:00
print lunch_end    # 12:45:00
print now          # eg. 09:05:59.750000

# you can compare type 'datetime.time' directly
if lunch_start < now < lunch_end:
    print "Hey, it's lunch time!  Mahlzeit!!"
elif now < lunch_start:
    print "Lunch is pretty soon!"
else:
    print "Darn, missed lunch time!!"
Ene Uran 638 Posting Virtuoso

Several things:
Try to give Tkinter and Calendar a namespace, so you know where the functions come from.
Give variables names that don't confuse, like 'l1' looks a lot like '11' in many editors, switching to 'lb1' helps readability.

Please use the [code=python] and [/code] tag pair to enclose your python code.


Here is my suggestion:

# display a monthly calendar in Tkinter

import Tkinter as tk
import calendar as cd

class MyApp(object):
    def __init__(self, root, m, y):

        self.m = m
        self.y = y
        self.frame1 = tk.Frame(root)
        self.frame1.pack()
        str1 = cd.month(self.y, self.m)
        font1 = ('courier',14,'bold')
        self.lb2 = tk.Label(self.frame1, text=str1, font=font1, bg='yellow')
        self.lb2.pack()
        self.b1 = tk.Button(self.frame1,text=' - ', bg="green")
        self.b1.pack(side=tk.LEFT, padx=3, pady=3)
        self.b2 = tk.Button(self.frame1,text=' + ',bg="red")
        self.b2.pack(side=tk.RIGHT, padx=3, pady=3)
        
        self.b1.bind("<Button-1>", self.decrease)
        self.b2.bind("<Button-1>", self.increase)
        
        root.mainloop()

    def increase(self, e):
        if self.m == 12:
            self.m = 1
            self.y = self.y + 1
        else:
            self.m = self.m + 1
        self.lb2['text'] = cd.month(self.y, self.m)

    def decrease(self, e):
        if self.m == 1:
            self.m = 12
            self.y = self.y - 1
        else:
            self.m = self.m - 1
        self.lb2['text'] = cd.month(self.y, self.m)


if __name__ == '__main__':
    y = 2007
    m = 1
    root = tk.Tk()
    root.title("monthly calendar")
    myapp = MyApp(root, m, y)
Ene Uran 638 Posting Virtuoso

A couple of things wrong with your countdown timer.
1 - don't limit the size of your root window, widgets won't fit
2 - labels take strings
3 - root.update() is needed
Look this over:

#Gamal Crichton
#Teje's Counter
#04/02/07

from Tkinter import *
import time

class Application(Frame):
    def __init__(self,master,act_name,time_):
        Frame.__init__(self,master)
        self.hh=time_[0]
        self.mm=time_[1]
        self.ss=time_[2]
        self.name=act_name
        self.grid()
        print time_
        self.disp_widgets()
        self.aggregate()
        
        
    def disp_widgets(self):
        #Uses labels to display time.
        Label(self,
              text=self.name, font=("Arial, 32")
              ).grid(row=0,column=0,columnspan=3,sticky=W)
        
        self.hourlbl=Label(self,
              text=str(self.hh), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.hourlbl.grid(row=1,column=0,columnspan=1,sticky=W)

        self.minutelbl=Label(self,
              text=str(self.mm), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.minutelbl.grid(row=1,column=1,columnspan=1,sticky=W)
        
        self.secondlbl=Label(self,
              text=str(self.ss), font=("Arial, 40")  # str()!!!!!!!!!!
              )
        self.secondlbl.grid(row=1,column=2,columnspan=1,sticky=W)
        
        Button (self,
                text="Stop",
                command=self.show,
                ).grid(row=2,column=0,columnspan=3,sticky=EW)
        
    def show(self):
        # needs more stuff
        print "Booooooooo!"

    def aggregate(self): #This function is supposed to decrement the time
        for hours in range(self.hh, -1, -1):
            for minutes in range(self.mm, -1, -1):
                for seconds in range(self.ss, -1, -1):
                    time.sleep(1)
                    root.update()  # needed!!!!!
                    self.secondlbl["text"]=str(seconds)  # str()!!!!!!!!!! 
                    if self.ss==0:
                        self.ss=60
                self.minutelbl["text"]=str(minutes)  # str()!!!!!!!!!!
                if self.mm==0:
                    self.mm=0
            self.hourlbl["text"]=str(hours)  # str()!!!!!!!!!!

#Main
root=Tk()

root.title("Timer!")

#root.geometry("250x75")  # do not use, too space restrictive!!!

app= Application(root, " Timer ", [2, 4, 5])

root.mainloop()
Ene Uran 638 Posting Virtuoso

Unless you have a huge amount of events in your loop, it could very well be your mouse.

mattyd commented: Tkiner GUI #Always helpful ;) mattyd +3
Ene Uran 638 Posting Virtuoso

... and old code will break frequently, since division will no longer yield integers. :eek:

Jeff

This is why it hasn't been implemented yet in a large number of other languages like C, C++ either.

Ene Uran 638 Posting Virtuoso

Here is something very simple that you can fancy up with a +/- year and a +/- month button:

# as simple monthly calendar with Tkinter

# give calendar and Tkinter abbreviated namespaces
import calendar as cd
import Tkinter as tk

# supply year and month
year = 2007
month = 2    # jan=1

# assign the month's calendar to a multiline string
str1 = cd.month(year, month)

# create the window form and call it root (typical)
root = tk.Tk()
root.title("Monthly Calendar")

# pick a fixed font like courier so spaces behave right 
label1 = tk.Label(root, text=str1, font=('courier', 14, 'bold'), bg='yellow')
label1.pack(padx=3, pady=5)

# run the event loop (needed)
root.mainloop()
Ene Uran 638 Posting Virtuoso

Welcome S.O.S to the Python crowd. We are all quite nice in Python land, just here to learn more!

Small Miss Steaks are accepted, gives the rest of us the opportunity to show off how smart we are.

Ene Uran 638 Posting Virtuoso

That will do it Jeff! HeHe, love the word "tweakery".

Ene Uran 638 Posting Virtuoso

Here is vegaseat's fancy Tkinter GUI "Hello World!" code:

# a simple "Hello, world!" Tkinter GUI
# add some color and a larger text font
# add buttons to change text color and fancy them up

# import Tkinter as namespace tk
import Tkinter as tk 

def white_blue():
    label1.config(fg='white', bg='blue')

def blue_green():
    label1.config(fg='blue', bg='green')

# create the basic window, let's call it 'root'  
root = tk.Tk()
# why not add a title
root.title("Hello World from DaniWeb!")

# create a label with colors in it
font1 = ('times', 36, 'bold')
label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow') 
# let's use a grid to put the label into the window
# make it span two grid columns
label1.grid(row=0, column=0, columnspan=2)
# create 2 buttons to click for text color change
# use the two grid positions below the label
# (by default the button will take up the center of each grid space)
# give the buttons some y-axis space and a ridge style
button1 = tk.Button(root, text="white on blue", relief='ridge', command=white_blue)
button1.grid(row=1, column=0, pady=5)
button2 = tk.Button(root, text="blue on green", relief='ridge', command=blue_green)
button2.grid(row=1, column=1, pady=5)

# run the GUI event loop
root.mainloop()

Here is the same program written in wxPython, seems to be slightly more complex:

# a simple "Hello, world!" wxPython GUI
# add some color and a larger text font
# add buttons to change text color and fancy them up

import wx

def white_blue(event):
    label1.SetBackgroundColour("blue")
    label1.SetForegroundColour("white")
    label1.SetLabel("Hello World!")

def blue_green(event):
    label1.SetBackgroundColour("green")
    label1.SetForegroundColour("blue")
    label1.SetLabel("Hello World!")

app …
Ene Uran 638 Posting Virtuoso

Since the data is coming from a raw source (text file, database, user input...) wouldn't it be nice if we didn't assume that the "[" will always be the first character of "txt" and "]" is not always the last character of "txt".

Given that the data can also be of the form " [ 32] " or "[32 ]". To handle such situations here is what I have come up with....

data_raw = """[20 ]
[ 35 ]
[40  ]
[84 ]
[100 ]
[ 245]
[  260]
[ 300 ]
[ 440 ]
[   521     ]
[ 650    ]
"""
data_list = data_raw.split()
print data_list  
data_list2 = [x.strip(" []") for x in data_list]
print data_list2

No cigars on that one s.o.s, here is the result I get:

"""
my output -->
['[20', ']', '[', '35', ']', '[40', ']', '[84', ']', ...]
['20', '', '', '35', '', '40', '', '84', '', ...]
"""
Ene Uran 638 Posting Virtuoso

Before I forget, you can also go into the DaniWeb Code Snippets section and search the Python Snippets for Tkinter. There are a fair number of Tkinter code snippets in there at various levels of complexity.

You can also search for wxPython and get a similar response.

Ene Uran 638 Posting Virtuoso

I am a little lost here. I assume your data comes from a file? Well, anyway, using assumptions here is some code:

def strip_brackets(txt):
    if txt[0] == "[":   # remove leading '['
        txt = txt[1:]
    if txt[-1] == "]":  # remove trailing ']'
        txt = txt[:-1]
    return txt

# assume your data string looks like this
data_raw = """[20]
[35]
[40]
[84]
[100]
[245]
[260]
[300]
[440]
[521]
[650]
"""

data_list = data_raw.split()
# test
print data_list  # ['[20]', '[35]', '[40]', '[84]', ...]
# convert to a list of numeric strings
data_list2 = [strip_brackets(x) for x in data_list]
# test
print data_list2  # ['20', '35', '40', '84', ...]
Ene Uran 638 Posting Virtuoso

I have used this info on Tkinter:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/

A liitle dry with few examples however!

This one has a nice Tkinter section and more examples:
http://bembry.org/technology/python/index.php

Ene Uran 638 Posting Virtuoso

I have a friend who's been encouraging use of Eclipse. Any experience with that out there?

Jeff

I heard that Eclipse is a huge system originally written for Java in Java. It is supposed to be really sluggish.

I have thoroughly tested both DrPython and PyPE for my coding needs, and personally like DrPython better. DrPython has more colors and fonts, is more intuitive than PyPE, and has a much better code assistant.

However PyPE is nice too and has a number of extras like a spell checker, trigger, and macro recorder. One interesting thing is that you send selected code to the Python shell. You can also call a command shell. Both those shells have copy and paste. With large code, the folding class and function option is real nice. As far as I can see PyPE also handles unicode better.

Maybe the two of them could get together and make one super product!

Ene Uran 638 Posting Virtuoso

I find counter4 to be a very interesting function, thanks for putting it up vegaseat.

Ene Uran 638 Posting Virtuoso

I have used SPE for quite a while. No, it's not the "Society of Petroleum Engineers", but "Stani's Python Editor". For some odd reason it has vanished on the net.

Now I am starting to use DrPython, that one seems to be still quite active and just released a new version. Also played with PyScripter, very promissing, but not quite there yet.

Ene Uran 638 Posting Virtuoso

Your initial problem is right here:

def main():
    print "This program sorts student grade information"
    filename = raw_input("Enter the name of the data file: ")
    dfield = raw_input("Enter gpa, name, or credits to sort: ")
    filename = raw_input("Enter a name for the output file: ")
    data = readStudents(filename)
    ...

You are assigning the same variable 'filename' to both the input and output file.

Your next problem is here:

if dfield == gpa:
        data.sort(cmpgpa)

The input function raw_input() returns a string, so this ought to be:

if dfield == 'gpa':
        data.sort(cmpgpa)

Give your data file a name like in.dat, don't use .py (it is not Python code!).
Your next problem is here ( I added a test print):

def makeStudent(infoStr):
    print string.split(infoStr,"\t")  # test --> ['Computewell, Susan 100 400\n']
    name, hours, qpoints = string.split(infoStr,"\t")
    return Student(name, hours, qpoints)

The result of splitting a string is a list, not a tuple! Also the data file needs tabs at the right places to make this work!

Ene Uran 638 Posting Virtuoso

I played wit it for a little while and came up with these obvious shortcuts:

# changed playerInitialList to pL to save on typing
# changed pL1 etc. to pL[1] etc.
# What do you do if initials of the two players match?

import random

def continents(): #<--- Visual Display of the 3 continents
    """
    list pL contains the inital letters of the players
    the index coincides with the number of the country
    """
    print "         __     ____"
    print "   N.A. |  \   /    ."
    print "         \__|  \ 2  |          ____"
    print "  ____________  |" + pL[2] + " /  __  Eu  / |  |"
    print " /   |  1  |  \  \|  /13\ ___/  |  |"
    print "/  0 |__" + pL[1] + "__|_/  |\   ." + pL[13] + "_// 14  /   |"
    print "|  " + pL[0] + " |  3 | 4|__|5\      /  " + pL[14] + "  /    |"
    print " \/ \|__" + pL[3] + "_|_" + pL[4] + "__|_" + pL[5] + "_\ __ |_/|_/| 19 /"
    print " /   |  6  | 7   /  /15\ __/  | " + pL[19] + " /"
    print "     |__" + pL[6] + "__|_" + pL[7] + "_/    ." + pL[15] + "_/ | 16 |  /"
    print "        \ 8  |          /  _" + pL[16] + " | |"
    print "         \ " + pL[8] + " \         /\ / \/\ |"
    print "           \ \        /17|18/  ||"
    print "            _\_      |" + pL[17] …
Ene Uran 638 Posting Virtuoso

Could be your editor/IDE.
Also, a Unicode string literal is preceded with a 'u'.

Ene Uran 638 Posting Virtuoso

I would use the state as the key just in case there could be two capitol cities with the same name:

dic = {'mississippi': 'jackson', 'arizona': 'phoenix', 'iowa': 'desmoines', 
'massachuettes': 'boston', 'michigan': 'lansing', 'virginia': 'richmond', 
'oregon': 'salem', 'hawaii': 'honolulu', 'nebraska': 'lincoln', 
'indiana': 'indianapolis', 'ohio': 'columbus', 'illnois': 'springfield'}

while True:
    state = raw_input("Enter the name of a state (enter quit to exit): ").lower()
    if state == 'quit':
        break
    try:
        print "The capitol city of %s is %s" % (state.capitalize(), dic[state].capitalize())
    except KeyError:
        print "%s is not in the dictionary!" % state.capitalize()
Ene Uran 638 Posting Virtuoso

You most likely get the error because you haven't selected anything on the listbox yet. You need to bind the listbox to the mouseclick that does the selection and to a function that contains your get(index) code. Something like this:

from Tkinter import *

musicfolder = [
  ["CollegeRock/"],
  ['RnB/'],
  ['HipHop/'],
  ['Build/'],
  ['Buy/'],
  ['Techno/'],
  ['Jazz/'],
  ['Classic/']
]

def get_list(event):
    """
    function to read the listbox selection
    and put the result in an entry widget
    """
    # get selected line index
    index = listbox1.curselection()[0]
    # get the line's text
    seltext = listbox1.get(index)
    # delete previous text in enter1
    enter1.delete(0, 50)
    # now display the selected text
    enter1.insert(0, seltext)
    
root = Tk()

# create the listbox (note that size is in characters)
listbox1 = Listbox(root, width=50, height=6)
listbox1.grid(row=0, column=0)

# create a vertical scrollbar to the right of the listbox
yscroll = Scrollbar(command=listbox1.yview, orient=VERTICAL)
yscroll.grid(row=0, column=1, sticky=N+S)
listbox1.configure(yscrollcommand=yscroll.set)

# create data entry
enter1 = Entry(root, width=50, bg='yellow')
enter1.insert(0, 'Click on an item in the listbox')
enter1.grid(row=1, column=0)

# load the listbox with data
for item in musicfolder:
    listbox1.insert(END, item)
 
# left mouse click on a list item to display selection
listbox1.bind('<ButtonRelease-1>', get_list)

root.mainloop()