Ene Uran 638 Posting Virtuoso

Here is a simple linear equation solver:

# a Python linear equation solver

def solve(eq, var='x'):
    eq1 = eq.replace("=", "-(") + ")"
    #print eq1   # test
    c = eval(eq1, {var:1j})
    #print c     # test
    return -c.real/c.imag


eq = "x-2 = 2*x"  # example
r = solve(eq)
print "equation: %s\n  result: x = %s" % (eq, r)
Ene Uran 638 Posting Virtuoso

The request came up on the forum for some typical Python class sample code. Here is my nickles worth:

# manage the contents of a basket
# note: 
#   "self" keeps track of instances, here basket1 and basket2
#   it has to be the first argument of a class method/function

class Basket(object):
    """
    a class to add elements to a list and display the result
    default is an empty basket
    """
    def __init__(self, contents=[]):
        # make a true copy of contents list to avoid surprises
        contents = contents[:]
        self.contents = contents

    def add(self, element):
        # add elements to the basket (list)
        self.contents.append(element)
    
    def remove(self, element):
        # remove an element from the basket
        if element in self.contents:
            self.contents.remove(element)
        else:
            print element, " not in basket!"
            
    def print_me(self):
        # print out the list elements as a string
        result = " ".join(self.contents)
        print "Basket now contains:", result


# basket1 instance of the class, it is an empty basket
basket1 = Basket()
# add items to basket1
basket1.add('pins')
basket1.add('needles')
basket1.add('wurst')

# basket2 instance starts out with contents of basket1
# and allows the user to add more elements
basket2 = Basket(basket1.contents)

basket1.print_me()
print "Add things to the basket, use -thing to remove it:"
while True:
    thing = raw_input("Enter a thing (press Enter only to exit): ")
    if thing:
        if thing[0] == '-':
            basket2.remove(thing[1:])
        else:
            basket2.add(thing)
        basket2.print_me()
    else:
        break
    
# final tally, show things now in basket2
print "Final tally:"
basket2.print_me()
Ene Uran 638 Posting Virtuoso

My humble contribution using a list comprehension:

# create a unique sorted list of all upper case letters in text
text = "This text has Upper and Lower Case Letters"
unique_list = []
[unique_list.append(c) for c in text if c.isupper() and c not in unique_list]
print sorted(unique_list)   # ['C', 'L', 'T', 'U']

Here is the breakdown of vegaseat's one liner as I see it:

text = "This text has Upper and Lower Case Letters"

uppers_raw = re.findall("[A-Z]", text)  # ['T', 'U', 'L', 'C', 'L']
uppers_set = set(uppers_raw)            # set(['C', 'U', 'T', 'L'])
uppers_list = list(uppers_set)          # ['C', 'U', 'T', 'L']
uppers_sorted = sorted(uppers_list)     # ['C', 'L', 'T', 'U']
Ene Uran 638 Posting Virtuoso

Scripting languages:
If you are familiar with C/C++ use Python.
If you are familiar with Java use Jython.
If you are familiar with Csharp use Lsharp (LispSharp).

Ene Uran 638 Posting Virtuoso

Used Reply with Quote, but it came up empty.
Anyway DarkFlash, thanks for the great Python site!

Ene Uran 638 Posting Virtuoso

Alright, I figured out how to do it, did some more research and stumbled on the answer

import ftplib                                          # We import the FTP module
session = ftplib.FTP('myserver.com','login','passord') # Connect to the FTP server
myfile = open('toto.txt','rb')                         # Open the file to send
session.storbinary('STOR toto.txt', myfile)            # Send the file
myfile.close()                                         # Close the file
session.quit()                                         # Close FTP session

hopefully somebody may find this useful. the site i found this at was:
http://sebsauvage.net/python/snyppets/

Hey DarkFkash, greate Python site!!! Thanks!

Ene Uran 638 Posting Virtuoso

Make sure your dictionary values are unique and immutable when you do this:

inverted_dict1 = dict([(v, k) for (k, v) in dict1.iteritems()])
Ene Uran 638 Posting Virtuoso

In MAIN SIZER CONTROL don't add the sizer to a sizer, but the panel:

import wx
 
ID_MENU_EXIT   = 101
ID_MENU_ABOUT  = 102
ID_RADIO_FORWARDS   = 201
ID_RADIO_STATIONARY = 202
ID_RADIO_BACKWARDS  = 203
 
 
class Frame1(wx.Frame): 
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(640, 480))
 
### MENU ###
 
        # Create a menubar at the top of the frame
        MenuBar = wx.MenuBar()
        FileMenu = wx.Menu()
        HelpMenu = wx.Menu() 
        # Add items to the menu                
        FileMenu.Append(ID_MENU_EXIT, "E&xit\tAlt-F4", "Exit the program")
        HelpMenu.Append(ID_MENU_ABOUT, "&About", "About the program")
 
        # Bind the menu event to an event handler        
        self.Bind(wx.EVT_MENU, self.OnMenuExit, id=ID_MENU_EXIT)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, id=ID_MENU_ABOUT)
 
        # Put the menu on the menubar
        MenuBar.Append(FileMenu, "&File")
        MenuBar.Append(HelpMenu, "&Help")
        self.SetMenuBar(MenuBar)
 
### STATUS BAR ###
 
        # create a status bar at the bottom of the frame
        self.CreateStatusBar()
 
 
### TITLE PANEL ###
 
        Title_Panel = wx.Panel(self)
 
        Title_Label = wx.StaticText(Title_Panel, -1, "Sequence Driven Controller")
        Title_Label.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, True))
        Title_Label.SetForegroundColour('#00009F')
 
        Title_Sizer = wx.BoxSizer(wx.VERTICAL)
        Title_Sizer.Add(Title_Label, 0, wx.ALL, 10)
 
        Title_Panel.SetSizer(Title_Sizer)
        Title_Panel.Layout()
 
### DIRECTION PANEL ###
 
        Direction_Panel = wx.Panel(self)
        RadioButtonForwards = wx.RadioButton(Direction_Panel, ID_RADIO_FORWARDS, "Forwards")
        RadioButtonStationary = wx.RadioButton(Direction_Panel, ID_RADIO_STATIONARY, "Stationary")
        RadioButtonBackwards = wx.RadioButton(Direction_Panel, ID_RADIO_BACKWARDS, "Backwards")
        Direction_Sizer = wx.BoxSizer(wx.HORIZONTAL)
        Direction_Sizer.Add(RadioButtonForwards, 0, wx.ALL, 10)
        Direction_Sizer.Add(RadioButtonStationary, 0, wx.ALL, 10)
        Direction_Sizer.Add(RadioButtonBackwards, 0, wx.ALL, 10)
 
        Direction_Panel.SetSizer(Direction_Sizer)
        Direction_Panel.Layout()
 
 
### MAIN SIZER CONTROL ###
        
        Main_Sizer = wx.BoxSizer(wx.VERTICAL)
        #Main_Sizer.Add(Title_Sizer, 0, wx.ALL, 10)  # don't add the sizer but the panel
        Main_Sizer.Add(Title_Panel, 0, wx.ALL, 10)
        #Main_Sizer.Add(Direction_Sizer, 0, wx.ALL, 10)  # don't add the sizer but the panel
        Main_Sizer.Add(Direction_Panel, 0, wx.ALL, 10)
 
        self.SetSizer(Main_Sizer)
        Main_Sizer.Layout()
        
 
### MENU EVENTS ###
 
    def OnMenuExit(self, evt):
        self.Close()
 
    def OnMenuAbout(self, evt):
        dlg = …
Ene Uran 638 Posting Virtuoso

The traceback will also give you the line number your error occured in. It is not in the code segment you posted! Look at it carefully!

You might have used start and not "start".

Ene Uran 638 Posting Virtuoso

Must be your first attempt at ELIZA type AI.
The function friends() is called, but does not exist. What is it supposed to do?

Ene Uran 638 Posting Virtuoso

This is a perfect application for a class! I took the Python snippet at:
http://www.daniweb.com/code/snippet390.html
and modified it slightly for the solvent database application:

# example of a small solvent database using a list of class instances

import operator  # for attrgetter()

class Solvent(object):
    """a structure class for solvents, self refers to the instance"""
    def __init__(self, name=9999, bp=9999, mp=9999, fp=9999):
        self.name = name
        self.bp = bp     # boiling point degC
        self.mp = mp     # melting point degC
        self.fp = fp     # flash point degC


def table(solvent_list):
    """print a table of all solvent attributes"""
    print "-"*50
    print "%-20s  %8s  %8s  %8s" % ("Name", "Bp", "Mp", "Fp")
    for solvent in solvent_list:
        print "%-20s  %8.1f  %8.1f  %8.1f" % (solvent.name, solvent.bp, solvent.mp, solvent.fp)
    print "-"*50
    print "9999 --> not applicable"
    print

def table_bp(solvent_list, bp_limit):
    """print a table of all solvent attributes, with bp restrictions"""
    print "-"*50
    print "%-20s  %8s  %8s  %8s" % ("Name", "Bp", "Mp", "Fp")
    for solvent in solvent_list:
        if solvent.bp > bp_limit:
            print "%-20s  %8.1f  %8.1f  %8.1f" % (solvent.name, solvent.bp, solvent.mp, solvent.fp)
    print "-"*50
    print "9999 --> not applicable"
    print

# make a list of class Solvent instances
# data order = name, boiling point, melting point, flash point
# 9999 --> not applicable
solvent_list = []
solvent_list.append(Solvent("methanol", 65, -98, 11))
solvent_list.append(Solvent("ethanol", 78, -114, 8))
solvent_list.append(Solvent("butanol", 118, -89, 35))
solvent_list.append(Solvent("acetone", 56, -95, -17))
solvent_list.append(Solvent("toluene", 111, -95, 4))
solvent_list.append(Solvent("water", 100, 0, 9999))
# got the drift, add more solvents here ...


print "Show one particular item:"
print solvent_list[1].name         # …
Ene Uran 638 Posting Virtuoso

Thank you! I am still trying to digest the one liners, particularly:

x_reversed = int(str(x)[::-1])

Can anybody break that down for me so I can see the flow?

x = 12345
x_string = str(x)                   # "12345"
x_reversedstring = x_string[::-1]   # "54321"
x_reversed = int(x_reversedstring)  # 54321
Ene Uran 638 Posting Virtuoso

Any program with extension .pyw is considered a windows program, not a console program!

Ene Uran 638 Posting Virtuoso

I tried your suggestionL

for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
        c=+1
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)

but doesn't seem to add the 1 to the end totals

A little error here use c = c + 1 or c += 1 not c = +1

Ene Uran 638 Posting Virtuoso

I simplified the code a little and put in test prints, hopefully that will explain the logic of the loop-around:

# loop around alphabet, offset/rotated by 13

rot = 13
for x in range(ord('a'), ord('z')+1):
    c = chr(x)
    limit = ord('z') - rot    
    # past the limit start with 'a'
    if x <= limit: 
        ascii_val = ord(c) + rot
        print chr(ascii_val),  # test print
    else: 
        ascii_val = ord(c) - rot
        print chr(ascii_val),  # test print

"""
note when the 'z' is reached how it restarts with 'a':
n o p q r s t u v w x y z a b c d e f g h i j k l m
"""
Ene Uran 638 Posting Virtuoso

Import is only for Python files that are written as modules. If you want to execute an external Python program use execfile("myfile.py") or execfile("myfile.pyw") .

In your program the line if denaystart == "denay" or "denay wiles": is wrong.
It should be if denaystart == "denay" or denaystart == "denay wiles": or simpler if "denay" in denaystart:

Ene Uran 638 Posting Virtuoso

Let's return for a moment to the original endeavor on LaMouche's part to learn about dictionaries.

Notice that your encode and decode dictionaries are the same. The order of the keys will be decided internally by the dictionary anyway using a hash algorithm to speed up key searches.

You could create the dictionary with a for loop this way:

def create_rotdic(rot=13):
    encode = {}
    for x in range(ord('a'), ord('z')+1):
        c = chr(x)
        limit = ord('z') - rot
        # past the limit start with 'a' 
        if x <= limit:
            ascii_val = ord(c) + rot
        else:
            ascii_val = ord(c) - rot
        encode[c] = chr(ascii_val)
    return encode
    

encode = create_rotdic()
print encode

That also would allow you to rotate by something other than 13 positions, just to be tricky!

Ghostdog's reminder that there is a builtin encode() method is sweet however:

# uses rot13 encoding
# alphabet is shifted by 13 positions to "nopqrstuvwxyzabcdefghijklm"
# so original 'a' becomes 'n' and so on
text = "i am crazy"
print "original =", text
encoded = text.encode('rot13')
print "encoded  =", encoded
decoded = encoded.encode('rot13')
print "decoded  =", decoded

Not much to do with dictionaries, but you learned something new!

Ghostdog also showed how to create the alphabet string a little simpler:

import string
alphabet = string.ascii_lowercase

# test
print alphabet  # abcdefghijklmnopqrstuvwxyz
Ene Uran 638 Posting Virtuoso

It would have to be if ch[1]==1 and ch[2:5]==[0,0,0]:

Ene Uran 638 Posting Virtuoso

Why do you want to keep two lists, a card has both a rank and a suit, they belong together to make the card. If you just shuffle the rank list, then you lost the connection with the suit list. As I mentioned before, keep your cards in a list of (rank, suit) tuples. That list will by default sort by rank (item 0 of the tuple) and keep the suit along. The same goes for the random.shuffle().

Ene Uran 638 Posting Virtuoso

We just discussed that in one of sneekula's threads:

# exercise in argument passing

def increment(*args):
    """receives tuple *args, change to list to process, then back to tuple"""
    args = list(args)
    index = 0
    for arg in args:
        args[index] += 1
        index += 1
    return tuple(args)
        

def main():
    c = d = e = 0

    # make sure you match arguments
    c, d, e = increment(c, d, e)
    print c, d, e   # 1 1 1

    c, d = increment(c, d)
    print c, d  # 2 2
    
    c, = increment(c)
    print c  # 3 


main()
Ene Uran 638 Posting Virtuoso

A few reasons to use Python classes come to mind, one is to group functions (in a class they are called methods) that belong together. This is sort of what modules do. However, classes have a leg up on modules, they have a way to inherit other classes and establish a tree search structure for attributes in any of these inherited/linked classes. You can go witout classes and OOP, but the ease of reuse of existing code makes a difference as you write larger programs.

So keep OOP in mind, introduce/immerse yourself gradually in this somewhat different world. Do it only if you are familiar with Python programming as a whole. There are some complex issues to tackle and a real beginner simply gets lost!

Ene Uran 638 Posting Virtuoso

Your problem might be one of Networking. There is actually a subforum on DaniWeb called "Linux Web Hosting and Apache"
see: http://www.daniweb.com/techtalkforums/forum33.html

Ene Uran 638 Posting Virtuoso

With __cmp__() you can override, overload, customize (whatever you want to call it) the cmp() function for the class instance. There are a bunch of these babies, all starting and ending with double underlines. I think they are also called instance methods. They can do powerful things, but also can make your code a bitch to read and comprehent.

Here is one that hijacks the iterator used by a for loop:

# operator overloading with instance method __iter__()

class Reverse(object):
    """custom iterator for looping over a sequence backwards
    sort of hijacks the iterator used by the for loop
    uses __iter__(self) and next(self) to do the trick"""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

for c in Reverse('iterator overload'):
    print c,  # d a o l r e v o   r o t a r e t i

Note that Reverse('iterator overload') is really a class instance!

Ene Uran 638 Posting Virtuoso

Function sleep(seconds) from module time is pretty much the best. Remember seconds is a float so you can delay 0.5 seconds.

import time

print "Hello ..."
time.sleep(2.5)  # wait 2.5 seconds
print "... there!"
Ene Uran 638 Posting Virtuoso

Do all of us a favor and uses spaces for indentation!! The reason, different text editors have set different number of spaces for the tabs!!

Looks like the line that starts with global does not line up with the next line starting with print!

A Python statement block expects consistent spacing! I prefer 4 spaces. Use an editor made for Python coding and set the indentation option to "spaces only", also translate tabs to 4 spaces.

Also, please use code tags around your code, it will preserve the indents.
I will show the needed tags in reverse so they don't activate
at the end of your code add this tag [/code]
at the start of your code add tag [code]

Ene Uran 638 Posting Virtuoso

I think we solved some of this in:
http://www.daniweb.com/techtalkforums/post266586-2.html

To sort two lists in parallel you can zip them to a list of tuples, sort that and convert back to two lists again.

Ene Uran 638 Posting Virtuoso

Here are two Python code smaples using the Tkinter GUI. Each example has a hint how to do the dart game:

from Tkinter import *

root = Tk()
root.title("Archery Target")

canvas = Canvas(root, width=600, height=600)
canvas.pack()

# draw five circles, largest one first, circles draw within a 
# square with given upper left corner and lower right corner coordinates
canvas.create_oval(50,50,550,550,fill='white',outline='white')
canvas.create_oval(100,100,500,500,fill='black',outline='black')
canvas.create_oval(150,150,450,450,fill='blue',outline='blue')
canvas.create_oval(200,200,400,400,fill='red',outline='red')
canvas.create_oval(250,250,350,350,fill='yellow',outline='yellow')

root.mainloop()

This tells you if the mouse has been clicked on target:

from Tkinter import *
import random

def create_rect():
    chance = random.sample(range(1, 250), 4)
    print chance  # test  eg. [72, 206, 116, 166]
    canvas.create_rectangle(chance, fill="red")

def check_rect(event):
    rect = canvas.find_overlapping(event.x, event.y, event.x, event.y)
    if rect:
        # delete old rectangle
        canvas.delete(rect)
        # create new rectangle
        create_rect()

root = Tk()
root.title("click on red")

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

# create the starting random rectangle
create_rect()

# respond to left mouse button click
canvas.bind("<Button-1>", check_rect)

root.mainloop()
Ene Uran 638 Posting Virtuoso

You can do the whole thing easily with the Python program given at:
http://www.daniweb.com/code/snippet499.html

You only need to adjust the last line of the code for your needs. Read the comments carefully!

Ene Uran 638 Posting Virtuoso

If you are popping the cards off your deck/pack list, the len() should give the number of cards left. Here is an example:

import random

class Cards(object):
    def __init__(self):
        """creates a deck/pack of cards and shuffles it"""
        suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
        numbers = ["Ace"] + range(2, 11) + ["Jack", "Queen", "King"]
        self.pack = ["%s of %s" % (n, s) for n in numbers for s in suits]
        #print self.pack  # test
        random.shuffle(self.pack)
      
    def deal(self, number_of_cards):
        """
        dealer takes (pops) number_of_cards off the top of the shuffeled deck
        the list of shuffeled cards will eventually run out!
        """
        cardList = [self.pack.pop() for i in range(number_of_cards)]
        #print "Your hand: %s" % cardList
        cards_left = len(self.pack)
        # deck/pack has been dealt reshuffle it
        if cards_left <= 5:
            print "reshuffled!"
            # create and shuffle a new deck
            self.__init__()
        for card in cardList:
            print card

   
newgame = Cards()
deal = "y"
while deal == "y":
    print "-"*30
    newgame.deal(5)
    print "-"*30
    deal = raw_input("Deal again? (y/n) ").lower()
Ene Uran 638 Posting Virtuoso

Here is one way to do it, using slicing, a for loop and indexing with enumerate():

# let's say you read your file in as a string ...
str1 = """
2 h
3 s
6 d
Ace s
"""

list1 = str1.split()

print list1  # ['2', 'h', '3', 's', '6', 'd', 'Ace', 's']

suit_list = list1[1::2]
rank_list = list1[0::2]

print suit_list  # ['h', 's', 'd', 's']
print rank_list  # ['2', '3', '6', 'Ace']

# replace h with Hearts etc.
for index, suit in enumerate(suit_list):
    if suit == 'h':
        suit_list[index] = "Hearts"
    elif suit == 'c':
        suit_list[index] = "Clubs"
    elif suit == 's':
        suit_list[index] = "Spades"
    elif suit == 'd':
        suit_list[index] = "Diamonds"

print suit_list  # ['Hearts', 'Spades', 'Diamonds', 'Spades']

Please use code tags on your code to preserve the all so important indentation!!!!!!!!!!!

Ene Uran 638 Posting Virtuoso

This tiny code snippet will separate your list and make the alpha list unique. I also added the typical list sort:

raw_list = [1, 'a', 2, 'a', 3, 'v', 4, 't', 5, 'v', 9, 'c']

alpha_list = []
number_list = []
for c in raw_list:
    # make the alpha_list unique
    if alpha_list.count(c) < 1 and str(c).isalpha():
        alpha_list.append(c)
    elif str(c).isdigit():
        number_list.append(c)

# sort list in place
alpha_list.sort()

print alpha_list   # ['a', 'c', 't', 'v']
print number_list  # [1, 2, 3, 4, 5, 9]

Added php tags to make Python code color highlighted.

Ene Uran 638 Posting Virtuoso

Well, a quiz program asking a question and giving multiple choice answers is always entertaining and can be fun, depending on the questions and answers. I think vegaseat suggested something like that in the "Projects for the Beginner" thread. Read through the zip file he attached and you will chuckle!
Located at: http://www.daniweb.com/techtalkforums/post161212-13.html

The text based "monster" RPG you started already is another good project. It will tax your logic skills.

Ene Uran 638 Posting Virtuoso

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\ATI Technologies\ATI Control Panel;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Common Files\Adobe\AGL;H:\Python24

or whatever version of Python you have.

Normally you don't have to do this kind of thing, when you install Python properly with the downloaded MSI installer file.

Ene Uran 638 Posting Virtuoso

A first quick look revealed a number of things. Give attention to my comments marked with "!!!!". Here is code that should work, so you can improve on it:

# this is supposed to be simple
# I am trying to simulate combat
# As easy as I can
# "Untitled"
# By Franki
# You find the crystals to destroy the Solomon Terminal

import random   # needed for random.randrange(2) or other random thingies

crystals = 0

"""
# declare global variables inside functions only!!!!
global gotCrystal_1
global gotCrystal_2
global gotCrystal_3
global gotCrystal_4
global gotGold_1
global gotGold_2
global gotGold_3
global gotGold_4
"""

# use False, later set to True, is more readable
gotCrystal_area1 = False
gotCrystal_area2 = False
gotCrystal_area3 = False
gotCrystal_area4 = False

gotGold_area1 = False
gotGold_area2 = False
gotGold_area3 = False
gotgold_area4 = False

gold = 0

# I am using Classes to make monsters (I don't know why)
# so you can later refer to as bad_warrior.level, should be 3
# or bad_hunter.name which is 'Cavernian Hunter'
# you can also define some action within the class
class Monster(object): 
    """Monster"""
    def __init__(self,name,level):
        self.name = name
        self.level = level

# The Monsters
bad_hunter = Monster("Cavernian Hunter","1")
bad_scout = Monster("Cavernian Scout","2")
bad_warrior = Monster("Cavernian Warrior","3")
bad_commander = Monster("Cavernian Troop Commander","4")

def place_monster():
    # the integer 1 places Monster, all others place nothing
    Monster_in = random.randrange(2)    # replaced MOnster_in with Monster_in spelling!!!!!
    if Monster_in == (0 or 2):
        return 0
    Monster = random.randrange(4)
    if Monster == 0:
        Monster = …
Ene Uran 638 Posting Virtuoso

Thanks Jeff, learned something new!

Ene Uran 638 Posting Virtuoso

Read on another forum:

With Python you learn how to drive the car, with C++ you learn how to build the car.

Ene Uran 638 Posting Virtuoso

Use:

os.path.exists(filename)  # returns True or False

I you don't want to truncate an existing file with 'w' or 'w+' use the 'a' option for append.

Ene Uran 638 Posting Virtuoso

You may want to change the 12 to more spaces, or the scores gets pushed to the right, still readable, just not as pretty.

Here is an another example of formatting:

def format_dollar(amount):
    """formats amount to dollars and cents"""
    return "$%.2f" % amount

print format_dollar(123.9 * 0.07)  # $8.67
Ene Uran 638 Posting Virtuoso

As far as I know only wxPython has a password option, the Tkinter Entry widget does not. An easy way to get around this, is to give the password entry widget a bg="yellow" and fg="white". This will be very hard to see for a bystander, as you type in the password, after the return key has been pressed clear the contents. If you want to be tricky, rather then clear, put in a silly password.

If you don't want to show your password in your code see:
http://www.daniweb.com/techtalkforums/post220840-56.html

Ene Uran 638 Posting Virtuoso

Printing with a format string comes in handy with tables. Let's say you have a list of player scores:

player_scores = [
["Freddy", 9234],
["Grace", 8723],
["Nutty Fuddy", 7143],
["Lurcher", 9545]]

for ps in player_scores:
    player = ps[0]
    score = ps[1]
    print player, score

"""
somewhat ugly:
Freddy 9234
Grace 8723
Nutty Fuddy 7143
Lurcher 9545    
"""

print "-"*50

for ps in player_scores:
    player = ps[0]
    score = ps[1]
    print "%-12s %d" % (player, score)

"""
much nicer table:
Freddy       9234
Grace        8723
Nutty Fuddy  7143
Lurcher      9545    
"""
Ene Uran 638 Posting Virtuoso

There is a a Hardware section under DaniWeb TechTalk, that's were the experts are for this project of yours!

Ene Uran 638 Posting Virtuoso

Unless there is something like a ubeep(), you are out of luck.

Ene Uran 638 Posting Virtuoso

Each time you move s, n, e, or west heal the monster(s) a little. That would be in your while loop's if command == 's' etc.

Ene Uran 638 Posting Virtuoso

This from the Win32 Programmer's Reference:

The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.

COLORREF GetPixel(

HDC hdc, // handle of device context
int XPos, // x-coordinate of pixel
int nYPos // y-coordinate of pixel
);


Parameters

hdc

Identifies the device context.

nXPos

Specifies the logical x-coordinate of the pixel to be examined.

nYPos

Specifies the logical y-coordinate of the pixel to be examined.

Return Values

If the function succeeds, the return value is an RGB value. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.

Remarks

The pixel must be within the boundaries of the current clipping region.
Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function.

A related function SetPixel() is used in one of the C code snippets about plotting. Vegaseat is probably right, for low level things like direct screen access C or C++ is best.

Ene Uran 638 Posting Virtuoso

If you have a Windows machine you can change the frequency and duration:

// simple sounds via Beep(frequency_hrz, duration_ms)
// on the PC internal speaker, a Windows Console program

#include <stdio.h>
#include <windows.h>   // WinApi header file

int main()
{
  puts("using winAPI Beep(frequency_hrz, duration_ms)...");
  Beep(523,500);  // 523 hertz (C5) for 500 milliseconds
  Beep(587,500);
  Beep(659,500);
  Beep(698,500);
  Beep(784,500);
  Sleep(500);    // 500 ms delay
  puts("\n\\a makes a beep on the internal speaker too ...");
  Sleep(500);
  puts("\a");
  Sleep(500);
  puts("\a");
  
  getchar(); // key wait
  return 0;
}
Ene Uran 638 Posting Virtuoso

@ slake

Why stick to Borland ???
If you are thinking about compiler migration better go for the free Visual Studio 2005 free edition or for GCC mingw compiler which nowadays most of the people use.

Why stick to Borland ??? Right on ~s.o.s~! Borland is a sinking ship!

The Visual Studio 2005 free edition is huge! Kind of takes over your computer. I would go for GCC which is part of the free Dev-C++ IDE.

Ene Uran 638 Posting Virtuoso

If you use C++, load a string vector and use the vector's sort. Then you don't have to give a rat-poop about the sorting algorithm, it will be the best! A somewhat modern example:

// load a string vector with words from a whitespace 
// separated text file and sort the words

/* typical sample file:
with
an
equal
mix
of
biosolids
to
make
the
compost
*/

#include <string>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() 
{
  vector<string> sV;
  ifstream in("compost.txt");
  string word;
  
  // separates words in file at a whitespace
  // and loads a string vector
  while(in >> word)
    sV.push_back(word);
     
  cout << "Unsorted words:" << endl;
  for(int i = 0; i < sV.size(); i++)
    cout << sV[i] << endl;
  
  cout << "---------------" << endl;
    
  cout << "Sorted words:" << endl;
  sort( sV.begin(), sV.end() );
  for(int i = 0; i < sV.size(); i++)
    cout << sV[i] << endl;  
  
  cin.get();
  return 0;
}
Ene Uran 638 Posting Virtuoso

To me VBasic is almost unreadable! Does it still produce a zillion different files for every small program you write?

I keep hearing that MS is dropping any further development with VB.

Ene Uran 638 Posting Virtuoso

I have to applaud your teacher for teaching Python rather than the usual "ugly syntax stuff" like C, C++ or Java. Colleges with their all too often ultra conservative teachers are just warming up to Python. So you and your teacher are way ahead!

I will be playing around with your code to get a feel, then let you know what I think.

Here is a quote from Donald Knuth who has written many books on computer science:

Donald E. Knuth, December 1974 -->
"We will perhaps eventually be writing only small
modules which are identified by name as they are
used to build larger ones, so that devices like
indentation, rather than delimiters, might become
feasible for expressing local structure in the
source language."

Ene Uran 638 Posting Virtuoso

Works nicely, welcome to GUI programmig! You seemed to have learned quite a bit!

Now, you can do a few cosmetic improvements, like making all the buttons the same sice and introducing some color.

Just a matter of taste, but I would have lined up all the buttons on top of each other for now. Later, as you add more links, use grid() to locate/group them in an order.

Great job!