Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

Since you want to save and later load an entire container object, the module pickle is what you want to use. Hre is a simple example:

# pickle saves and loads any Python object intact
# via a byte stream, use cpickle for higher speed

import pickle

myList1 = [12, 52, 62, 02, 3.140, "Monte"]
print "Original list:"
print myList1
file = open("list1.dat", "w")
pickle.dump(myList1, file)
file.close()
file = open("list1.dat", "r")
myList2 = pickle.load(file)
file.close()
print "List after pickle.dump() and pickle.load():"
print myList2

In your case you would pickle the students dictionary!

Ene Uran 638 Posting Virtuoso

I think bash is a script language on Linux computers. I don't use Linux (yet), so I can't test it, but the program flow is easy to follow. The first part is a menu from which you select, and the second part is a case statement that activates a slected program on Linux.

Python does not have a case statement, but you can use a series of if/elif condionals or a dictionary made to look like a case statement. To run an external program from Python, you can use os.system("program")

Here is a simplified version in Python:

import os

while True:
    print
    print "PROGRAM MENU"
    print "1 - open xmms"
    print "2 - open emacs"
    print "3 - open gparted"
    print "4 - open gedit"
    print "5 - open firefox"
    print "6 - open gaim"
    print "7 - open kopete"
    print "8 - open console"
    print "0 - exit program"
    print
    selection = input("Enter selection: ")
    if selection >= 0:
        break

if selection == 0:
    raise SystemExit
elif selection == 1: os.system("xmms")
elif selection == 2: os.system("emacs")
elif selection == 3: os.system("sudo gparted")
elif selection == 4: os.system("gedit")
elif selection == 5: os.system("firefox")
elif selection == 6: os.system("gaim")
elif selection == 7: os.system("kopete")
elif selection == 8: os.system("konsole")
Ene Uran 638 Posting Virtuoso

You can use function sys.exc_info() to fetch the error created by my_program.py:

# save as my_file.py
# executes a file my_program.py which has an error

from Tkinter import*
import sys

root=Tk()
text=Text()
text.pack()

try:
    execfile('my_program.py')
except:
    error = "%s --> %s in file my_program.py"% (sys.exc_info()[0], sys.exc_info()[1])
    
# put error msg raised by my_program.py into text field
text.insert(END, error)
mainloop()

I am always surprised by the things Python can do! Have fun with Python!

Ene Uran 638 Posting Virtuoso

Just a few observations, hope you don't mind:

1) Python has True = 1 and False = 0 builtin

2) define your functions outside of the conditional if, or Python will redefine your functions whenever you take a test. This would slow down the program. The memory manager cleans up properly though.

3) use a try/except to protect against non numeric entries

Here is the code sample updated:

#true = 1   # Python has True = 1 
#false = 0  # Python has False = 0 

def get_questions(x = -1):
    lista = [["What colour is the daytime sky on a clear day?","blue"], 
            ["What is the answer to life, the universe and everything?","42"], 
            ["What is a three letter word for mouse trap?","cat"], 
            ["What noise does a truly advanced machine make?","ping"]] 
    if x == -1: 
        return lista 
    else: #of course, it's recommended to check if x is out of bounds 
        return lista[x] 

def check_question(question_and_answer): 
    question = question_and_answer[0] 
    answer = question_and_answer[1] 
    given_answer = raw_input(question) 
    if answer == given_answer: 
        print "Correct" 
        return True 
    else: 
        print "Incorrect, correct was: ",answer 
        return False 

def run_test(questions):
    if len(questions) == 0: 
        print "No questions were given." 
        return 
    index = 0 
    right = 0 
    while index < len(questions): 
        if check_question(questions[index]): 
            right = right + 1 
        index = index + 1 
    print "You got ", right*100/len(questions),"% right out of",len(questions) 

menu_item = 0 
while menu_item != 9: 
    print "------------------------------------" 
    print "1. Take test" 
    print "2. Display all questions and answers." 
    print "9. quit"
    try:
        menu_item = …
Ene Uran 638 Posting Virtuoso

To find experiments with the Python random module see:
http://www.daniweb.com/code/snippet306.html

For loops and function range() are covered in:
http://www.daniweb.com/code/snippet386.html

You can search the Python snippets and this forum for other things like lists, strings, dictionaries, tuples, file handling and so on.

Different text types are the realm of GUI programming with Tkinter for instance.
Here is an example of a Tkinter GUI program that sets a text font and uses random:

# display random sentences from a list using colorful Tkinter

from Tkinter import *
import random

black  = '#000000'
blue   = '#0000FF'
red    = '#FF0000'
yellow = '#FFFF00'
lime   = '#00FF00'

sentenceList = [
'the dog is on skates', 
'the bird is on a plane', 
'the pig rides the horse',
'the snake is on rollerskates',
'the fish drives a car']

def setText():
    str1 = random.choice(sentenceList)
    push1.config(text=str1)
    

#create the form
form1 = Tk()

# set the form's title
form1.title('Random Text')

# create a button
push1 = Button(form1, text='Click to set new text .............', command=setText)

# configure the button's text font and foreground/background colors
push1.config(height=3, font=('times', 20, 'bold'), fg=black, bg=yellow)

# pack the button into the frame
push1.pack(expand=YES, fill=BOTH)

# start the event loop (run the program)
form1.mainloop()

A good tutorial for beginners is in this online book:
http://www.ibiblio.org/g2swap/byteofpython/read/

Ene Uran 638 Posting Virtuoso

Thanks for thinking out loud, I found it interesting!

Ene Uran 638 Posting Virtuoso

Once you go to GUI programming, your approach has to change past just making labels. User actions are initiated by clicking on buttons, data is entered in an entry widget, results and messages can be displayed in labels.

Get used to callback functions. Also, you might as well start a class Risk, so variables are transferred properly via the self. prefix. Just a little extra learning curve here! GUI programming is not too hard, just a mildly different way of thinking

Ene Uran 638 Posting Virtuoso

The answer is: execfile("myfile.py")

Ene Uran 638 Posting Virtuoso

Wow! Your code is hard to read!

See Dani's remarks at: http://www.daniweb.com/techtalkforums/announcement114-3.html

The common way to save data each time you use a program is to save it to a data file. Then bring in the latest saved data each time the program is run. If you want to save data as an object like a complete list, use the module pickle or cpickle.

Ene Uran 638 Posting Virtuoso

I think your trouble comes from the fact that Python itself actually has a module Queue. Rename your module MyQueue.py and it works just fine.

This small code shows you all the modules Python has installed:

help("modules")

To avoid conflicts give your own modules a prefix like "my"or "My".

Ene Uran 638 Posting Virtuoso

You mean something like that:

# write out each text containing line 
# (other than '\n') to a separate file

str1 = """sentence one

sentence two

sentence three

"""

# write str1 to the test file
fout = open("test.txt", "w")
fout.write(str1)
fout.close()

# read the test file as a list of lines
fin = open("test.txt", "r")
list1 = fin.readlines()
fin.close()

print list1  # just testing

n = 0
for line in list1:
    if len(line) > 1:
        n += 1
        filename = "test%d.txt" % n
        fout = open(filename, "w")
        fout.write(line)
        fout.close()
        print "%s --> %s" % (line, filename)  # just testing
Ene Uran 638 Posting Virtuoso

I guess I must be a geek, since I would rather use my computer to write programs and surf the net than watch TV.

Ene Uran 638 Posting Virtuoso

The international forces act as police, training cadre for the Iraqi armed forces, and as construction crews to rebuild damage done to Iraqi infrastructure during the war.

I have buddies in the US Army that tell me that the few Dutch soldiers are too busy with their hairnets to do any good! You must be sponsored by the Shell Oil Company that has huge interests in Iraq.

Ene Uran 638 Posting Virtuoso

We went into Iraq without real goals. Well, the original goals (removal of WMD) were fake.

If we would have spend the trillions of borrowed Dollars on alternative energy, we wouldn't have to worry about gas prices, home heating and home cooling. Research, development and manufacture of alternative energy like wind, solar, bio-diesel, ethanol, butanol, fusion (cold or hot) would have created a lot of good paying constructive jobs.

Well, now we don't have any money left, and future generations of hamburger flippers are stuck with paying off the debt! Just my limited opinion.

Ene Uran 638 Posting Virtuoso

I have been in Las Vegas with some friends on the weekend, and the beer or shots are free as long as you play the penny slots. Of course, these folks want you to loosen up and waste your money on their machines or the tables.

Ene Uran 638 Posting Virtuoso

Can you show us the batch file?

Ene Uran 638 Posting Virtuoso

Vega,
your are right! In the real world it is more important to be out on the market with a working program at the right time. There are a few cases, where it is critical to milk the speed of program execution for every microsecond.

Ene Uran 638 Posting Virtuoso

I have a hunch that driving a printer depends a lot on the operating system and the installed drivers.

Ene Uran 638 Posting Virtuoso

Where can you find more info on the tkinter text widget?

I have played with Tkinter GUI just a little and find it very nice.

Ene Uran 638 Posting Virtuoso

What GUI library are you using? I am a little familiar with Tkinter and wxPython and might be able to help. There are others I am not familiar with.

Ene Uran 638 Posting Virtuoso

I took a look at BioPython, very nice work they have done!

Ene Uran 638 Posting Virtuoso

Is it the processor, the operating system or the compiler?

Old Albert is wrong, human stupidity is rather limited. Infinity is much too perfect!

Ene Uran 638 Posting Virtuoso

If it's anything like the sleep(t) function I have been using with C++, there is no way to stop it early. Maybe ctrl/alt/del, but that is not what you want to normally do.