woooee 814 Nearly a Posting Maven

The easiest to understand is to Use a function

def get_one_salary(ctr):
    while True:  ##infinite loop
        salary=raw_input("enter the salary #%d: " % (ctr+1))
        try:
            salary = float(salary)
            return salary
        except ValueError:
            print "could you please enter the correct salary? "

n = int(raw_input("enter the number of employee: "))
salary = []
for ctr in xrange(n):
    input_value = get_one_salary(ctr)
    salary.append(input_value)
print salary
woooee 814 Nearly a Posting Maven

That would be just a simple
1. compare the first number with the remaining (2 in this case)
2. swap the first and second number and do again

You would continue swapping if there were more digits. You have not included enough actual code to really comment on so it is difficult to move on from where your code starts. Note that the input "self.word" is not being used anywhere so whatever result you get it will not include the digits from the input. Also note that 123 and 321 are sometimes condsidered the same combination. Present a simple example in a few lines where you combine and swap and perhaps we can help more.

woooee 814 Nearly a Posting Maven

"Better" is in the eye of the beholder. The first rule is that the program does what it is supposed to.

def in_order(t):
    for ctr in range(1, len(t)):
        if t[ctr-1] > t[ctr]:
            return False
    return True

for t in ([1,2,2], ['b','a'], [3, 1, 5, 2, 4],
          ['d', 'a', 'c', 'b'], ['a', 'b', 'b', 'd', 'e', 'e', 'f', 'g']):
    print t, in_order(t)
woooee 814 Nearly a Posting Maven

This is backwards

pointsPossible+= totalPossibePoints

as totalPossiblePoints will always stay at zero and pointsPossible will be over-written on the next input through the loop. If you want to average then you also have to keep track of how many were entered so you can divide total by number entered. Also there is no course1, course2, etc. entered. As the courses are entered append them to a list and keep them that way. That is what lists are for Click Here

woooee 814 Nearly a Posting Maven

What does that mean and what do you want the program to do?

woooee 814 Nearly a Posting Maven

As a hint, the dictionary can only contain data from the file. Strings like"user" or "password" can not be used as keys or anywhere in the dictionary. Nor can anything else that is not from the file.

woooee 814 Nearly a Posting Maven

Combine the two if statements

    if (name in A['user']) and (code in A['password']):
            print("Successful Login")
    else:
            print("Username or Password Incorrect")
woooee 814 Nearly a Posting Maven

At the bottom of the list were Alaska, California and Hawaii. Don't know what that means. Maybe a lot of coastal water equals something.

woooee 814 Nearly a Posting Maven

The else statement only executes if the name is not correct, regardless of what the password is (name=correct & password=incorrect = nothing is printed). Note also that A['user'] and A[password'] will only contain the last value from the while loop, so you should print the dictionary to verify this.

woooee 814 Nearly a Posting Maven

Money is the root of good evil.

The quote actually is

For the love of money (greed) is a root of all kinds of evil.

Money is an inanimate object that can do, or cause, nothing.

woooee 814 Nearly a Posting Maven

Once again, lists are mutable (passed by reference) so global is unnecessary. Another example :

def print_row():
   print rowA

rowA = ['*', '*', '*', '*', '*', '*', '*', '*']
print_row()

for ctr in [1, 3, 5]:
   rowA[ctr] = "X"
print_row()
woooee 814 Nearly a Posting Maven

Lists are mutable, which means they can be used without global. The problem is possibly in the code you use to update the list; it truncates the list also. Run the code example below. You are asking questions that are in most tutorials so you should start with a tutorial instead of asking us to answer questions that every beginner should know. A place to start = tutorial on lists Click Here Python Wiki list of tutorials Click Here

rowA = ['*', '*', '*', '*', '*', '*', '*', '*']
seat=5
rowA[0:int(seat)] = ['X']  ## copies up to "seat" only
print "update 1", rowA 
#
# instead
rowA[0]="Y"
rowA[2]="X"
print "update 2", rowA
#
for ctr in range(0, 3):
    rowA[ctr] = "Z"
print "update 3", rowA
woooee 814 Nearly a Posting Maven

Do you want to search for a file name ending, "data" i.e. list of files, if not, state what you do want the program to do?? Now you do the same search [the result from input()] for each file name returned from os.listdir

    command_line = input('Enter the game you would like to search for: ')
    for data in os.listdir('/SNES/SNESRoms'):
        if command_line.endswith(extensions):
woooee 814 Nearly a Posting Maven

It appears that bayFails is a class instance

<class 'pandas.core.series.Series'>

and so can not be converted to a list. You will have to access the data within the class. Since we have no idea were bayFails comes from, the only advice would be to read the Pandas docs since extracting data would be rountinely done by many programmers (I would guess by using itertuples or iteritems).

woooee 814 Nearly a Posting Maven

As stated above, I would compare word to word instead of how you are doing it. Since the problem is obviously in the file, add "didn't" to the file or to the result of the read, and if it finds it this time then you know for sure that the file is the problem.

woooee 814 Nearly a Posting Maven

If finds "didn't" in the following test. Also, you do not strip the newline character(s) after reading the files, and because you use "in" instead of creating a dictionary or set of individual words and comparing word with word; the word "and" will be found, i.e. is in, when compared to the word "sandy"

#fullwords = open("Enwords.txt").read()
#contrwords = open("Encontract.txt").read()
fullwords=['accept', 'actually', 'again', 'ago', 'all', 'allow', 'already', 'always', 'and', 'another', 'apply', 'are', 'around', 'author', 'bang', 'be', 'believe', 'bible', 'big', 'billion', 'but', "can't", 'cannot', 'cause', 'caused', 'could', 'creation', 'description', 'do', 'does', "doesn't", 'exist', 'explained', 'for', 'genesis', 'god', 'have', 'he', 'here', 'i', 'if', 'in', 'incorrect', 'is', 'it', 'its', 'laws', 'likely', 'literally', 'malarky', 'mean', 'meant', 'most', 'no', 'not', 'of', 'okay', 'old', 'only', 'period', 'physics', 'put', 'responsible', 'say', 'simply', 'so', 'taken', 'that', 'the', 'then', 'there', 'think', 'this', 'those', 'thought', 'to', 'true', 'universe', 'way', 'what', 'which', 'wrong', 'years', 'you']
contrwords=["can't", "didn't", "doesn't"]
wordlist = []
nonwordlist = []
failedwords = []
string4 = "I have already explained this I thought. Okay here it is again. I beleive that the laws of physics apply to the universe and always have. Those laws do not allow the universe to be only 6000 years old. So the only way in which God could be responsible for the creation of the universe is if the bible is incorrect in its description of creation. That doesn't mean there is no God, but only that if he does exist, he is not the author of the bible if he meant …
woooee 814 Nearly a Posting Maven

Use a while loop to generate random numbers until a valid number occurs:
- Ships can't overlap --> keep track of the occupied squares in a list
- Ships must be within the gamegrid --> you can supply a range for rows and a range for columns
- Ships must be going down or across --> randomly choose 0 (across) or 1 (down) and then get a random number for column start or row start.

woooee 814 Nearly a Posting Maven

For starters, print the result/"word" for

for word in f:

Also, "data" has not been declared

   if i in data:

Read cities.txt and place the cities in a list or dictionary. Print this to make sure there is no white-space, etc. Then search for each of the cities in each of the records in master.txt (you will and to split each record into words). Post that code and ask for more help. Lists and File readlines()

woooee 814 Nearly a Posting Maven

I can't tell what your code looks like because it is not indented.

doubler is now f(2) = return g so that is removed and the value from doubler(5) gets assigned to y that is why you get the x*y value and not "function g at blah blah" which is what the return g would print. Add some print statements

def f(x):
    print " f entered", x
    def g(y):
        print "g executed", y
        return x * y
     return g

doubler = f(2)
print doubler(5)


## if you want to look at it like this: doubler as f(2) =
x = 2
def g(y):
    return x * y
woooee 814 Nearly a Posting Maven

Take a look at the first code example Click Here especially how text is assigned so it appears on the button.

woooee 814 Nearly a Posting Maven

You have to capture the return from split() and iterate over each one. Using split eliminates the split characters so you can prepend them back or adjust the slice numbers by -2 as I have done below.

test_data=\
"7e001090007d33a200408b2e0c2db70100160057637e001090007d33a2004089e04a569d010016003885"

if test_data[0:2] == '7e':
    data_split=test_data.split('7e')
    print data_split
    for Data_in in data_split:
        print "=========================="
        print "Found Packet: " + Data_in

        begin=4
        if Data_in[begin:begin+2] == '90' and
           len(Data_in) > 36:
            print "Packet Type = ZgBee RX Packet"
            AH = Data_in [begin+6:begin+14]
            AL = Data_in [begin+14:begin+22]
            print "Device Address = ", AH, AL
            TH = Data_in [begin+30:begin+32]
            TL = Data_in [begin+34:begin+36]
            THc = int(TH, 16)
            TLc = int(TL, 16)
            print "Temperature: %d.%d" % (THc, TLc)
            print "=======================\n"
woooee 814 Nearly a Posting Maven

The "in" operater is used to look up a key in a dictionary --> dictionary tutorial http://www.greenteapress.com/thinkpython/html/thinkpython012.html Note rrashkin's advice above and store each item in a string or as an element of a sub-list so you can access them individually as (s)he has done. You should not post real phone numbers or e-mail addresses on a public forum.

key = input('Enter a contact information here: ')
if key in ab:
    print (ab[key])
else:
    print("name not found")
woooee 814 Nearly a Posting Maven

In order to save volunteers here from wasting time, this thread has been cross-posted on all of the other forums groups, Active State, python-list, python-forum, devshed, dreamincode, and maybe others, so decide for yourself if you want to spend any time on this or not.

woooee 814 Nearly a Posting Maven

As stated above, I would suggest you add a print statment (after the line quoted below) and compare the output to what it should be, calculated by hand. If it does not come out then break each part down and compare, i.e calculate minutes only and compare and subtract from what total milli-seconds should be if correct giving seconds and milli-seconds remaining, then you can compare seconds and do the same and then milli-seconds (you are dividing and multiplying by 1000 not 100 so milli-second is correct).

hundredths = int(60000 * minutes + 1000 * seconds + 0.001 * centesimos)

So the following, and obviously milliseconds is the problem but you have to get to what they should be verses what they are in some way.

    minutes = int(mins1) + int(mins2)

    ## for the 2nd test ('03:00:02', '02:00:00') = 2:30:01 as median
    ## = how many milliseconds should your program have
woooee 814 Nearly a Posting Maven

00:02:500 # should be 00:02:30

A half a second is 500 milliseconds so 2:500 (== 2.5) is correct

00:03:0 # should be 00:03:30

We don't know what code you are using so how do you expect someone to help? Take vegaseat's suggestion and print the variables total_seconds, millisec, minutes, micro_x, and seconds on the line following each calculation to determine where the error is occurring.

Also, you can use

t1 = lap1.split(":") 

def convert_to_int(lap):
    t = lap.split(":")
    return int(t[0]), int(t[1]), int(t[2])

def lap_average(lap1, lap2):
    print convert_to_int(lap1)
    print convert_to_int(lap2)

lap_average('03:40:00', '05:20:00') 

Print the "t" tuple if you don't know what it will contain.

woooee 814 Nearly a Posting Maven

Did you try that? What happened?

woooee 814 Nearly a Posting Maven
cur.execute("""INSERT INTO TableX (itemID, sortID)
VALUES (%s, %s)""",
[plist[sid], lastQ[0] ] )

What type is plist[sid]? If it is a string you now have to cast it to a byte in Python3.x (encode it), possibly the cause is something in Python3.3.

woooee 814 Nearly a Posting Maven

For starters, you have declared names to be a tuple containing one list so you would access it with
e=names[i][0]. But anyway, your code cleaned up a bit.

names=['Paul','Tim','Fred']
for nm in names:
    print nm

while True:  ## infinite loop until break is called
    a = raw_input("Choose name to be deleted:\n")
    if a in names:
        names.remove(a)
        print "name deleted"
        break
    else:
        print "No such name!Please Re-enter!"
woooee 814 Nearly a Posting Maven

Hi Guys,

Please be gentle with me as im a complete n00b. My favorite language is actually Java which im learning at Uni at the moment. However to throw a spanner in the works they have switched us over to Python, as well as learning Java. My mind has been completely boggled. I just need to understand this for the moment and Im hoping someone out there will be kind enough to help me. I have created a list with names in, and i want to delete what ever name i wish to do so. So i have put a for loop in there. Now I can delete any name WITHOUT the if-statement in there but when i put if statements in there so set either condition to be true or false it doesnt do what i want it to. here is my code:

Any ideas? Thanks :-)

   names=(['Paul','Tim','Fred'])
   def main():
       for i in range(len(names)):
       e=names[i]
           print names
           print
           a = raw_input("Choose name to be deleted:\n")
       if(a==e)
           names.remove(a)
           print "name deleted"
       if(a!=e):
           print "No such name!Please Re-enter!"
woooee 814 Nearly a Posting Maven

Spaghetti is the plural form of the word spaghetto, an Italian word which means "thin string" or "twine".

woooee 814 Nearly a Posting Maven

The Air Force has spent more than $1 million to help develop a small and versatile robot dragonfly. But in a move to raise funds for the Dragonfly, the developers are offering the public the chance to own their own flying robot Dragonfly for $119. http://www.indiegogo.com/robotdragonfly

“This means you can do amazing aerial photography, spy on people, secure your house or use it as the next-gen gaming platform,” says Emanuel Jones, co-founder of TechJect, in a promotional video for the project on the Indiegogo website.

woooee 814 Nearly a Posting Maven

And you can do this more compactly

BR1 = []
for ctr in range(2, 8):
    BR1.append(Resistance[ctr]

## replaces
BR1 = []
b1 = Resistance[2]
b2 = Resistance[3]
b3 = Resistance[4]
b4 = Resistance[5]
b5 = Resistance[6]
b6 = Resistance[7]
BR1.append(b1)
BR1.append(b2)
BR1.append(b3)
BR1.append(b4)
BR1.append(b5)
BR1.append(b6)
woooee 814 Nearly a Posting Maven

What happens when there is a tie? When X wins, the program still asks O for a square. What happens if someone enters the letter A?

woooee 814 Nearly a Posting Maven

The next "end of the world"

The “Prophet Gabriel” supposedly told the Sword of God Brotherhood that the “dying time” will come in 2017.

September 28th, 2020. George Madray predicted that on this date a Yom Kippur Parousia will take place in 2020 = End of the world.

The Year 4,500,000,000 AD is when the sun is predicted to burn up. The sun will swell into a red giant star.

woooee 814 Nearly a Posting Maven

I would strongly suggest that you take another look at the encode function.

woooee 814 Nearly a Posting Maven

You should use a dictionary to store the e-mails in a dictionary if it is not already there. If it is there, then it is a duplicate. I would suggest that you store the original record and the duplicate because they may be different and you would want to keep the correct one, not the first one found.

woooee 814 Nearly a Posting Maven

Your original problem was a missing closing parens in this statement

self.button.append(Button(frame, text=str(i), width=5, command=lambda i=i:self.numberPressed(i))

In the future, remember to check the statement before the one indicated for syntax errors as it happens a lot.

woooee 814 Nearly a Posting Maven

You define text_list to point to the same block of memory as final.

final = text_list

If you want want a copy, use copy or deepcopy

In line 107 you append final to decode_list multiple times. Break the program down into small functions that you can test individually, as fixing one error will probably just lead to many more that you can not find because you can not test each group of code the way it is now. Like Tony, 157 lines of code is more than I care to wade through so post back if there are any other problems that you can not fix.

 decode_list.append(''.join( final ))
woooee 814 Nearly a Posting Maven

That is because "! =" does not equal "!=" (original code copied for reference).

    #-------------------------------------------------------------------------------
    # Name:        module1
    # Purpose:
    #
    # Author:      User
    #
    # Created:     18/12/2012
    # Copyright:   (c) User 2012
    # Licence:     <your licence>
    #-------------------------------------------------------------------------------
    #tictactoe board

    import random

    board = [0,1,2,
             3,4,5,
             6,7,8]

    def game():
        print (board[0],'|',board[1],'|',board[2])
        print ('----------')
        print (board[3],'|',board[4],'|',board[5])
        print ('----------')
        print (board[6],'|',board[7],'|',board[8])

    def check(char, spot1, spot2, spot3):
        if board[spot1] == char and board[spot2] == char and board[spot3] == char:
            return True
    def checkAll (char):
        if check (char, 0, 1, 2):
            return True
        if check (char, 1, 4, 7):
            return True
        if check (char, 2, 5, 8):
            return True

        if check (char, 6, 7, 8):
            return True
        if check (char, 3, 4, 5):
            return True
        if check (char, 0, 1, 2):
            return True

        if check (char, 2, 4, 6):
            return True
        if check (char, 0, 4, 8):
            return True
    while True:
        p1 = input("Player 1, where do you want to place your marker?")
        p1 = int(p1)
        if str(board[p1]) ! = 'x' and str(board[p1]) ! = 'o':
            board[p1] = 'x'

    if checkAll('x') == True:
                print "Player 1 wins!"
                break
            break

    while True:
            p2 = input("Player 2, where would you like to place your marker?")
            p2 = int(p2)
            if str(board[p2]) ! = 'x' and str(board[p2]) ! = 'o':
                str(board[p2]) = 'o'

                if checkAll('o') == True:
                    print "Player 2 wins!"
                    break
            break

I made some additional changes to help you out and reduced the code in checkAll() by using a list, but the program …

woooee 814 Nearly a Posting Maven

You have made the classic mistake of including even numbers = testing twice as many numbers. Start out with i=3 and add two on each pass.

woooee 814 Nearly a Posting Maven

For starters, you can use a loop

import os

for path in [["x"], 
             ["x", "y"], 
             ["x", "y", "z"]]:
    pathname = "pathname"
    for next_path in path:
        pathname = os.path.join(pathname, next_path)
    print pathname
woooee 814 Nearly a Posting Maven

And this page says to return "break" which seems to work.

class TestSearch():
    def __init__(self):
        # Keyword Search box (user inputs keywords)
        root = Tk()
        Label(root, text="Search box: Enter keywords and press 'Enter'").pack()
        self.search_box=Text(root, height=1,width=48, padx=5,wrap='word',
                        font=('helvetica','12','bold'))
        self.search_box.bind('<Return>', self.handle_event)
        self.search_box.pack(fill='x', expand='yes',pady=2)
        self.search_box.focus_set()

        root.mainloop() 

    # Keywords Search event handler.
    def handle_event(self, event):
            search_term = self.search_box.get(1.0, END) 
            search_term = search_term.strip()
            print "adjusted", search_term
            return "break"

TS=TestSearch()
woooee 814 Nearly a Posting Maven

So we are spending our time on simple toggles huh. This uses a list so the function has access to the previous setting. I was too lazy to create a class with an instance variable.

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def toggle():
    index_dict={"True": "False", "False": "True"}
    index[0] = index_dict[index[0]]
    t_btn['text'] = index[0]

root = tk.Tk()
index=["True"]
t_btn = tk.Button(text=index[0], width=12, command=toggle)
t_btn.pack(pady=5)

root.mainloop()
woooee 814 Nearly a Posting Maven

You check for "KeyPress" and the return happens after that so you don't catch it. The solution is to use "KeyRelease". Also, to use your program as is, you would have to delete the contents of the box on the first keystroke so it only contains the search term. I have used a label instead for convenience. Most times, a button is provided that the user clicks and is bound to the callback to avoid this problem.

class TestSearch():
    def __init__(self):
        # Keyword Search box (user inputs keywords)
        root = Tk()
        Label(root, text="Search box: Enter keywords and press 'Enter'").pack()
        self.search_box=Text(root, height=1,width=48, padx=5,wrap='word',
                        font=('helvetica','12','bold'))
#        search_box.insert(END,"Search box: Enter keywords and press 'Enter'")
#        self.search_box.bind('<Key>',self.handle_event)
        self.search_box.bind('<KeyRelease>', self.handle_event)
        self.search_box.pack(fill='x', expand='yes',pady=2)
        self.search_box.focus_set()
        root.mainloop() 

    # Keywords Search event handler.
    def handle_event(self, event):
        eventDict={'2':'KeyPress','3':'KeyRelease'}
        if event.type=='3' and event.keysym=='Return' :
            print "Event"
            search_term = self.search_box.get(1.0, END) 
            print search_term
            search_term = search_term.strip()
            print "adjusted", search_term
            self.search_box.delete(1.0, END) 
            self.search_box.insert(END, search_term)

TS=TestSearch()
woooee 814 Nearly a Posting Maven

The problem is explained by the comments in the code. It is a fundamental question about the method call...every time I try text_box_name.tk_textBackspace() I get the TclError message. That's why I asked the question without the code...

# When user enters a search word in the +search_box' text widget and presses
# "Enter" on the keyboard, the search word is no longer visible because
# of the new line at the end of the string caused by pressing "enter".
# Hitting backspace on the keyboard brings the keyword back into view,
# so I tried to use the method tk_textBackspace to simulate that and remove
# the 'new line' (so the entry in list_box would again be visible.)

from tkinter import *
root = Tk()

# Keyword Search box (user inputs keywords)
search_box=Text(root, height=1,width=48, padx=5,wrap='word',
font=('helvetica','12','bold'))
search_box.insert(END,"Search box: Enter keywords and press 'Enter'")

# Keywords Search event handler.
def handle_event(event):
    eventDict={'2':'KeyPress','3':'KeyRelease'}
    if event.type=='2' and event.keysym=='Return' :

        search_box.tk_textBackspace()
# the line above doesn't even get to execute...generates the error message:
# _tkinter.TclError: invalid command name "tk_textBackspace"
# but the library for text widget has that as a valid method...
# hence the question.

    pass # the rest of the routine's code goes here

## the code below is my workaround (executes on "enter" key release)
## if event.type == '3' and event.keysym == 'Return':
## search_box.see(0.0) # Make start of Keywords string visible
## return

search_box.bind('<Key>',handle_event)
search_box.bind('<KeyRelease>', handle_event)
search_box.pack(fill='x', expand='yes',pady=2)
mainloop() 
woooee 814 Nearly a Posting Maven

Take check() out from under NAC()--capture the return from a function

def check(player):
    if player == Grid[0][0] == Grid[0][1] == Grid[0][2]:
        print("%s wins!", (player))
        return True

Please read the Python Style Guide to make your code readable. Functions and variable names are lower case with underscores.

You have redundant code in the if statements

if YourGo == '7':
    Grid[0][0] = 'X'
elif YourGo == '8':
    Grid[0][1] = 'X' #Player one's turn

DisplayGrid()
check()

Also, you can map the squares to the numbers and use a for loop or simpify like this

if YourGo == '7':
    Grid[0][0] = 'X'
elif YourGo == '8':
    Grid[0][1] = 'X'
elif YourGo == '9':
    Grid[0][2] = 'X'

#------------------------------------
# replace with
this_row ['7', '8', '9']:
if YourGo in this_row:
    row = 0
    col = this_row.index(YourGo)

Grid[row][col] = 'X'

Finally, turn the above into a function and send the player to it so you don't test separately for X and O, i.e. the same code twice.

aVar++ commented: Helped me alot! +0
woooee 814 Nearly a Posting Maven

Anything that involves a dozen. Mmmmm doughnuts.

woooee 814 Nearly a Posting Maven

We've all been there.

woooee 814 Nearly a Posting Maven

How else would you program remove-the-labels-only-and-keep-everything-else, except on an individual basis. The way you have it set up you would have to keep track of the class instance for Slot as well as each label belongs to a separate class instance.

self.s=Slot(self.root,self.canvas,self.photolist[0],10,10)
some_list.append(self.s.l)
woooee 814 Nearly a Posting Maven

but I'm not really sure where to go next

That is too vague to understand what you mean. Draw the whole thing out on paper, breaking it into steps. Also, add some print statements to help with debugging. You are using
for i in letter():
for example and the variable "letter" has not been declared so your program will not run as is. If you do not know what to do, it generally means that you do not know enough about Python to solve this particular problem and should pick something else.