jlm699 320 Veteran Poster

Let me also say that you seem to be mistaken in your usage of continue. You would use continue to skip the rest of the code within a loop, much like break, however you will continue onto the next iteration instead of completely breaking out of the loop.

You are also confused on the return statement. Return literally returns a value from a function. So by saying return x, there should be a variable waiting to catch that value at the function call.
Example:

>>> def funcA():
...     # This function returns a value
...     g = 5
...     return g
...     
>>> g = 100
>>> ret = funcA()
>>> g
100
>>> ret
5
>>>

See how g has a different scope within the function as it does outside the function? It's not the same variable just because it uses the same name. By saying return however, that variable is being sent back from the function to the main portion of code.

I hope that clears up some of your confusion.

jlm699 320 Veteran Poster
#
#hangman.py
#

import random
import sys
wlist = ['apple', 'blue', 'house', 'frog']
guessed = []
gright = []
guesses = 0
choice = None
word = random.choice(wlist)
# add dictionary for category 


def menu():
    while True:
        print 'Welcome to hangman!'
        print 'To start a new game type "n"\n'
        print 'To quit the game press "q"\n'
        choice = raw_input('enter your choice: ')
        if choice == 'q':
            break
        if choice == 'n':
            return choice
        else:
            print 'invalid selection'
            continue 


def length(n):
    if len(n) > 1:
        return False
    else:
        return True
    
def chckguess():
    global guesses
    n = raw_input('guess a letter: ')
    if n == 'q':
        sys.exit()
    else: 
        if n in word:
            if length(n) is True:
                gright.append(n)
                print 'correct!\n you have found the letters: %s' %gright
                print 'you have used up %d of 5 wrong guesses so far' % guesses
                return gright
        else:
            guesses += 1
            print 'sorry that letter is not in the word'


menu()
while True:
    print 'your word is %d letters long' % len(word)
    while guesses != 5:
        chckguess()
        if len(gright) == len(word):
            print 'you win!'  # later make user solve word
            sys.exit()
        else:
            continue

Here's an example of how to use the global method.

jlm699 320 Veteran Poster

You can use wxPython to display chm files in a native help window.

jlm699 320 Veteran Poster

Google Byte of Python and Dive into Python. Both are great launching pads for getting into some serious Python programming. The latter is more for people that are familiar with programming languages in general, while the first is more for somebody that is using Python as their first programming language ever.

jlm699 320 Veteran Poster
def chckguess(guesses)
#guesses = 0

By declaring guesses = 0 at the beginning of your function you are resetting its value. Also guesses being defined within the function only gives that variable scope within that function.
You should either have that variable be global, and then within the function call global guesses or simply pass the guesses variable from outside the function and then catch it on the return like so: guesses = chckguess(guesses) ; however keep in mind if you do this that you'll need to initialize guesses before your loop so that it exists.

jlm699 320 Veteran Poster

What? Are you asking about two variables of the same name ? Or are you asking about a private variable that can only change through a public modifier?

jlm699 320 Veteran Poster

First try opening an interpreter and just type in import pyExcelerator . That will tell you if you copied the directory to the right location.

jlm699 320 Veteran Poster

If you don't know how to build python packages, simply extract the pyExcelerator directory and place it in your Python site-packages folder... on Windows it will be: C:\PythonXX\Lib\site-packages .

jlm699 320 Veteran Poster

You're on the right track! However I typically like to use slicing when I know precisely where on a line the information that I'm looking for is going to be. Here's what you suggested in a friendly python format:

inp = open('SAdatabsse.txt', 'r')
outp = open('SAdatabse2.txt', 'w')

for eachline in inp:
    line_data = eachline.split()
    if eachline[:2] == 'MM' or eachline[:2] == 'HS':
        outp.write( '%s %s' % ( line_data[0], line_data[3] ) )

inp.close()
outp.close()

BTW, the notation of [:2] is called slicing. Open up a Python interpreter (shell) and play around with it... basically you're "slicing" a piece out of an object.
example of playing around in shell:

>>> slice1 = 'Slicing Example 1'
>>> slice2 = [ 1, 2, 3, 4, 5, 6 ]
>>> slice1[:4]
'Slic'
>>> slice1[4:]
'ing Example 1'
>>> slice1[5:9]
'ng E'
>>> slice2[:2]
[1, 2]
>>> slice2[-2:]
[5, 6]
>>>

As you can see by omitting a number you are basically saying either the beginning or the end of the object
And you can use negative indexing too!

jlm699 320 Veteran Poster

You will need to download and install pyExcelerator as it is not distributed with the standard Python.
Link: Py Package

You cannot create a csv file with multiple sheets (tabs), as the format does not allow it.

jlm699 320 Veteran Poster

What "doesn't seem to work"?
It works fine for me.

jlm699 320 Veteran Poster

Well when you fork a new process, the process ID is returned, so you would append that to a list... then when you're ready to quit, iterate through the list issuing system calls to kill each process.

jlm699 320 Veteran Poster

This is not a Python issue, it is an Access issue. If you can perform the query in Access it will work through Python you just need to be careful as to how you format your query. If you paste the query that you would use from within Access, we can help.

jlm699 320 Veteran Poster

You would need to keep track of the boundary of 'square', which would be the leading edge of movement (this gets really complicated if square is rotating while falling), and then do a comparison to make sure that the leading edge isn't at the line... if it is past the line either stop movement or reverse the direction with the proper exit angle, momentum, and kinetic energy.

jlm699 320 Veteran Poster
>>> md = {}
>>> md['a'] = [1,2,3,4]
>>> md['h'] = (1,2)
>>> md['t'] = {'first':[9,8,7], 'sec':(1,2,3,4), 'h':'foobar'}
>>> md
{'a': [1, 2, 3, 4], 'h': (1, 2), 't': {'h': 'foobar', 'sec': (1, 2, 3, 4), 'first': [9, 8, 7]}}
>>>

Is that what you mean by multiple values from a dictionary?

jlm699 320 Veteran Poster

You bind an event to intercept the maximize event and call an event.veto()

jlm699 320 Veteran Poster
import math

for line in inp:
    myList = line.split()
    prev_i = None
    for i in myList:
        if not prev_i:
            continue
        dailyReturns = log(i.myList[1] - prev_i.myList[1])
    myList.append(dailyReturns)
    print myList

thats what I used, but I am getting an error saying that dailyReturns is not defined. )-:

You must consider that if myList is empty, dailyReturns will never be initialized (defined) so you will run into this problem. You should initialize dailyReturns to some arbitraty value (like 0) and then check to see if it has changed after the for i in myList loop. That way you only append it if it changed.

jlm699 320 Veteran Poster

Could your main thread keep a dynamic dictionary or list of the process ids ? Then you could perform some basic system commands to see which theads are still running and kill them if necessary?

jlm699 320 Veteran Poster

You can simply store the data of the previous line in a variable, so that on the following iteration you can calculate with the previous line and the current one.

jlm699 320 Veteran Poster

i want it to be able to load the program up and then be able to choose from addition as well as substraction like a button for each on start up or something.

What if you had a radio button choice. So that addition and subtraction could be chosen dynamically. The user could try a few additions, and then go to subtraction if they wanted.
If you want to force them to perform the same ops for the entirety of the game, then another option would be to have a message box pop up when the program starts with two buttons, addition or subtraction.

jlm699 320 Veteran Poster

Yes there are not only GUI toolkits for PYthon where you could make a very nice looking UI for the user, but python scripts can also simply be double-clicked to have them execute.

jlm699 320 Veteran Poster

I've used a module called paramiko to open a tunnel into another machine and execute commands remotely. It worked very nicely.

jlm699 320 Veteran Poster

Before your for loop you should initialize a5 and a6 as ''. Then within your loop instead of a5 = or a6 = you should use += to concatenate.

jlm699 320 Veteran Poster

if you can type exactly that command into your command window, then os.system() with *exactly* that command will work.

What doesn't work about it? Are you getting an error?

jlm699 320 Veteran Poster

What have you tried so far? Give us what you've already done and we can help you along. However we cannot simply do this for you because then you wouldn't learn anything.

jlm699 320 Veteran Poster

First, you need to use code tags on your code to make it readable and not lose your inentation.

Your line for (first, second) in pairs: is along with your error suggesting that pairs is being passed in as an integer.

When you provide an example code it would help if it is an actual example that can be run to demonstrate your dilemma. Otherwise we are left to guess at best, which is all we can do here since we can't see what you're passing to this function or what the context of your program is like.

jlm699 320 Veteran Poster

When you are calling wx.DirPickerCtrl( ) simply place the size that you want in the initialization like so: wx.DirPickerCtrl( self, -1, '', 'My Dir Picker', size = (a, b) ) where a and b are the desired dimensions.

You could also set the size after the fact with my_picker.SetSize( (a, b) ) where once again a and b are the desired dimensions.

jlm699 320 Veteran Poster
>>> usr_inp = eval( raw_input ('Enter a number: ') )
Enter a number: 5.78
>>> usr_inp
5.7800000000000002
>>> usr_inp = eval( raw_input ('Enter a number: ') )
Enter a number: 14e-5
>>> usr_inp
0.00013999999999999999
>>>

You can use the eval() method to convert your raw_input (saved as a string) to int or float. You should also work into your code a check after that input to make sure that the user did not enter a string, as that will mess up your "maths" as you put it.
A simple try: except: clause wrapping your maths should do it.

jlm699 320 Veteran Poster

I am getting errors such as False is not defined.
When I made it try returning a counter in the modules that called it I get the error that the counter is not defined.

False is a reserved keyword in Python. Make sure you are capitalizing the F in False however.
If you are using a variable inside the function, make sure you return it and capture it outside the function as following:

>>> bool_list = [True, True, 1, 'Hi', False, 0, '']
>>> len( bool_list )
7
>>> def retFalseIndx( list ):
...     my_counter = 0
...     for item in list:
...         if not item:
...             return my_counter
...         else:
...             my_counter += 1
...     
>>> retFalseIndx( bool_list )
4
>>> ret = retFalseIndx( bool_list )
>>> ret
4
>>>
jlm699 320 Veteran Poster

yIntercept = y1 - (((y2 - y1)/(x2 - x1))(x1))

Yes, Python is not a scientific calculator so it does not know that (x-5)(x-4) has an assumed multiplication between parenthesis. You will need to be more specific so change your line to

yIntercept = y1 - ( ( ( y2 - y1 ) / ( x2 - x1 ) ) * ( x1 ) )
jlm699 320 Veteran Poster

That interface looks very nice!

wxPython is something that will allow you to make stand-alone programs, however it would be pretty difficult to come up with an interface as kid-friendly or inviting as the one that you've already created there.

I've unfortunately never used Fireworks, however I'd be glad to help in any way possible (as I'm sure the rest of this community of experts would). So don't be shy about asking for more help!

jlm699 320 Veteran Poster

So you want each program to run on it's own pipe? As long as you're in a *nix environment use fork()

jlm699 320 Veteran Poster

If your open() call is "not working" perhaps you are mistaken with which working directory you're using. Try a simple os.getcwd() call to see where the files are being created.

jlm699 320 Veteran Poster

You could simply change the password in the script and then run main() again.

jlm699 320 Veteran Poster

Lo siento mi amigo, it's StringIO... sometimes I type faster than my brain can process words. :\

jlm699 320 Veteran Poster

yep exactly, if they input a negative number it will return differentiate that form a positive number.
Also thanks alot for what you have given me.

>>> li = [ 1, -2, 2.3, 't', -5.3e5, -0.1, 4e-5, 'hey!' ]
>>> for item in li:
...     test = str(item)
...     if test == item:
...         print item, 'String!'
...     else:
...         if item < 0:
...             print item, 'Not string... negative!'
...         else:
...             print item, 'Not string... positive!'
...     
1 Not string... positive!
-2 Not string... negative!
2.3 Not string... positive!
t String!
-530000.0 Not string... negative!
-0.1 Not string... negative!
4e-005 Not string... positive!
hey! String!
>>>

Simply check if the number is less than zero to determine if it is negative.
Just remember to do this only after you've verified that the item is not a string or else you will run into some strange results.

jlm699 320 Veteran Poster

hi guys,when i run my program which contains the following portion of code in the mainloop

clock=pygame.time.Clock()
      while True:
          sound1.play()
          clock.tick(60)
          pKeys = pygame.key.get_pressed()
          Eves=pygame.event.get()
          villian.face()
          villian.hert()
          if Eves[KEYDOWN] and pKeys[K_UP]:
              hero.moveup()
          if Eves[KEYUP] and pKeys[K_UP]:
              hero.gravity()
          if Eves[KEYDOWN] and pKeys[K_DOWN]:
              hero.movedown()
          if Eves[KEYDOWN] and pKeys[K_RIGHT]:
              hero.forward()
          if Eves[KEYDOWN] and pKeys[K_LEFT]:
              hero.back()
          if Eves[KEYDOWN] and pKeys[97]:
              sound.play()
              hero.reShape()
          if Eves[KEYUP] and pKeys[97]:
              hero.Shape()
          if Eves[KEYDOWN] and pKeys[115]:
              hero.Kick()
          if Eves[0]:
              pygame.quit()
              raise SystemExit()
          allsprites.update()
          screen.blit(background,(0,0))
          allsprites.draw(screen)
          pygame.display.flip()
          time.sleep(1/30)

List index is out of range. You are not using Eves and pKeys correctly.
Can you post how you're initializing you game space for curiosity's sake?

jlm699 320 Veteran Poster

Sorry, double post :(

jlm699 320 Veteran Poster
fin = open ('input.bin')
fout = open ('output.bin')
fin.readline()

x = fin.readlines (1)
str (x)

open( file_name ) defaults to read mode. You want open( file_name, 'w' ) for your output file so that you may write to it.
This first part is moving the file cursor. Are you sure you want to do this?
The first fin.readline() does not store the line anywhere.
The x = fin.readlines(1) already reads in a string, so saying str(x) isn't doing anything... (especially since you're not storing the result of str(x) ).

for row in fin:
    print open ("input.bin", "r")

What? You are iterating over each line of your input file here. But on each iteration you are reopening "input.bin" for reading?

for line in open ("input.bin", "r"):
    print output.txt,

fout = open ("output.txt", "w")

Now you are opening your input file once more, not storing the file handler but still iterating over it. On each iteration you're trying to print output.txt .... this should be throwing an error since you never created any thing called output, especially an output with an attribute txt.
Then at the end you're simply opening the file "output.txt" for writing and not writing anything to it.
I don't believe that your program will even run.
File reading and writing should be done something like this:

fh = open('input.bin', 'r')
fo = open('output.txt', 'w')

for line in fh:
    # do something to line here, storing to another variable …
jlm699 320 Veteran Poster

There are a few possibilities I can think of, but probably the most straight forward:

>>> li = [ 1, 2.3, 4e-5, 'hey!' ]
>>> for item in li:
...     test = str(item)
...     if test == item:
...         print item, 'String!'
...     else:
...         print item, 'Not String!'
...     
1 Not String!
2.3 Not String!
4e-005 Not String!
hey! String!
>>>

Now when you say restrict this to positive numbers, do you mean:
If Input is not <a positive number>:
perform action

vegaseat commented: Good example +8
jlm699 320 Veteran Poster

I'm not positive about this but I would assume that some of the time is consumed in the buffering of the file write process.

Perhaps in stead of an open file handle you could try an IOString, which after the operation is complete you could write to file in one chunk?

jlm699 320 Veteran Poster

Thanks alot! hope you don't mind if I take a little from both of your guys code and change it a little bit. and the reason I had the break in there was cause I thought I needed to break the first condition before I put another one....but as I understand now the first condition will only run if the condition is true then the next one if it is false? if that is still wrong maybe you could explain it.

As far as if, elif, else statements are concerned, Python evaluates them one by one.
Example:

if a1:
    # Perform Action 1
elif a2:
    # Perform Action 2
else:
    # Perform Default Action
print 'End of if/else structure.. returning to main code'

If the condition a1 is true, action 1 will be performed and then processing will return to the print statement.
If a1 is not true, Python will evaluate a2. If a2 is true, action 2 will be performed. (Keep in mind that you can have as many elif conditions as you want.) Once action 2 is complete, processing will return to the print statement.
If none of the if or elif statements are true and an else clause exists (such as in this case), the default action will be performed. (You can always exclude this else clause and just not have anything happen unless one of your conditions is true).

I hope I've explained this concept well, but if not I urge …

jlm699 320 Veteran Poster

Sorry, I misunderstood. The only way I know of is to pass it as an arg to the script being executed. Something like:
subprocess.call( 'program_name m', shell=True)
The program being executed would have to examine sys.argv to find it.

This would not allow him to use the class members or methods as program_name m in the shell would not make anysense and the argv[1] would simply contain a character m.

Perhaps you could pickle the class, pass the name of the pickled file via the above method, and then unpickle in the target script?

Refer to pickling docs for more info.

jlm699 320 Veteran Poster

Building off of paulthom12345's code...

import random, sys

words = ['sprinkles', 'computer', 'mouse', 'shooter', 'edge', 'guard', 'python']
myword = random.choice(words)
guesses = "aeiou"
turns = 10

print "Do you want to play a game of hangman?"
play = raw_input('Answer (y) yes or (n) no:')
if play == 'y':
    print 'Let\'s begin'
    while turns:
        blank_flag = False
        turns-=1
        print ""
        for letter in myword:
            if letter in guesses:
                sys.stdout.write( letter )
            else:
                blank_flag = True
                sys.stdout.write( '_' )
        sys.stdout.write('\n')
        sys.stdout.flush()
        if not blank_flag:
            print "You've won!!!  AMAZING!"
            break
        usr_inp = raw_input( "Enter your guess (only one letter): " )
        if len(usr_inp) > 1:
            print "You've forfeited a turn by entering more than one letter."
        else:
            guesses += usr_inp
    if not turns:
        print "GAME OVER!"
else:
    print 'Good-Bye.'
jlm699 320 Veteran Poster

I think that you would benefit from implementing this game in wxPython.

By doing this, you can come up with a nice, clean interface to work with and you can very easily implement a splash screen as well.

jlm699 320 Veteran Poster

A few things to consider further. If an incorrect difficulty or operation is input, how would you handle it? As your code stands it would crash. You should work in some error handling first to make sure that the user is playing 'nice'.

Try googling Python's try, except concepts to see how you could add in some elaborate error handling. For example, if instead of a number the user entered letters for an answer. The program would throw a ValueError exception, so you could wrap the answer = raw_input() statement with a try:, except 'ValueError': statement that would warn the user that only numerical answers are allowed, and then you could subtract one from the count so that they can't bypass a turn by putting in invalid answers.

Further more, without having an else: on your operation and difficulty if statements, you are inviting the user to crash your program. If they typed in 'R' for an operation just to be a brat your program would never ask for or assign any value to the difficulty parameter. As soon as your loop begins your program would crash with a NameError exception complaining that 'difficulty' is not defined.

On the other hand if they input bogus values for difficulty the rand_range would never be able to be determined and the program would again crash.

jlm699 320 Veteran Poster

Here are a few modifications I made:

name = raw_input("\t\t\tPlease Enter Your Name: ")
print
print "\t\t\t\tHello", name
print "\t\t\tWelcome to my Mathematics Game"

# Selecting the operation of Addition and Substraction followed by the difficulty
print
operation = str(raw_input("\t\t\tAddition (A) or Substraction (S)"))
if operation == "A" or operation == "a":
    my_op = 'Add'
    difficulty = str(raw_input("\tSelect a difficulty - Easy (E)(1-100), Medium (M) (1-200) or Hard (H) (1-500)"))
    print
    print "Addition"
    print '** ** **'
    print
elif operation == "S" or operation == "s":
    my_op = 'Sub'
    difficulty = str(raw_input("\tSelect a difficulty - Easy (E)(1-100), Medium (M) (1-200) or Hard (H) (1-500)"))
    print
    print "Subtraction"
    print '** ** ** **'
    print

if difficulty == "Easy" or difficulty == "easy" or difficulty == "E" or difficulty == "e":
    my_rand_range = 100
elif difficulty == "Medium" or difficulty == "medium" or difficulty == "M" or difficulty == "m":
    my_rand_range = 200
elif difficulty == "Hard" or difficulty == "hard" or difficulty == "H" or difficulty == "h":
    my_rand_range = 500

# Amount of questions asked (10) and randomisation of numbers
import random
counter = 0
while counter < 10:
    counter = counter +1

    # Difficulty - Easy, Medium or Hard
    number1 = random.randrange( my_rand_range ) + 1
    number2 = random.randrange( my_rand_range ) + 1

    # Addition Calculations
    if my_op == 'Add':
        print number1, "+", number2, "="
    # Substraction Calculations
    elif my_op == 'Sub':
        print number1, "-", number2, "="

    # Input for answer
    answer = int(raw_input("Type in your answer: ")) …
jlm699 320 Veteran Poster
>>> '%e' % (5 * 0.00544)
'2.720000e-002'
>>> '%.2e' % (5 * 0.00544) ## This is the correct form of sci. notation *10^-2
'2.72e-002'
>>> 
>>> 0.0272 * 10**18  ## This is what your number was
27200000000000000.0

You see? Like I said, you were way off. That last one is 10^18

jlm699 320 Veteran Poster

You are mistaking sub/superscript for scientific/exponential notation (P.S. your scientific notation conversion is way off).

>>> '%e' % (5 * 0.00544)
'2.720000e-002'
>>> '%.2e' % (5 * 0.00544)
'2.72e-002'
>>>

That illustrates some text formatting in Python. If you'd like information check out this page on Formatting

jlm699 320 Veteran Poster

What I dont get is what these code blocks do:

def set_fname(self, fname):
        self._fname = fname

 def set_lname(self, lname):
        self._lname = lname

What exactly does the set_fname and set_lname do? and how come the self._fname and self._lname are inaccessible?

Those blocks of code reassign the value of _lname and _fname. self._fname and self._lname are not technically inaccessible, they are just simply hidden to the common user. If you typ

>>> p1 = Person('James', 'Matthews')
>>> p1
<__main__.Person instance at 0x01C84FD0>
>>> p1.fname()
'James'
>>> p1._fname
'James'
>>>

As you can see, I can still access those objects. However the helper function fname() makes it easier on the user.