bumsfeld 413 Nearly a Posting Virtuoso

Here are some corrections:

// blah blah blah code

    cout << "Please enter initial balance: ";
    cin >> acctbalance;
    // add the do for the while!!!
    do
    {
        cout << "What do you wish to do?" << endl;
        cout << "D Deposit Money" << endl;
        cout << "W Withdraw Money" << endl;
        cout << "B Display Balance" << endl;
        cout << "Q Quit" << endl;
        cin >> choices;
        
        switch (choices)
        {
            case 'D':
            case 'd':
            {
                cout << "Enter amount to be deposited: "<< endl;
                //cout << deposit;  // wrong
                cin >> deposit;     // add this!!!

// blah blah blah

            case 'W':
            case 'w':
            {
                cout << "Please enter amount to withdraw " << endl;
                cout << "Value must be multiple of 20" << endl;
                cin >> withdraw;     // add this!!!

// blah blah blah

            case 'Q':
            case 'q':
            {
                cout << "Thank for using our services have a nice day!" << endl;
                break;
            }
        }
    } while (choices != 'q' && choices != 'Q');  // change ! =  to  !=

// blah blah blah
bumsfeld 413 Nearly a Posting Virtuoso

Sorting your facevalues won't work, you are sorting strings that when sorted will in no way represent the proper sequence for a straight!

You can give them integer values from 2 to 13, and notice that the ace will be a 1 or a 13 in a straight.

bumsfeld 413 Nearly a Posting Virtuoso

Maybe it's something like this:

// simple to do with copy and paste

#include <iostream>

using namespace std;

void hour_glass()
{
    cout << "*******" << endl;
    cout << " ***** " << endl;
    cout << "  ***  " << endl;
    cout << "   *   " << endl;
    cout << "  ***  " << endl;
    cout << " ***** " << endl;
    cout << "*******" << endl;   
}

int main()
{
    hour_glass();
    cin.get();
    return EXIT_SUCCESS;
}

However, that would be too simple. I am sure your teacher expects you to complicate the code a little with for loop and some if statements to place the stars correctly.

bumsfeld 413 Nearly a Posting Virtuoso

Looks like whatever is item in hand is not an integer. I also fail to see how hand can be 1, 2, 3 , 4, ... all at the same time?

bumsfeld 413 Nearly a Posting Virtuoso

Thank you, makes sense! Had one of those days with a mental block!

bumsfeld 413 Nearly a Posting Virtuoso

Looks like you have somewhat incomplete code:

#include<stdio.h>

float x[4] = {1.2,2.4,3.6,4.8};
float f[4] = {0.1,0.2,0.3,0.4};
float xave = 0.0;
float ftotal = 0.0;

int main()
{
  int i;
  float weights[4] = {0};
  char buf[80];
  for(i = 0; i < 4; ++i)
  {
    printf("Enter weight #%d", i+1);
    fgets(buf,sizeof(buf),stdin);
    weights[i] = atof(buf);
  }
  
  //???????????? missing something here!!!
  {
    int i;
    for (i=0; 1<4;i++) ftotal + = f[i];
    if(ftotal!=1.0)
    {
      printf("error\n");
      exit();
    }
    for(i=0;1<4;i++) xave+=f *x;
    printf("\nThe weights are %f"&f);
    printf("\nThe average is %f\n",xave);



  // blahblah...
  return 0;
}

There are quite a number of obvious errors too!

bumsfeld 413 Nearly a Posting Virtuoso

I wrote this little code to test a 2 dimensional array. Given the array array[row][col] I can find total_columns, but I am at loss to figure out total_rows.

// 2 D array

#include <iostream>

using namespace std;

int main()
{
  int row, col, total_columns;
  
  // two dimensional array in the form array[row][col]
  int  iarray2[3][5] = { 1, 2, 3, 4, 5,          
                         6, 7, 8, 9,10,
                        11,12,13,14,15 };

  total_columns = sizeof(iarray2[0])/sizeof(int);  // result = 5
  //total_rows = ??;
    
  for(row = 0; row < 3 ; row++)
  {
    for(col = 0; col < total_columns; col++)
    {
      cout  << row << "  " << col << "  " << iarray2[row][col] << endl; 
    }
    cout << endl;
  }
  
  // wait
  cin.get();
  return EXIT_SUCCESS;
}
bumsfeld 413 Nearly a Posting Virtuoso

I read in the news that Python in going from version 2.4 to version 2.5 fixed 450 bugs. That seems to be lots of bugs! I used Python a lot and never found a single one of those bugs. What is your experience?

bumsfeld 413 Nearly a Posting Virtuoso

Got to hurry! The waitress at the internet bistro wants to serve my meal.
Here is some more code, hope that satisfies your needs:

# this would be rawfile.txt
str1 = """
NAME:XXXXXXXXXXXX
SURNAME:XXXXXXXXXXXX
DATE:23.09.2006
A B C D E F G H (column names)
40 250 300 01.01.2006 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2006 11:22:43 450 CAPITALBANK
.
.
.
.
PAGE 1

40 150 240 01.11.2006 17:41:21 50 12346678 XBANK
31 123 455 02.02.2006 11:22:43 654474151 YBANK
.
.
PAGE 2

40 250 240 01.11.2006 17:41:21 50 12346678
.
PAGE 3

.
.
PAGE 4

.
.
NOTES:XXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXX
"""

# convert to ...
"""
A B C D E F G H
40 250 300 01.01.2005 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2005 11:22:43 450 tab CAPITALBANK
40 150 240 01.11.2005 17:41:21 50 12346678 CITYBANK
31 123 455 02.02.2005 11:22:43 tab 654474151 CITYBANK
"""
# save as resultfile.txt

# create raw_file.txt from str1 for testing
fout = open("raw_file.txt", "w")
fout.write(str1)
fout.close()

# read in raw_file.txt as list of lines/strings
fin = open("raw_file.txt", "r")
line_list1 = fin.readlines()
fin.close()

#print line_list1  # test

def sub_missing(line):
    """take string line and sub for certain missing items"""
    # convert string to list
    list1 = line.split()
    # if list1[1] (column A1) starts with 2 prefix with 555
    if list1[1].startswith('2'):
        list1[1] = "555" + list1[1]
    # dito for column A2
    if list1[2].startswith('2'):
        list1[2] = "555" + list1[2]
    # if list1[1] (column A1) starts with 4 prefix with 666 …
bumsfeld 413 Nearly a Posting Virtuoso

Simply replace this part of present code:

# process the list of lines
# give the new list proper header
#line_list2 = ["A B C D E F G H\n"]
str3 = "ID A1 A2 Date Time Sec.SID Bank\n"
str3.replace(" ", "\t")
#print str3  # test
line_list2 = [str3] 
for line in line_list1:
    lead_char = line[0]
    # use only line starting with a number
    if lead_char.isdigit():
        # replace space with tab
        line.replace(" ", "\t")
        #print line  # test
        line_list2.append(line)

The thing with xxx, yyy, zzz and default values you have to explain better. For instance, is xxx contained in rawfile.txt and you want it replaced with 111111? You could do that with additional line.replace(what, with) statements.

bumsfeld 413 Nearly a Posting Virtuoso

Aha, now I see it! All you need to do is reference daclick1() properly! Forget the inherited solution.

#!/usr/bin/python


import wx
import time


class MakePanel1(wx.Panel):
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)
        
        self.dalabel = wx.StaticText(self, -1, "   panel 1 label   ")
        self.dabutton1 = wx.Button(self, label="button 1") 
        self.dabutton1.Bind(wx.EVT_BUTTON, self.daclick1 )
        self.bs1 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs1.Add(self.dabutton1,0)
        self.bs1.Add(self.dalabel,0)
        self.SetSizer(self.bs1)
        
    def daclick1(self, event):
        self.dalabel.SetLabel(str(time.time()))


class MakePanel2(wx.Panel):
    """Note that MakePanel2 inherits MakePanel1"""
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)

        self.dabutton2 = wx.Button(self, label="button 2") 
        self.dabutton2.Bind(wx.EVT_BUTTON, self.daclick2 )
        self.bs2 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs2.Add(self.dabutton2,0,wx.ALL,20)
        self.SetSizer(self.bs2)

    def daclick2(self, event):
        # reference daclick1() properly!!!!!!! 
        daframe.Panel1.daclick1(self)

class DisFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.Panel1 = MakePanel1(self)
        self.Panel2 = MakePanel2(self)

        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.Panel1,1,wx.EXPAND);
        bs.Add(self.Panel2,1,wx.EXPAND);

        self.SetSizer(bs)
        self.Fit()


if __name__ == '__main__':
    app = wx.App()
    daframe = DisFrame(None)
    daframe.Show()
    app.MainLoop()

Sorry, was sitting in my favorite internet bistro and got distracted by friends!

bumsfeld 413 Nearly a Posting Virtuoso

Make sure you test this out thoroughly! There are few things that might need to be changed.

bumsfeld 413 Nearly a Posting Virtuoso

If the lines you want start with number, other than header, here is easy solution:

# this would be rawfile.txt
str1 = """
NAME:XXXXXXXXXXXX
SURNAME:XXXXXXXXXXXX
DATE:23.09.2006
A B C D E F G H (column names)
40 250 300 01.01.2006 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2006 11:22:43 450 CAPITALBANK
.
.
.
.
PAGE 1

40 150 240 01.11.2006 17:41:21 50 12346678 XBANK
31 123 455 02.02.2006 11:22:43 654474151 YBANK
.
.
.
.
PAGE 2

.
.
PAGE 3

.
.
PAGE 4

.
.
NOTES:XXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXX
"""

# convert to something like this ...
"""
A B C D E F G H
40 250 300 01.01.2005 13:43:21 250 12345678 KENTBANK
31 123 455 02.02.2005 11:22:43 450 tab CAPITALBANK
40 150 240 01.11.2005 17:41:21 50 12346678 CITYBANK
31 123 455 02.02.2005 11:22:43 tab 654474151 CITYBANK
"""
# save as resultfile.txt

# create raw_file.txt from str1 for testing
fout = open("raw_file.txt", "w")
fout.write(str1)
fout.close()

# read in raw_file.txt as list of lines/strings
fin = open("raw_file.txt", "r")
line_list1 = fin.readlines()
fin.close()

#print line_list1  # test

# process the list of lines
# give the new list proper header
line_list2 = ["A B C D E F G H\n"]
for line in line_list1:
    lead_char = line[0]
    # use only line starting with a number
    if lead_char.isdigit():
        print line  # test
        line_list2.append(line)

#print line_list2  # test

# convert processed list to string
str2 = ''.join(line_list2)

print str2  # test

# write the string to file
fout = open("result_file.txt", "w")
fout.write(str2)
fout.close()
bumsfeld 413 Nearly a Posting Virtuoso

One solution to fix problem is to have MakePanel2 inherit MakePanel1, then you only need to create instance of MakePanel1 in MakePanel2. For some odd reason wx.BoxSizer() gets confused with the label location. Look the code over.

#!/usr/bin/python


import wx
import time


class MakePanel1(wx.Panel):
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)
        
        self.dalabel = wx.StaticText(self, -1, "   panel 1 label   ")
        self.dabutton1 = wx.Button(self, label="button 1") 
        self.dabutton1.Bind(wx.EVT_BUTTON, self.daclick1 )
        self.bs1 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs1.Add(self.dabutton1,0)
        self.bs1.Add(self.dalabel,0)
        self.SetSizer(self.bs1)
        
    def daclick1(self, event):
        self.dalabel.SetLabel(str(time.time()))


class MakePanel2(MakePanel1):
    """Note that MakePanel2 inherits MakePanel1"""
    def __init__(self, Parent, *args, **kwargs):
        wx.Panel.__init__(self, Parent, *args, **kwargs)

        self.dabutton2 = wx.Button(self, label="button 2") 
        self.dabutton2.Bind(wx.EVT_BUTTON, self.daclick2 )
        self.bs2 = wx.BoxSizer(wx.HORIZONTAL)
        self.bs2.Add(self.dabutton2,0,wx.ALL,20)
        self.SetSizer(self.bs2)

    def daclick2(self, event):
        #MakePanel1.daclick1()  # gives error, need to make instance first
        self.Panel1 = MakePanel1(self)
        self.Panel1.daclick1(self)

class DisFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.Panel1 = MakePanel1(self)
        self.Panel2 = MakePanel2(self)

        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.Panel1,1,wx.EXPAND);
        bs.Add(self.Panel2,1,wx.EXPAND);

        self.SetSizer(bs)
        self.Fit()


if __name__ == '__main__':
    app = wx.App()
    daframe = DisFrame(None)
    daframe.Show()
    app.MainLoop()
bumsfeld 413 Nearly a Posting Virtuoso

I would split user and computer creation of random numbers up like this:

import random

def computer_random():
    """let computer create a list of 6 unique random integers from 1 to 50"""
    ci = random.sample(range(1,50), 6)
    return ci
    
def user_random():
    """let user create a list of 6 unique random integers from 1 to 50"""
    print "Enter 6 random integers from 1 to 50:"
    ui = []
    while len(ui) < 6:
        print len(ui) + 1,
        i = input("--> ")
        # check if i is unique and has a value from 1 to 50
        # otherwise don't append, could also assure that i is an integer
        if (i not in ui) and (1 <= i <= 50):
            ui.append(i)
    return ui

comp_list = computer_random()  # assign the returned list to variable comp_list
print comp_list  # test it

user_list = user_random()
print user_list  # test it

Function comp_random() will be called numerous times, each time you need to compare comp_list with user_list. Now you have to work on list compare function to find the matches, then count how many times 3 to 6matches have occured.

bumsfeld 413 Nearly a Posting Virtuoso

Just for learning purposes:

# one alternative to random.sample(range(0,50), 6)

import random

print "show 6 random unique integers from 1 to 50:"
numbers=[]
while len(numbers) < 6:
    ri = random.randint(1,50)
    if ri not in numbers:
        numbers.append(ri)

print numbers
bumsfeld 413 Nearly a Posting Virtuoso

Another simple Python project:
Write head/tail coin toss program. Test it with about 1000 tosses and see if head or tail prevail.

bumsfeld 413 Nearly a Posting Virtuoso

My effort to create some simpler Python projects:
Take sentence (text string) and replace all the lower case vowels with upper case vowels.

bumsfeld 413 Nearly a Posting Virtuoso

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

How can you display this text with just a one line statement?

Hint: Think about this!

bumsfeld 413 Nearly a Posting Virtuoso

Wonder why you did that:

noun1 = noun
verb1 = verb
adjective1 = adjective
moan = sound_disgust

You had perfectly good variable names already.

bumsfeld 413 Nearly a Posting Virtuoso

A while ago our friend "a1eio" suggested the Python tutorial at http://bembry.org/technology/python/index.php

I liked that one! Very good for Python starters!

bumsfeld 413 Nearly a Posting Virtuoso

There are modules like numpy, that do high speed array and matrix manipulations. Google for numpy, its free.

bumsfeld 413 Nearly a Posting Virtuoso

Nice little song! This is how you make things wait for a few seconds:

# by Christopher O'Leary
# The death of Charlie!

import time

def print_charlieVerse():
    print "Charlie was a pidgeon, a pidgeon, a pidgeon."
    print "Charlie was a pidgeon, a pidgeon that flew."
    print "He flew in the morning, he flew in the night."
    print "And when he came home he was covered in ..."   # covered in what?
    print
 
n = 0
while n < 10:
    print_charlieVerse()
    n = n + 1
    time.sleep(5)  # sleep/wait 5 seconds
    
print "This song is annoying, annoying, annoying."
time.sleep(2)
print "This song is annoying, that much is true."
time.sleep(2)
print "It pisses me off, how about you?"
time.sleep(2)
print "If one more verse happens he will not sur ..."    # survive?
time.sleep(4)
print "CHARLIE WAS A PIDGEON, A PIDGEON, A PIDGEON!"
time.sleep(4)
print "CHARLIE WAS A PIDGEON, A PIDGEON I SHOT!"
bumsfeld 413 Nearly a Posting Virtuoso

The short Tkinter GUI code wll draw one yellow circle on the canvas:

from Tkinter import *

root = Tk()
root.title("Tkinter Circle")

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

# yellow circle is drawn within square with corner 
# coordinates x1=50, y1=50 and x2=350, y2=350
canvas.create_oval(50,50,350,350,fill='yellow')

root.mainloop()

Your challenge will be to draw one archery target consisting of 5 concentric circles going from yellow center to red, blue, black, white.

As added challenge draw the 64 square chess board using the GUI of your choice. I like wxPython, but Tkinter will do.

bumsfeld 413 Nearly a Posting Virtuoso

Write wxPython image viewer. Most of the information needed is already in the Python snippets here at Daniweb.

First create list of all image files (like .jpg, .png) in given folder. Go through the list with a next and previous button to display the selected images.

Much of the image info is in http://www.daniweb.com/code/snippet337.html

bumsfeld 413 Nearly a Posting Virtuoso

There are situations where you want to add s to string to indicate plural. Here is example:

print "<%s>" % ('s' * 0)  # <>
print "<%s>" % ('s' * 1)  # <s>
print 1 != 1              # False --> 0
print 2 != 1              # True --> 1

# add an 's' to indicate plural when k is not 1
for k in range(1, 4):
    print "The for loop ran %d time%s" % (k, 's'*(k != 1))

"""
The for loop ran 1 time
The for loop ran 2 times
The for loop ran 3 times
"""
bumsfeld 413 Nearly a Posting Virtuoso

Richard Gruet has very good quick-reference of Python on his home page:
http://rgruet.free.fr/

The reference can be downloaded as HTML, zipped HTML or PDF file. It is in English.

bumsfeld 413 Nearly a Posting Virtuoso

Yes, wrap your Python code into these code tags to have it show up correctly indented on DaniWeb. I started Python about one year ago, but have used C/C++ much longer.

Please bring up any of your code question here on the forum, so others can help and learn too!

bumsfeld 413 Nearly a Posting Virtuoso

Usually memory is saved by keeping data in files. In your case, you would have to keep data in memory using module StringIO. That is swimming upstream.

You could compress your datafile with methods in module zipfile or better tarfile. That will speed up loading time.

bumsfeld 413 Nearly a Posting Virtuoso

Check
remove_tree( directory[verbose=0, dry_run=0])
in module
distutils.dir_util

bumsfeld 413 Nearly a Posting Virtuoso

This code allows you to create unique file names containing date and time that can be sorted by age:

import time

# using year_month_day_hour_min_sec  (24 hour foemat)
filename1 = time.strftime('%Y_%m_%d_%H_%M_%S.dat')
print filename1  # eg.   2006_08_05_20_57_56.dat

# or using seconds since epoch
filename2 = str(int(time.time())) + ".dat"
print filename2  # eg.  1154825876.dat
bumsfeld 413 Nearly a Posting Virtuoso

A more foolproof way would be to loop each data entry like this:

# let's say your attacking army can be from 1 tp 100

# keeps looping until entry is acceptable
aArmy = 0
while aArmy < 1 or aArmy > 100:
    try:
        aArmy = input("Enter the size of the attacking army (1 to 100): ")
    except NameError:  # a letter is entered
        aArmy = 0
print aArmy
bumsfeld 413 Nearly a Posting Virtuoso

Looks like first thing you need to add is menu loop to add, edit, search data, also exit program should be in loop.

Took the liberty to put your code into code tags, added some remarks:

import shelve
import string

UNKNOWN = 0
HOME = 1
WORK = 2
FAX = 3
CELL = 4

class Phoneentry:  # by convention class names start with capital letter
    def __init__(self, name='Unknown', number='Unknown', type=UNKNOWN):
        self.name = name
        self.number = number
        self.type = type

    #  create string representation
    def __repr__(self):
        return('%s:%d' % ( self.name, self.type ))

    # "fuzzy" compare of two items
    def __cmp__(self, that):
        this = string.lower(str(self))
        that = string.lower(that)
        if string.find(this, that) >= 0:
            return(0)
        return(cmp(this, that))

    def showtype(self):
        if self.type == UNKNOWN: return('Unknown')
        if self.type == HOME: return('Home')
        if self.type == WORK: return('Work')
        if self.type == FAX: return('Fax')
        if self.type == CELL: return('Cellular')

class Phonedb:
    def __init__(self, dbname = 'phonedata.slv'):  # added ext .slv
        self.dbname = dbname;
        self.shelve = shelve.open(self.dbname);

    def __del__(self):
        self.shelve.close()
        self.shelve = None

    def add(self, name, number, type = HOME):
        e = Phoneentry(name, number, type)
        self.shelve[str(e)] = e

    def lookup(self, string):
        list = []
        for key in self.shelve.keys():
            e = self.shelve[key]
            if cmp(e, string) == 0:
                list.append(e)
        return(list)
        
#  if not being loaded as a module, run a small test
if __name__ == '__main__':
    foo = Phonedb()
    foo.add('Sean Reifschneider', '970-555-1111', HOME)
    foo.add('Sean Reifschneider', '970-555-2222', CELL)
    foo.add('Evelyn Mitchell', '970-555-1111', HOME)

    print 'First lookup:'
    for entry in foo.lookup('reifsch'):
        print '%-40s %s (%s)' % ( entry.name, entry.number, entry.showtype() ) …
bumsfeld 413 Nearly a Posting Virtuoso

Which version of wxPython did you install?

Here is site that seems to have many difficult install questions/answers for wxPython:
http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi/11

bumsfeld 413 Nearly a Posting Virtuoso

For image files I would stick with binary file operation, it can handle text too. Here is example:

# typical image header
str1 = \
"""BANDS = 1
BAND_STORAGE_TYPE = BAND_SEQUENTIAL
BAND_NAME = "N/A"
LINES = 2240
LINE_SAMPLES = 3840
SAMPLE_TYPE = UNSIGNED_INTEGER
SAMPLE_BITS = 8
END
~~now starts binary image data~~
"""

filename = "mc03.img"

# write test image file
fout = open(filename, "wb")
fout.write(str1)
fout.close()

# read image file line by line
for line in open(filename, "rb"):
    if 'END' in line:
        break
    if 'LINES' in line:
        # remove trailing newline
        line = line.rstrip('\n')
        # extract integer value
        print int(line.split('=')[1])  # 2240
bumsfeld 413 Nearly a Posting Virtuoso

For learning about Python and XML see this website:
http://pyxml.sourceforge.net/topics/howto/xml-howto.html

For GUI package for Python I would use wxPython. It is much more powerful than Tkinter.

Python is useful for just about anything you are interested in. Things like scientific calculations, problem solving, working with databases, networking, WEB programming, audiovisual processing, text processing and many more.

Take short look at "Projects for Beginners"
http://www.daniweb.com/techtalkforums/thread32007.html

and Python code snippets on Daniweb.
http://www.daniweb.com/code/python.html

bumsfeld 413 Nearly a Posting Virtuoso

So, you want to know the operating system your computer has? This short Python code can tell you:

import sys

operating_system = sys.platform
print operating_system              # eg.  win32

if operating_system[:3] == 'win':
    print "Your OS is Windows"
elif operating_system[:5] == 'linux':
    print "Your OS is Linux"

# or ........

import os

print os.name              # eg.  nt
print os.environ['OS']   # eg.  Windows_NT
bumsfeld 413 Nearly a Posting Virtuoso

Is there a way to verify an exit, if you click on the exit symbol on a wxPython frame?

I left a short example in code snippet area:
http://www.daniweb.com/code/snippet526.html

bumsfeld 413 Nearly a Posting Virtuoso

"Beautiful Soup" is an HTML/XML parser for Python that can turn even poorly written markup code into a parse tree, so you can extract information.

Download the free program and documentation from:
http://www.crummy.com/software/BeautifulSoup/

bumsfeld 413 Nearly a Posting Virtuoso

If you insist writing your own destructor for class Tree, change it to this:

class Tree:
    def __init__(self):
        self.Root = None
    def __del__(self):
        if self.Root != None:
            del self.Root
    def LNR(self):
        ...
        ...

Note: Destructors are optional thing in Python.

bumsfeld 413 Nearly a Posting Virtuoso

This was not a dumb question! It was a question that needed to be asked! So, thanks for asking it and answering it!

bumsfeld 413 Nearly a Posting Virtuoso

Helena is lucky to have her own programmer! I too had Windows problem and solved it by putting message in label. I couldn't help myself, just had to add some colour. I hope Helena is not colorblind. I also show you how to bind the return key. Here is your program with some colour:

from Tkinter import *
import tkMessageBox
import random
#import string  # not needed!

def ask():
    global num1 
    num1 = random.randint(1, 12)
    global num2 
    num2 = random.randint(1, 12)
    global answer 
    answer = num1 * num2
    label1.config(text='What is ' + str(num1) + 'x' + str(num2) + '?')
    # put the cursor into the Enter-Box
    entry1.focus_set()
    
def checkAnswer():
    herAnswer = entry1.get()
    # if empty give message
    if len(herAnswer) == 0:
        tkMessageBox.showwarning(message='Need to enter some number!')
        return
    if int(herAnswer) != answer:
        tkMessageBox.showwarning(message='The answer is: ' + str(answer))
    else:
        tkMessageBox.showinfo(message='Correct!')

#set the window
root = Tk()
# add some color
root.tk_bisque()
root.title("Helena's Multiplication Quiz")
root.geometry('500x500')

# replaces tkMessageBox.showinfo() 
label2 = Label(root, text="Hi, Helena!\n  Let's do some multiplication problems!")
# add a colorful font
label2.config(font=('times', 18, 'bold'), fg='red', bg='yellow')
label2.grid(row=0, column=0)

#add label
label1 = Label(root)
label1.grid(row=2, column=0)

#add entry
entry1 = Entry(root)
entry1.grid(row=3, column=0)
# bind the return key
entry1.bind('<Return>', func=lambda e:checkAnswer())

#add button
askBtn = Button(root, text='Ask Me a Question!', bg='green', command=ask)
askBtn.grid(row=4, column=0)

okButton = Button(root, text='OK', command=checkAnswer)
okButton.grid(row=4, column=1)

# seems to create a problem with the entry1 focus in Windows, replace with label2
#tkMessageBox.showinfo(message="Hi, Helena!  Let's do some multiplication problems!")

root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

Please show your code. It makes it tough to help without it. Others too can learn from your code and the answers.

This would be one way to bind Entry box enter1 to return key:

enter1.bind('<Return>', func=my_function)

The data is then in enter1.get() as a string.

bumsfeld 413 Nearly a Posting Virtuoso
  • Politics Geek
  • Hate-Tatoos Geek
  • Food Geek
bumsfeld 413 Nearly a Posting Virtuoso

Go to directory where idle.py is located. On my Windows XP computer this was
C:\Python24\Lib\idlelib
Now bring up file
config-main.def
in editor like NotePad. It explains a lot of your questions.

bumsfeld 413 Nearly a Posting Virtuoso

Strings ar immutable like tuples, but have many functions to operate on them, while tuples do not. How is this?

bumsfeld 413 Nearly a Posting Virtuoso

Imagine robot arm with three pulse driven motors. One motor for each axis (x = left/right, y = up/down, z = depth). Positive pulse goes 1/10 unit (cm or inch) in one direction, negative pulse in opposite direction.

At the end of the robot arm is woodcutting tool (router). Write Python program to make the tool cut one semisphere from solid block of wood (20x20x10 units).

bumsfeld 413 Nearly a Posting Virtuoso

A kbyte is 1024 bytes. This would be more correct:

fsize = os.path.getsize(fname) 
print "size = %0.1f kb" % float(fsize/1024.0)
bumsfeld 413 Nearly a Posting Virtuoso

I assume you want to sum numeric values. Here is slight modification, also removing return statement out of the loop:

def three2one(prot):                                            
    code = {"G" : "6", "A" : "7", "L" : "1", "I" : "4",
            "R" : "2", "K" : "3", "M" : "5", "C" : "8",
            "Y" : "9", "T" : "10", "P" : "11", "S" : "12",
            "W" : "14", "D" : "15", "E" : "16", "N" : "17",
            "Q" : "18", "F" : "19", "H" : "20", "V" : "21" , "R" : "22"}
 
    newprot = 0
    for aa in prot:
        newprot += int(code.get(aa))
        print newprot  # just for testing
    return newprot
 
prot ="""FGYYHFRPTKLRQWEI"""
# split this up to make testing go better
result = three2one(prot)
print "result =", result
bumsfeld 413 Nearly a Posting Virtuoso

Maybe using the famous Microsoft kludge for handling spaces in filenames will do the trick. This wraps a pair of single quotes and double quote around the string. Try:

j = win32pipe.popen('"c:\\disk\\plink jnitin@10.94.101.178 -pw mat123 df -g"','r')

Also, if plink is plink.exe use extension.