SoulMazer 26 Posting Whiz in Training

Thanks for the links myle. Except I seem to be having a little trouble with my server (which uses the asyncore module). I'm not quite sure how I can implement ssl into my code:

class ChatServer(dispatcher):

    def __init__(self, port, name):
        dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(('', port))
        self.listen(5)

    def handle_accept(self):
        conn, addr = self.accept()

if __name__ == '__main__':
    s = ChatServer(PORT, NAME)
    try: asyncore.loop()
    except KeyboardInterrupt: pass

Now, if I add "self.ssl.wrap_socket(conn, server_side=True, certfile="servercert.pem", keyfile="serverkey.pem", ssl_version=ssl.PROTOCOL_SSLv3)" into my "__init__" method, I get the following error:

s = ChatServer(PORT, NAME)
File "chatserver.v0.3.py", line 854, in __init__
self.ssl.wrap_socket(conn, server_side=True, certfile="servercert.pem",
File "/usr/lib/python2.6/asyncore.py", line 391, in __getattr__
return getattr(self.socket, attr)
AttributeError: '_socketobject' object has no attribute 'ssl'

SoulMazer 26 Posting Whiz in Training

Hi, I have written a simple chat server and a client that can connect to it. To make it more secure, I would like to add SSL to the connection process. How would I go about doing this?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Ok, well I finally solved this by myself. For the multi-color part, check this thread. For the part about an auto-scrollbar, I just repeatedly called the following code:

Text.yview(END)

Thanks to everybody that helped.

SoulMazer 26 Posting Whiz in Training

Sorry, I finally figured this out myself. If anybody is curious:

msgbox = Text(master)
msgbox.tag_config("myfootag", foreground="#66FFFF")

mytext = raw_input("> ")
if "foo" in mytext:
      parts = mytext.split("foo")
      msgbox.insert(END, parts[0])
      msgbox.insert(END, "foo", ("myfootag"))
      msgbox.insert(END, parts[1]+"\n")

IMPORTANT NOTE: This code assumes that you will only have one instance of "foo" in your code.

SoulMazer 26 Posting Whiz in Training

Hi, so in order to make my problem more clear, I shall just make a simple example of what I am trying to do. I will start with a little code:

from Tkinter import *

master = Tk()

msgbox = Text(master)
msgbox.pack()

mytext = raw_input("> ")
msgbox.insert(END, mytext)

master.mainloop()

Now, say I enter the string "foo just ran down the street and met his friend bar. foo was very happy" when I am prompted by "raw_input". What I would like to do is tag all occurrences of "foo" and color them red. How would I go about doing this?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Sorry for the second post, but I missed sneekula's post.
@sneek: Ok, if I try your code I get the following error:

Traceback (most recent call last):
File "/home/foo/Documents/pyscripts/ChatProgram/Versions/Client/chatclient.v0.3.py", line 125, in <module>
client.msgbox = myapp.setup(master, client)
File "/home/foo/Documents/pyscripts/ChatProgram/Versions/Client/chatclient.v0.3.py", line 36, in setup
self.msgbox.yview_scroll(lines, "units")
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 3167, in yview_scroll
self.tk.call(self._w, 'yview', 'scroll', number, what)
_tkinter.TclError: expected integer but got "0 0"

EDIT: Ok, I figured out that I receive a "TclError" if the contents of the widget isn't long enough to scroll through so I put your code within a "try" statement. However, if the contents of the widget is long enough, it doesn't scroll.

Thanks again.

SoulMazer 26 Posting Whiz in Training

Use scrollbar.config ()
scrollbar.config( command = listbox_widget.yview )
listbox_widget.see(listbox_widget.size())
I think it is something like this for a text widget
Text.see(Text.END)

Well, here is my code:

self.scrollbar = Scrollbar(master)
self.scrollbar.pack(side=RIGHT, fill=Y)
        
self.msgbox = Text(master, bg="black", fg="#0099cc") #33CCCC
self.msgbox.focus_set()
self.msgbox.pack()
        
self.msgbox.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.msgbox.yview, bg="black", activebackground="#313131")
        
self.msgbox.see(self.msgbox.END)

And I receive this error:

self.msgbox.see(self.msgbox.END)
AttributeError: Text instance has no attribute 'END'

Most all of Tkinter's widget's have a background and foreground option. See the docs.

Ok, well I must have been a little unclear. I would like to make it multi-colored. As you can see in my code above, I have already set the main foreground and background colors for my Text widget, except would it be possible to do something like such?:

chatstr = "#FFFFFFHello,#000000World#FF0000!!
client.msgbox.insert(END, chatstr + "\n")

So "Hello" would be white, "World" would be black, and the two exclamation points would be red. Is that possible to do within the same widget?

Thanks again.

SoulMazer 26 Posting Whiz in Training

Also, if you did not want to use threading/multiprocessing, you could use the "after" method.

Example:

def dothis():
    #Do something
    master.after(2000,dothis)       

master = Tk()
myapp.after(2000,dothis) 
master.mainloop()

Arguments:
The first argument is the time in milliseconds, the second is the function to run after the time set in the first argument has passed.

SoulMazer 26 Posting Whiz in Training

Ok, I am writing a client for the "instant messaging" server I just wrote. The client is in all Python, and the GUI is made with Tkinter.

Anyways, my first question is this: is there a way to make a scrollbar widget automatically scroll to the bottom?

Second, in a Text widget, how would I be able to make everything...colored? Example: "<Username> Message."
Would there be a way to make "username" blue and "message" say....green?

Thanks in advance

SoulMazer 26 Posting Whiz in Training
print 'Hello ' + name

Try this:

print "Hello,", name

The why:

If you use the code: "string1"+"string2"
You get the following: string1string2
However, if you use this: "string1","string2"
You get: "string1 string2" (notice the space)

cohen commented: Thanks for your Python help! It worked well! +2
SoulMazer 26 Posting Whiz in Training

Well I finally solved the problem, myself. I did this while doing another script. When doing that other script, I got stuck and looked for some samples on the web...somebody on the web used a method named "after". I thought about applying that method to my current situation and it worked! In case anybody wants to see the actual fix:

def recvdata1():
    client.recvdata()
    print "Successfully received data."
    master.after(150,recvdata1)       

client = ChatClient()
master = Tk()
myapp = MyGUI(master)
myapp.after(150,recvdata1)  #The first argument is the time in milliseconds, the second is the function to run after the time set in the first argument has passed.
myapp.mainloop()

Well, thanks to everybody that helped.

SoulMazer 26 Posting Whiz in Training

That is misinformation, what led you to believe that?

I for some reason thought that binding a key to an action was a looping action (like the .mainloop() of a GUI). I'm not sure where I got that notion, but I just combined the two and received no errors. Thanks for that.

Back to the original problem, what can I do to fix the problem stated in my last post?

Thanks again.

SoulMazer 26 Posting Whiz in Training

Ok, here's my MyGUI class:

from Tkinter import *

class MyGUI(Frame):
    
    def __init__(self): pass

    def setup(self, master, Tkinter, client):
        Frame.__init__(self, master)
        self.pack()
        scrollbar = Scrollbar(master)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        self.msgbox = Text(master)
        self.msgbox.focus_set()
        self.msgbox.pack()
        
        self.msgbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.msgbox.yview)
        return self.msgbox
    
    def setup2(self):
        self.entrything = Entry()
        self.entrything.pack()
    
        self.contents = StringVar()
        self.contents.set("")
        self.entrything["textvariable"] = self.contents
        self.entrything.bind('<Key-Return>', self.print_line)
        
    def print_line(self, event):
        "Gets the content of the entry box and adds it to the main text area"
        mytext = "Foo: "+self.contents.get()
        self.entrything.delete(0, END)
        self.addmsg(mytext, client)
        
    def addmsg(self, chatstr, client):
        "Actually adds the contents of the entry box to the text area"
        if chatstr == "Foo: ":
            pass
        else:
            client.msgbox.insert(END, chatstr + "\n")
            client.senddata(chatstr)

(The reason I have two "setup" methods is because in the first one I return a variable, and in the second one I have to bind an action to a key. As far as I know, these can't both be done within the same method.)

Also, if I put a myapp.mainloop() right after the myapp = MyGUI, the GUI runs perfectly.

Thanks again.

SoulMazer 26 Posting Whiz in Training

Ok, sorry but disregard my last post. I think I'm going to just stick with threading. Anyways, I think I am being a little unclear in what my real problem is. It is rather difficult to explain in words, so I will just give an example.

import threading

class RecvData(threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        client.recvdata()
        print "Successfully received data."

class GUILoop(threading.Thread):
    def __init__(self, myapp):
        threading.Thread.__init__(self)
        print "Checkpoint Two"
        myapp.mainloop()
        print "Checkpoint Three"
        
# Client Setup
client = ChatClient()
s = client.connect(host, port)
# GUI Setup
master = Tk()
myapp = MyGUI()
client.msgbox = myapp.setup(master, Tkinter, client)

# Threads
print "Checkpoint One"
GUILoop(myapp).start()
print "Checkpoint Four"
RecvData(client).start()

When I run this code, my output is like such:

Checkpoint One
Checkpoint Two

As you can see, it just doesn't get past the ".mainloop()" of my GUI (line 13 in the code), even though it's in a thread. So...to put it in the most simple terms...how can I make my script get to "Checkpoint Three"?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Thanks for the idea jlm, except I actually think woooee has more of what I am looking for (running two pieces of code continuously and simultaneously).

Except now I get an error without a traceback when I run my script.

X Error of failed request: BadIDChoice (invalid resource ID chosen for this connection)
Major opcode of failed request: 45 (X_OpenFont)
Resource id in failed request: 0x6e00010
Serial number of failed request: 72
Current serial number in output stream: 73

What can I do to fix this?

Thanks again.

SoulMazer 26 Posting Whiz in Training

Ok thanks, that just about did it. Now I just have one slight problem. How would I pass a variable to the "run" method?

For example:

import threading

myapp = MyGUI()

class Test(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self, myapp):
        myapp.mainloop()
T = Test()
T.start()

Because if I just replace T = Test() with T = Test(myapp), the argument it pass to "__init__", not "run". How would I go about doing this?

Thanks again.

SoulMazer 26 Posting Whiz in Training

Ok, I really hated to resort to threading, but it seems like I have no other choice. I am writing a client script for the "instant message" server I just finished writing. Sadly, I am having a slight problem with threading. What I would like to do is have two threads running simultaneously: thread one would control the main loop of the GUI, thread two would receive messages sent from the server. Yet, I am having trouble with this.

My code (Note, this is just the part that the threading concerns):

import threading

class RecvData(threading.Thread):
    def __init__(self, client):
        print "RecvData thread started."
        while True:
            client.recvdata()

class GUILoop(threading.Thread):
    def __init__(self, myapp):
        print "GUILoop thread started."
        myapp.mainloop()
        
# Client Setup
client = ChatClient()
s = client.connect(host, port)
# GUI Setup
master = Tk()
myapp = MyGUI()
client.msgbox = myapp.setup(master, Tkinter, client)

# Threads
RecvData(client).start()
GUILoop(myapp).start()

Now, when I run this code, only the first thread executes. So what am I doing wrong and how can I fix this to make both threads run at the same time?

Thanks very much in advance.

SoulMazer 26 Posting Whiz in Training

Well, sorry for the double post, but I somehow solved my problem. I have no idea how...I just bugged around with some variable names and such and I stopped receiving the error. Weird.

Well, feel free to delete this thread. Sorry again.

SoulMazer 26 Posting Whiz in Training

Hi, so I am trying to write a simple chat server in Python. If I just run the server, it runs fine. Yet, when I try to connect to the server from a different terminal via a "telnet localhost (port)", the server gives me an error:

error: uncaptured python exception, closing channel <__main__.ChatServer listening :5008 at 0x7f7eb733be60> (<type 'exceptions.TypeError'>:__init__() takes exactly 3 arguments (2 given) [/usr/lib/python2.6/asyncore.py|read|74] [/usr/lib/python2.6/asyncore.py|handle_read_event|408] [./ChatServer.py|handle_accept|58])
warning: unhandled close event

I saw the "__main__.ChatServer" and the "TypeError'>__init__() takes exactly 3 arguments (2 given)", so I assumed I was forgetting to pass a variable...yet I don't think I am.

Code:

port = 5008
name = "TestChat"

class ChatServer(dispatcher):
    def __init__(self, port, name):
        ...
        ...
s = ChatServer(port, name)
try: asyncore.loop()

So...what's my problem here? It complains about receiving 2 variables instead of 3...but it only accepts 2 (port, name)? Now what can I do to solve my problem?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

I will have to try that. Thanks for the idea.

SoulMazer 26 Posting Whiz in Training

What would opening it as unbuffered do? And would it have a large effect on performance?

SoulMazer 26 Posting Whiz in Training

try this:

infoToWrite = "Harry Potter: Teenage boy who has an owl"
myFile = open("characterlist.txt",'r+')
myFile.write(infoToWrite)
myFile.flush()

you can put a raw_input() line beneath flush() and check if it's writing to file

Thank you so much! It would have been a pain to close and re-open the file every time I wrote to the file. Solved my problem. Thanks again.

SoulMazer 26 Posting Whiz in Training

Try:

infoToWrite = "Harry Potter: Teenage boy who has an owl"
myFile = open("characterlist.txt", "r")
myFile.write(infoToWrite)

It should work, I only removed the 'plus'(+) after the r in 'myFile'

Thanks for an idea, except how would that work? Isn't "r" for just reading? If I do what you suggested, I am greeted with the following error:

IOError: [Errno 9] Bad file descriptor

SoulMazer 26 Posting Whiz in Training

Ok thanks for the idea.

SoulMazer 26 Posting Whiz in Training

Hi, I am writing a script that aims to help a person keep a list of characters while reading a book. In doing this, I am writing to a file and checking it constantly, except I ran into a problem. Say I executed a code block such as the following:

infoToWrite = "Harry Potter: Teenage boy who has an owl"
myFile = open("characterlist.txt", "r+")
myFile.write(infoToWrite)

Now after this code is executed, I notice that my "characterlist.txt" file does not contain the data I just wrote. However, if I were to close the Python shell, the file contains the data.

So, what is causing this? And is there anything I would be able to do to make this file writing instantaneous?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Perfect. That solved it. Thank you very much.

SoulMazer 26 Posting Whiz in Training

This is my first PHP script, so please excuse my clumsiness. I have a HTML page which consists of a form and a PHP page which deals with the variables that are outputted. The HTML page functions as a small box that asks to input an email account/password, and the PHP page simply echoes the results.

My HTML page:

<html>
<form action="emailresults.php" method="post">
        <p>
                Email address:<br />
                <input type="text" name="email" size="20" maxlength="50" value="" />
        </p>
        <p>
                Password:<br />
                <input type="password" name="pswd" size="20" maxlength="15" value="" />
        </p>
        <p>
                <input type="submit" name="subscribe" value="subscribe!" />
        </p>
</form>
</html>

My "emailresults.php":

<?php
      echo "The email you entered is $_POST['email'].";
      echo "The password you entered is $_POST['pswd'].";
?>

When I arrive at my PHP page, I get the error "Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING" for line 2.

What can I do to fix this?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Well, that was a great deal easier than I thought it would be. Thank you for catching my stupid mistake. And also, it seems like every time I post on this forum you always seem to be the one to solve my problems. Thank you again!

SoulMazer 26 Posting Whiz in Training

So, I always thought that it was possible to return dictionaries in Python. I was wanting to do this because I would prefer not to use globals. However, I am having trouble with returning my dictionary.

Code:

#!/usr/bin/python
# 6/9/09

def loadWords():
    pathstart = "/home/foo/Documents/PyScripts/Vocab/Lists/"
    print "What is the number of the list you would like to load?"
    listnum = raw_input("> ")
    fn = 'VocabList.'+str(listnum)+'.txt'
    fullpath = pathstart + fn
    wordfile=open(fullpath,"r")
    words = {}
    for i in wordfile:
	p=i.split(":")
	first = p[0]
	second = p[1]
	words[first] = second
    print "Print test one..."
    for x in words:
	print x
    return words
	
loadWords()
print "Done loading words."
print
print "Print test two..."
print
for x in words:
    print x,
print "Done printing words."

If it matters, this is what my "VocabList.0.txt" file looks like:

uno:one
dos:two
tres:three
cuatro:four
cinco:five

Also, the output of running my script is the following:

What is the number of the list you would like to load?
> 0
Print test one...
cuatro
dos
tres
cinco
uno
Done loading words.

Print test two...

Traceback (most recent call last):
File "./VocabTest.Revamp.py", line 27, in <module>
for x in words:
NameError: name 'words' is not defined

So, what could I do to allow myself to print the "words" dictionary out of the function "loadWords"?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Thanks for the idea woooee, but I think I'm going to try to stick with one dictionary for now. If I continue to expand on the script, I might end up using two. And thanks for everybody's input. I am leaving tomorrow so I will no longer be able to respond.

Thanks everybody!

SoulMazer 26 Posting Whiz in Training

Thanks snee that really helps. I actually have a pretty big script going now. Would it be okay if maybe in a few hours I could post it here and get a little help on it? I am trying to avoid globals, but I have no idea how I could do so when I am using so many different variables in different functions.

SoulMazer 26 Posting Whiz in Training

Oh thanks woooee that looks like a very nice tool to use.

SoulMazer 26 Posting Whiz in Training

Thanks jlm you solved my problem. I had originally tried using an absolute path, but Python does not like Linux shortcuts. So, this was all caused because I typed out ~/myscript.py instead of /home/blah/myscript.py....laziness fails!

Thank you for your reply though. Learned something new with that os.chdir function!

SoulMazer 26 Posting Whiz in Training

Sorry, I realized I was a little unclear about what I was trying to say.

So, that is like what I wanted, but not quite. I wanted to do it so...I think it would be easier to show you.

Membrane that surrounds the heart
a. somepossibleanswer
b. somepossibleanswer
c. somepossibleanswer
d. somepossibleanswer
e. correct answer
f. somepossibleanswer

> e

Correct!

So pretty much, rather than typing in the first letter of the correct answer, I would like to do it in a format where you choose a/b/c/d/e/f.

Sorry for the inconvenience, however I have no idea how I would do this.

SoulMazer 26 Posting Whiz in Training

For the time being, I just changed the keys to the name of the correct answer.

Example:

Instead of

"c":"The brain region which controls the coordinates muscular activity\na. medulla oblongata\nb. cerebrum\nc. cerebellum\nd. optic lobe\ne. brain stem"

I did this:

"cerebellum":"The brain region which controls the coordinates muscular activity\na. medulla oblongata\nb. cerebrum\nc. cerebellum\nd. optic lobe\ne. brain stem"

Also, that brings me to a great question. Currently, I have my script set to check if the user's answer is equal to the key of the dictionary pair. Since I cannot just name the keys "a", "b", etc., is there any other way I could have the user type in only "a" or "b", rather than the entire answer?

SoulMazer 26 Posting Whiz in Training

For my script, I am trying to open a text file and print out the information in the console window. However, I am having trouble finding the right way to load it.

To start, I need to figure out how to load something in the same directory as the script, so far I have this:

listnum = input("> ")
fn = 'VocabList.'+str(listnum)+'.txt'
wordfile=open(fn,"r")

This returns

wordfile=open(fn,"r")
IOError: [Errno 2] No such file or directory: 'VocabList.0.txt'

So, what am I doing wrong?
Also, is it possible to load a file in another directory?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Much sorryness. I just figured out that the words were my problem. All the words were technically the same 6 keys *hits head on desk*. Feel free to delete thread.

SoulMazer 26 Posting Whiz in Training

So, I have this script that I am using to study some Biology vocab words for my final tomorrow. All I did was put the list of words/definitions in my existing script, and everything seems to go wrong. I have a total of 50 definitions, yet it says there are only 6.

Simplified code:

#!/usr/bin/python

words = {"a":"The placing of sperm cells in the oviducts of the females is called\na. internal fertilization\nb. milting\nc. spawning\nd. moting\ne. external fertilization\nf. tremendously invigorating",
	     "c":"The brain region which controls the coordinates muscular activity\na. medulla oblongata\nb. cerebrum\nc. cerebellum\nd. optic lobe\ne. brain stem",
	     "c":"brain region which attaches brain to spinal column and controls internal organs\na.cerebellum\nb.cerebrum\nc. medulla oblongata\nd. hypothalamus",
	     "c":"the sac that stores the fluid cellular wastes of the body\na.gall bladder\nb. medulla oblongata\nc. urinary bladder\nd. villi\ne. mesentary",
	     "f":"The muscle that divides the abdominal and thoracic cavities in mammals is the\na. rugae\nb. tricep\nc. bicep\nd. caecum\ne. peritenium\nf. diaphragm",
	     "e":"The organ that allows exchange of materials between the embryo and mother in mammals is the\na. dura mater\nb. amnion\nc. yolk\nd. chorion\ne. placenta\nf. none of the above",
	     "e":"The reason for the testes being carried in the scrotum outside of the body is\na. for looks\nb. to decrease sperm production\nc. to increase the production of sperm\nd. unknown to scientists\ne. temperature regulation",
	     "d":"One characterist all mammals have in common is that\na. they are terestrial\nb. they have large brains\nc.they bear live young\nd. their young are nourished by milk\ne. all of these",
	     "e":"the largest brain region in mammals -- it controls memory -- is\na.dura mater\nb. medulla …
SoulMazer 26 Posting Whiz in Training

Alright it solved my problem. Thank you very much.

SoulMazer 26 Posting Whiz in Training

So, I had a quick question about having multiple arguments being read into a bash script. In the following script, if I type "./myscript -h", it returns "Hippo.". However, if I type "./myscript -h -k", the script returns only "Hippo." I would like to know how to have the script print out both "Hippo." and "Kangaroo.". What is the easiest way to do this?

case "$*" in
*-h*)
echo "Hippo."
;;
*-k*)
echo "Kangaroo."
esac

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Well, it is finally working. The problem was not with the function itself, but I have the script run a different function if the word is not correct. Somehow, that other function must have been editing the answer input by the user.

Well, thank you for all the continued help paulthom! Rep well deserved!

SoulMazer 26 Posting Whiz in Training

Dang nice try. But still nothing. I even tried stripping the answer. Nada!

SoulMazer 26 Posting Whiz in Training

Well...big step! No errors! However, the script does not seem to like matching variables.

What word does the following definition correspond with?
cheap and gaudy in nature or appearance; showy; sleazy
> tawdry
That is incorrect. The answer was tawdry

Code:

def vocabtest():
    word = words.keys()
    random.shuffle(word)
    for w in word:
        a = words[w]
        print "What word does the following definition correspond with?"
        print a
        answer = raw_input("> ")
        answer = answer.strip()
        if words[answer] == w:
            print "Correct!"
        else:
            print "Fail."
SoulMazer 26 Posting Whiz in Training

Sorry for all the trouble paulthom, but I am still getting errors. Now I am getting Key Error at random words in my dictionary.

Error:
print words[w]
KeyError: ('inert', 'without power to move or act; lifeless; exhibiting no chemical activity; unreactive')

It does not only happen with the word inert, but with a variety of words. Well hey at least now I know the dictionary is randomized!

However, may you please help me again?

Thanks.

SoulMazer 26 Posting Whiz in Training

Well, when I use that code, it simply does nothing. I have no idea what is wrong...I have tried shuffling both the keys and the values, as well as items.

Simplified Code:

def vocabtest():
    random.shuffle(words.items())
    for a, r in words.items():
        print "What word does the following definition correspond with?"
        print a
        answer = raw_input("> ")
        if words[answer] == r:
            print "Correct!"
        else:
            print "Fail"

I tested two versions of the code in two different shells: one with the "random.shuffle..." line, and one without. And, they both output the words in the same exact order. Am I doing some idiot mistake or what is wrong?

SoulMazer 26 Posting Whiz in Training

Thanks paulthom, however I get a TypeError when I add in those lines.

Full error:
for f in random.shuffle(words.keys()):
TypeError: 'NoneType' object is not iterable

Any idea what is wrong?

Thanks.

SoulMazer 26 Posting Whiz in Training

Hi, so I just have a question that I at least think will be pretty easy. So, I am making a script that basically gives you a "vocabulary test". There is just one feature I would like to implement that I need help with.

I would like to make it randomized. I am using a dictionary for all my words/definitions, and I know that the dictionary does not keep them in order, however it is not randomized.

What would be the easiest way to randomize the order in which the questions are asked?

Snippet of code: ("words" is a dictionary)

def vocabtest():
    for a, r in words.items():
        Blah
        Blah

Thank you in advance.

SoulMazer 26 Posting Whiz in Training

Thank you again. I have all my problems fixed. Now, however, I have a new problem. If you would be able to still help I would greatly appreciate it.

Thanks again!

SoulMazer 26 Posting Whiz in Training

Thanks Gribouillis, that solved my immediate problem. However, yes I am still a beginner, but how would I access...or just print the correct answer?

Thanks.

SoulMazer 26 Posting Whiz in Training

Hello, if you have seen any of my other posts you will know I am working on a script to make a "vocabulary test". I currently having it functioning nearly perfectly, except I get an error if I enter the wrong word.

Code:

def vocabtest():
    for r in words.values():
        count = 0
        while count < 3:
            print("What word does the following definition correspond with?")
            print(r)
            answer = raw_input("> ")
            if words[answer] == r: #Error
                print("Correct!")
                count = 100000
            elif words[answer] != r:
                if count < 2:
                    count = count + 1
                    print("That is incorrect. Try again.")
                elif count == 2:
                    count = count + 1
                    print("That is incorrect. The answer was",str(words[r]) + ".")
                    fail[r] = words[r]

If I enter the wrong word, I get a Key Error at line 8. Would anybody be able to help? Thanks in advance.