woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

Try

if userInput in ['r', 'R']:
# ----- or -----
if userInput.lower() == "r":
woooee 814 Nearly a Posting Maven

Some print statements should help:

for i in number[1]:
    print "test i =", i
    if int(i) >= 5:
        print "     deleting", number[0]
        del number[0]
        print "     deleting", number[0]
        del number[0]
        print "     deleting", number[0]
        del number[0]
    print "     after, number =", number, "len(number) =", len(number)

And __definitely__ test this with numbers greater than 10.

woooee 814 Nearly a Posting Maven

It is a courtesy to others readers to mark the thread as "Solved" when it is finished so volunteers don't waste their time reading threads that are finished. Sometimes the posts don't end there but it is something to keep in mind.

woooee 814 Nearly a Posting Maven

n yea... m new to python !!

This is not high school nor does anyone want to become a personal assistant for the lazy http://tinyurl.com/6eavfzu

woooee 814 Nearly a Posting Maven

And please do a reasonable number of tests of your code before posting. This is a truncated version of the function to point out the error:

def isprime(n):
    for ctr in range(2,n):  ## do not use 'i', 'l', 'O' as they can look like numbers
        if n%ctr==0:
            return 'Not a prime number',ctr,'is a factor'
        else:
            return 'Prime number'

print isprime(9)  ## 9 is not prime-->3**2
woooee 814 Nearly a Posting Maven

You have to retrieve and store the RadioButton object. This code stores the grid() object:

#
Radiobutton(canvas, variable=xy, value=x,command=self.move).grid(row=row,column=column)
#
# instead use
#
self.rb =Radiobutton(canvas, variable=xy, value=x,command=self.move, image=xxx.)
self.rb.grid(row=row,column=column)  # using "row" and "column" as names is confusing
#
# and then
self.rb.configure(image=yyy)

For configure options see http://www.astro.princeton.edu/~rhl/Tcl-Tk_docs/tk/button.n.html

woooee 814 Nearly a Posting Maven

Try it the other way around?

inCur = gp.SearchCursor(myFeatureClass2,'COLLECTED_BY = "%s"' % (str(Name)), \
                                         "", "", "DATE_COLLECTED A")

Generally, the name is also stored as "obrien" so you can find O'Brien, O'brien, Obrien, etc. I don't know if this is possible here or not.

woooee 814 Nearly a Posting Maven

What does the function normDistProb return? The first attempt to debug this should be to print it

for i in range(0,12):
    listProbFog.append(normDistProb(dayValues[i], fogAve[i], fogVar[i]))
    print normDistProb(dayValues[i], fogAve[i], fogVar[i])
    print listProbFog
    # the other lists are just extra cruft until you get this problem solved
bumsfeld commented: agree +7
woooee 814 Nearly a Posting Maven

I tried using the ordered dict, but its still giving the memory error

That is too vague to be of any value. Post the actual error. Also this line
if tuple(line[:2]) in od.keys():
should just be
if tuple(line[:2]) in od:

".keys" returns a list of the keys which means there is double the amount of memory for the number of keys. If you can not do this with the memory available, then you want to use an SQLite database on disk instead.

woooee 814 Nearly a Posting Maven

Also, form the habit of using a list instead of if/elif. It is more straightforward as all of the conditions are on one line. And verb[-2:] is just shorthand for verb[-2:len(verb)], just as verb[:-2] is shorthand for verb[0:-2].

verb = input("Write the verb here: ")
if verb[-2:] in ['ar', 'er', 'ir']:
#
else:
#
# or
found = False
for ending in ['ar', 'er', 'ir']:
    if verb.endswith(ending):
        found = True
Gribouillis commented: good pattern +6
woooee 814 Nearly a Posting Maven

A second dictionary is not required. Create a tuple containing item1 and item2 and look up in the dictionary. If found, you have a match. If you want to keep the keys in the same order as the file, use the ordered dictionary. For Python 2.7 it is in "collections".

woooee 814 Nearly a Posting Maven

"while True" serves no purpose in this program.

woooee 814 Nearly a Posting Maven

You never exit the "while True" so it is an infinite loop. Once you eliminate that, you should be able to print the final word_list list which will be a series of numbers. Sort the list and count each of the sequences of the same number. You should also get an error on this statement
text = text.join().strip()
What are you trying to do? Take a look at this doc to see what join() does http://docs.python.org/library/stdtypes.html

woooee 814 Nearly a Posting Maven

You should state what it is you want to do. No offense but there are other solutions and perhaps someone here can come up with a workable solution. Generally you would use (although I can't really understand what you are asking):

class myClass:
    def __init__(self, methodName="This is the result"):
        self.methodName = methodName

MC = myClass()
print MC.methodName

If you want to associate 2 or more items, a dictionary is generally used. But again, if you state the problem, there will probably be better solutions presented.

woooee 814 Nearly a Posting Maven

1) change the button sizes to be all the same size (buttons are labeled decrease, surrender, remain, etc...)

You can use width and height on buttons the same way as done with Text in your program. Reference sites here and here

from Tkinter import *

class PreferencesWindow(object):

    def __init__(self, master):
        master.geometry("200x100+10+10")

        row = 1
        self.preferences_button = Button(master, text='Preferences', \
            width=9, height=2, \
            command=self.edit_preferences)
        self.preferences_button.grid(row=row, column=0)

        self.make_report_button = Button(master, text='Make reports', \
            width=7, height=5, \
            command=self.generate_reports)
        self.make_report_button.grid(row=row, column=1)

    def edit_preferences(self):
        print "preferences callback"

    def generate_reports(self):
        print "generate_reports callback"


if __name__ == "__main__":
    root = Tk()
    app = PreferencesWindow(root)

    root.mainloop()
woooee 814 Nearly a Posting Maven

Take a look at the "buttons" function in this code, as it should help with the StringVar, and with creating several buttons using a for loop. In this case the buttons are stored in a dictionary.

from Tkinter import *
from functools import partial

class TicTacToe:
   def __init__(self, top):
      self.top = top
      self.button_dic = {}     ## pointer to buttons and StringVar()
      self.X_O_dict = {"X":[], "O":[]}  ## list of "X" and "O" moves
      self.top.title('Buttons TicTacToe Test')
      self.top_frame = Frame(self.top, width =500, height=500)
      self.buttons()
      self.top_frame.grid(row=0, column=1)

      exit = Button(self.top_frame, text='Exit', \
             command=self.top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   ##-------------------------------------------------------------------         
   def buttons(self):
      """ create 9 buttons, a 3x3 grid
      """
      b_row=1
      b_col=0
      for j in range(1, 10):
         ## point the button number to a Tkinter StringVar()
         self.button_dic[j] = StringVar()
         ## set the StringVar() to the button number
         self.button_dic[j].set(str(j))
         ## set textvariable to the StringVar()
         b = Button(self.top_frame, textvariable = self.button_dic[j], \
                    command=partial(self.cb_handler, j))
         b.grid(row=b_row, column=b_col)

         b_col += 1
         if b_col > 2:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, square_number ):
      print "cb_handler", square_number
      if self.player:                       ## True = "X", False = "O"
         player = "X"
      else:
         player = "O"

      ##--- square not already occupied
      if square_number not in self.X_O_dict["X"] and \
         square_number not in self.X_O_dict["O"]:

         ## change the StringVar() to "X" or "O"
         self.button_dic[square_number].set(player)
         self.X_O_dict[player].append(square_number)
         print player, 
         self.check_for_winner(self.X_O_dict[player])
         self.player = not self.player
      else:
         print "Occupied, pick another"

   ##----------------------------------------------------------------
   def check_for_winner( self, list_in ):
      set_in = set(list_in)

      winner_list = [[1, 2, 3], [4, 5, …
woooee 814 Nearly a Posting Maven

Split on "study", or a normal split on space(s) will also work as the number.txt will be -1, or the study's description will be everything except the last element.

woooee 814 Nearly a Posting Maven

A second way is to use a StringVar(). See the "textvariable" write up at http://infohost.nmt.edu/tcc/help/pubs/tkinter/button.html

woooee 814 Nearly a Posting Maven

You can't combine grid() and pack() but must use one or the other. Also, AFAIK, one radio button must be selected (a default selection or you can't choose 'none' when using radio buttons), and the others can be deselected.

from Tkinter import *
 
class App:
   def __init__(self, parent):
    self.my_parent = parent
    self.my_parent.geometry("200x100+10+10")
#    self.fm = Frame(parent, width=400, height=300)
#    self.fm.pack_propagate(0) # to keep the frame size
#    self.fm.pack()
 
 
    self.R1 = Radiobutton(self.my_parent, text="Red", value=1, command=self.make_Red)
    self.R1.grid(row =2 , column = 1)
    self.R1.select()

    self.R2 = Radiobutton(self.my_parent, text="Blue",  value=2, command=self.make_Blue)
    self.R2.grid(row =2 , column = 2)
    self.R2.deselect()
 
    self.R3 = Radiobutton(self.my_parent, text="Green", value=3, command=self.make_Green)
    self.R3.deselect()
    self.R3.grid(row =2 , column = 3)
 
 
   def change_buttons(self, color):
       self.my_parent.configure(bg=color)
       self.R1.configure(bg=color)
       self.R2.configure(bg=color)
       self.R3.configure(bg=color)

   def make_Red(self):
       self.change_buttons("Red")
 
   def make_Blue(self):
       self.change_buttons("BLUE")
 
   def make_Green(self):
       self.change_buttons("GREEN")
 
root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()
Gribouillis commented: Tkinter Guru Award. +5
woooee 814 Nearly a Posting Maven

Doug Hellmann's write-up.

woooee 814 Nearly a Posting Maven

The difference between
name1,number1;name2,number2;name3,number3
and
name1,number1
name2,number2
name3,number3
is a newline. Use rstrip() to strip the newline before you write to the output file.
out.write(line.rstrip())

woooee 814 Nearly a Posting Maven

You don't have a callback or any way to execute curselection. An example:

import Tkinter

class TestCallback:
   def __init__(self, top):
      self.top = top
      self.top.geometry( "100x100+10+10" )
      self.top.minsize( 200, 175 )

      self.listbox = Tkinter.Listbox( self.top, height=6, width=20, font=('Fixed', 14) )

      lit = [ "aaa", "bbbbb", "ccccccc", "dd", "e", \
              "fff", "ggggg", "hhhhhhh", "jj", "m", \
              "nn", "ooo", "ppp", "rr" "s" ]
      for item in range( len(lit) ):
          new_item = "%2d  %-10s" % (item, lit[item])
          self.listbox.insert(Tkinter.END, new_item)

      exit = Tkinter.Button(self.top, text='Exit',
             command=self.top.quit, bg='blue', fg='yellow' )
      exit.pack(side="bottom", fill=Tkinter.X, expand=1)


      self.listbox.pack(side="left")
      self.listbox.see(2)
      self.listbox.bind("<Double-Button-1>", self.test_callback)


   def test_callback(self, event):
      print self.listbox.curselection()
        
root = Tkinter.Tk()
TC = TestCallback(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

I'm not sure I understand your question but if you want to use multiple class instances, one per dog, try something like this.

if __name__ == "__main__":
	dogs = list()
        dog_name = ""
	first_inp = "Name: ('quit' to exit) "
	second_inp = "Breed: "
	while dog_name.lower() != "quit":
		dog_name = input(first_inp).strip()
		dog_breed = input(second_inp).strip()
		this_instance = Dog(dog_name, dog_breed)
                dogs.append(this_instance)
        for each_instance in dogs:
            print(each_instance.name, each_instance.breed)
woooee 814 Nearly a Posting Maven

Run the input files one at a time, i.e. run the program using the first file and check the output, then run the program again using the second file and check the output file, etc.

woooee 814 Nearly a Posting Maven

Use curselection to return the item number selected. Note that the title of this thread indicates that this is a "HowTo", a code snippet on how to do something, and not a question. You will possibly get more views=more responses when it is clear that this is a question.

woooee 814 Nearly a Posting Maven

Sorry, I don't have must experience with that. I only use SetBackgroundColour, etc.

woooee 814 Nearly a Posting Maven

try and convert the value from the numctrl to a decimal

You can not convert a float to decimal.Decimal because floats are inaccurate past a certain number of digits. You will have to get/enter the value as a string and convert.

woooee 814 Nearly a Posting Maven

Use a while() loop that checks for the answer. Also, you should print what options are available as an answer instead of making the enterer guess. This is not intended as a complete answer.

while intro not in ["yes", "no"]:
    intro = input("Want to play a game of number guess? ('yes' or 'no'")

available_guesses = [str(x) for x in range(1, 11)]
while intro == 'yes':
    guess = "0"
    while guess not in available guesses:
        guess = input("\nOkay. Just guess the number I am thinking of from 1 to 10. ")
    while intro not in ["yes", "no"]:
        intro = input("Want to play a game of number guess? ('yes' or 'no'")

(sorry i didn't know how to explain it well)

That is why you can't code it. You have to first explain it in words, in detail, in order to explain it in code?

woooee 814 Nearly a Posting Maven

A cross platform solution is os.path.join(). The only gottcha is it sometimes gets confused when a "/" or "\" is included with the right-most string
print os.path.join("dir_1", "dir_2", "image"+str(12)+".png")

woooee 814 Nearly a Posting Maven

I am getting "syntax error - unindent does not match any outer indentation level"

Look at the line number of the error message (you didn't post it) and check that it, or sometimes the previous line, lines up correctly.

woooee 814 Nearly a Posting Maven

join() interleaves a list with a constant so
self.currentOutDir.join(self.counterStr)
would produce
self.counterStr[0]+self.currentOutDir+self.counterStr[1]+self.currentOutDir+self.counterStr[2]...etc.
A simple example:

x = ["1", "2", "3"]
print "a".join(x)
#
x = "123"
print "b".join(x)
woooee 814 Nearly a Posting Maven

You are obviously not passing the ball object to Bounce (Python naming conventions), so look at the places that call Bounce and see if the ball object is actually being passed.

woooee 814 Nearly a Posting Maven

"row" is a string, and strings are immutable, i.e. can not be changed, so you have to catch the return and use it.

for row in open('C:\\test.xml','r'):
    if 'RecCount' in row:
        print row
        new_row = row.replace('RecCount','12345')
        print new_row
woooee 814 Nearly a Posting Maven

You would first compare the ID returned to record[0], the original ID. If it has changed, you can use UPDATE

cur.execute("UPDATE People SET SQL_id_tag==:update_id",
       {"update_id": new_id_variable})
con.commit()
woooee 814 Nearly a Posting Maven

If you can not use a built-in method to reverse the string (or list if you prefer), please state what the requirements are, otherwise:
reverse_word = input_word[::-1] ## [begin:end:step=-1]

woooee 814 Nearly a Posting Maven
subprocess.call(['python link_config_idu12.py %s'%addr],shell=True)

"addr" is not defined in the code you posted.

But, i see that what i expect is not happening.

What does this mean? To set a list element, you access by the offset, i.e

test_list = [0, 0, 0, 0]
print "Before", test_list
for y in range(5):
    test_list[y] = y
print "After", test_list
woooee 814 Nearly a Posting Maven

Is there something I am doing wrong?

There is no way to tell what you are doing. You didn't post any code to comment on. Take a look at vegaseat's example here and see if it helps you.

woooee 814 Nearly a Posting Maven

This is a linked list type of problem, where every question is linked to another for a yes or no response. Each question is assigned a unique number. It does not matter what the number is, it is just a unique identifier for each question. So you can have multiple questions linked to "bigger than a backpack" for example. A simple snippet follows. At some point you will have to guess, so you might want to also be able to input "guess" at any point, and guess in some way.

##         layout =  question        yes  no
question_dic = {1: ("Is it a thing? ", 21, 11), 
                11: ("Is it a place? ", 21, 12),
                12: ("Is it a person? ", 21, 21),
                21: ("Can it fit in a backpack? ", 0, 22),
                22 ("Is it bigger than a car? ", 23, 24),
                23: ("Is it bigger than a house? ", 0, 0),
                24: ("Is it bigger than a table? ", 0, 0)}

store_responses = {}
num = 1
while num != 0:
    question = question_dic[num][0]
    x = ""
    lit = ""
    while x not in ("yes", "no"):
        print lit
        x = raw_input(question).lower()
        lit = "Enter 'Yes' or 'No' only"

    store_responses[num]= x              ## question number & yes or no
    if x == "yes":
        num = question_dic[response][1]
    else:   
        num = question_dic[response][2]

print "Game Over"
woooee 814 Nearly a Posting Maven

Also, calculate (p0 * math.e) once before the for() instead of every pass calculating it again. You should be using one for() loop, since they all do the same thing.

numeratorPos1 = 0
numeratorPos2 = 0
denominatorPos = 0
p0_math_e = p0 * math.e
for x in range(0, n):        
    y = p0_math_e**(-(decay * x))

    numeratorPos += ((x**2)*y)
    numeratorPos += (y*(math.log(y)))
    denominatorPos += y
#
# etc.
woooee 814 Nearly a Posting Maven

This will produce a unique number for each file name.

for ctr, fname in enumerate(files):
    print ctr, fname
woooee 814 Nearly a Posting Maven

It possibly has something to do with the unconventional way you are including/calling Tkinter. The standard way is here. The following code works on my Slackware Linux system.

import Tkinter

class App():
    def __init__(self):
        self.parent = Tkinter.Tk()
        self.initialize() 
        self.parent.mainloop()
 
    def initialize(self):
        self.itemVar = "abc"
        for r in range(8):
            mode = r*2+1
            self.itemOdds =  Tkinter.Radiobutton(self.parent, text="item"+str(mode),
                        variable=self.itemVar, value=mode)
            self.itemOdds.grid(row=r, column=0)
 
        EVENS = [
            ('item0', 0),
            ('item2', 2),
            ('item4', 4),
            ('item6', 6),
            ('item8', 8),
            ('item10', 10),
            ('item12', 12),
            ('item14', 14),
        ]
 
        r = 0
        for text, mode in EVENS:
            self.itemEvens = Tkinter.Radiobutton(self.parent, text=text,
                        variable=self.itemVar, value=mode)
            self.itemEvens.grid(row =r, column=1)
            r += 1

if __name__ == "__main__":
    app = App()
woooee 814 Nearly a Posting Maven

You should supply both the row and column to the grid http://effbot.org/tkinterbook/grid.htm

woooee 814 Nearly a Posting Maven

is there a way for me to link the movie file to the text in the listbox

Each listbox entry corresponds to a number, i.e. curselection returns the line number. You can link the number selected to a file using a dictionary.

woooee 814 Nearly a Posting Maven

You should eliminate the pass-through functions.

class DemoImpl(QtGui.QMainWindow):
    def __init__(self, *args):
        super(DemoImpl, self).__init__(*args)
        uic.loadUi('K:\QTProjects\pos\mainwindow.ui', self)
        self.btnLogin.clicked.connect(self.createConnection)

    def createConnection(self):
        db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName(':memory:')
        if not db.open():
            QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"), QtGui.qApp.tr("Unable to establish a database connection.\nThis example needs SQLite support. Please read the Qt SQL driver documentation for information how to build it.\n\nClick Cancel to exit."), QtGui.QMessageBox.Cancel)
            return False
        else:
            QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open database"), QtGui.qApp.tr("Database Connected"), QtGui.QMessageBox.Cancel)
            return True
woooee 814 Nearly a Posting Maven

find() will locate a character

found = 0
while found > -1:
    found = text_to_output("\r")

You can then use split() and/or replace to create the modified output.

print text_to_output.split("\r")
woooee 814 Nearly a Posting Maven

but for some reason crashes with large numbers (the 10001st prime)

That is possibly the result of using "is". Python stores smaller numbers and points to them, so "is" works on smaller numbers since they all point to the same object, but once you get above the stored value it no longer works. This code works for me:

def nth_prime(n):
    primes = [2]
 
    test_int = 1
    while len(primes) < n:
        test_int += 2
        prime_found = True
        for p in primes:
            if test_int % p == 0:
                prime_found = False
                break
        if prime_found:
            primes.append(test_int)
 
    return primes[n - 1]
 
print( nth_prime(10002) ) 

"""
 prints 104759 which is on the list here 
http://www.cs.arizona.edu/icon/oddsends/primes.htm
I'm not going to count them to see if it really is number 10,002
"""
woooee 814 Nearly a Posting Maven

Take a look at Effbot's tutorial for an entry box to find out how you set and get the text as there are at least two ways to do it.

woooee 814 Nearly a Posting Maven

Also you are using "is" instead of equal. "is" tests for the same object, so can not be relied upon for an equal condition. Finally, the statement

else:
    if p is primes[len(primes)]:

is unnecessary. The for loop takes care of that. So, you could use an indicator like this instead.

prime_found = True
        for p in primes:
            if test_int % p is 0:
                prime_found = False
                break
        if prime_found:
            primes.append(test_int)
##
##-------------------------------------------------------------------
##   a short example of "is" vs. "=="
x = "abc"
y = "abcd"
print x is y, id(x), id(y)        ## prints False
print x is y[:3], id(x), id(y)    ## prints False
print x == y[:3], x, y[:3]        ## prints True
woooee 814 Nearly a Posting Maven

The following slightly modified code displays correctly for me on a Slackware Linux system.

import Tkinter

def addmovie(root):
    addboard = Tkinter.Toplevel()
    addboard.title("Add a movie")
    addboard.geometry("600x600")
    #addboard(padx=10, pady=10)
    print "add"
    #adding the title
 
    lbtitle = Tkinter.Label(addboard, text = "Enter the movie's title:")
    lbtitle.grid(row = 1, column = 1)
    entitle = Tkinter.Entry(addboard)
    entitle.grid(row = 1, column = 3)
    #adding the director
    lbdirector = Tkinter.Label(addboard, text = "Enter the mmovie's director:")
    lbdirector.grid(row = 2, column = 1)
    endirector = Tkinter.Entry(addboard)
    endirector.grid(row = 2, column = 3)
    #adding the year
    lbyear = Tkinter.Label(addboard, text = "Enter the movie's year:")
    lbyear.grid(row = 3, column = 1)
    enyear = Tkinter.Entry(addboard)
    enyear.grid(row = 3, column = 3)
    #if a value is left blank program will ask what to do
    #to be added later
 
    #The button and the commands to put it all together
    btnok = Tkinter.Button(addboard, text = "Continue")
    btnok.grid(row= 5, column = 4)
    btncancel = Tkinter.Button(addboard, text = "Cancel", bg= 'red', command=root.quit)
    btncancel.grid(row = 5, column = 1)


root = Tkinter.Tk()
addmovie(root)
root.mainloop()