woooee 814 Nearly a Posting Maven

See this link on functions http://www.tutorialspoint.com/python/python_functions.htm You should also have a function_1 that will input the name and grade until told to stop. It would also receive the "data" list and append to it. If the length of "data" is zero, then option 2 has not been selected. You can either print an error message or call function_2 from function_1 to read the data. It is a good habit to include some useful info about what the function does with every function call for future reference.

def function_2():
    """ get the file name, open and read the file, and return the data
    """
    fname = input("What is the file name?")
 
    file1 = open(fname, "r")
    data = file1.readlines()
    file1.close()
    return data

def function_3(data):
    """ process the data by calculating the mean
    """
    for rec in data:
        print rec
 

def main():
    data=""
    choice = input("Please enter the number for your choice or press <enter> to quit\n\n1.) Add a student to File\n2.) Display course info\n3.) Display course stats.")
    if choice == '1':
        function_1(data)
    elif choice == '2':
     data=function_2() #should open file to read file
     print data
    elif choice == '3':
     function_3(data) #display results from arithmetic mean and range for the course
 
    else:
        print "Enter 1, 2, or 3 only"

    file1 = open(filename1,"a")
    file1.write(myInfo + ","   ",\n" )
    file1.close()
 
 
 
 
 
if __name__ == '__main__':
    main()
woooee 814 Nearly a Posting Maven

Open and read the file once into a list at the start of the program. If there are adds, simply add them to the list. Write the file once at the end of the program. I am guessing that each record in the file will contain the student's name and the grade so you can satisfy the requirements for #3. Start by getting the name and grade many times and appending each to a list, until the user enters "quit" for the student name, then write the file to disk and verify it's contents. The other parts have to wait until this is finished.

woooee 814 Nearly a Posting Maven
content = row[0] + row[4] +  row[5] +  row[11] +  row[12] + row[13] +  row[16] + row[17] + row[22]
	csv_out.writerow( content )

The above uses 9 fields.

# I want it to save the file in csv format as: 1,2,yhnujmik,2121212121

This has 4 fields.

however the code is generating this: 1,2,y,h,n,u,j,m,i,k,2,1,2,1,2,1,2,1,2,1

This has 20 fields. 9 != 4 != 20. There is no way to answer a question that does not make sense. Post some sample input and desired output and perhaps we can then offer some help.

woooee 814 Nearly a Posting Maven

Since words are not very long, it is not a problem to iterate through the entire word and keep track of the position of the first vowel, and if there is a consonant.

first_vowel = -1         ## location of first vowel
    consonant_found = False  ## assume no consonants
    t = 0
    for x in word:
        ## use lower() or upper() and one list of vowels
        if x.lower() in ["a", "e", "i", "o", "u", "y"]:
            if first_vowel == -1:     ## -1 == not found yet
                first_vowel = t
        else:
            consonant_found = True
        t += 1

    prefix = word[:first_vowel]
    stem = word[first_vowel:]
    if not consonant_found:
        print "Translated word:",
        print word + "yay"
    # etc.

"Yay" translates to "Yayyay"

woooee 814 Nearly a Posting Maven

You hit the Enter key without any data. You should know what the code does even if you get it from someone else. What is necessary to exit in this code?

in_str=""
    while in_str != "q":
woooee 814 Nearly a Posting Maven

I think graphics has an undraw() method, you'll have to check to be sure, but set a variable to True or False. If True, call function_1 which undraws "standing" and draws "jump" and set variable=False. If False, call function_2 and do the reverse. It would be much easier if all of figure 1 is in list_1, and all of figure 2 is in list 2. A pseudo-example:

win = GraphWin ("GraphicsWin", 900,700)

def draw_1(list_1):
    for object in list_1:
        object.draw(win)

def undraw_1(list_1):
    for object in list_1:
        object.undraw()

def stand():
    ret_list=[]
    circ = Circle(Point(200,400),30)
    ret_list.append(circ)

    line1 = Line(Point(200,430),Point(200,530))
    ret_list.append(line1)

    ## etc
    return ret_list

list_1 = stand()
for ctr in range(5):
    draw_1(list_1)
    time.sleep(1.5)
    undraw_1(list_1)
    time.sleep(1.5)
woooee 814 Nearly a Posting Maven

sys.exit() is never a good idea. In this case Tkinter's quit() is the preferred way to exit. The program runs on my Slackware system with this modification to endProgram()

def endProgram (self):
      if self.state == 0:
         self.master.quit()
      else:
         print ("state is not zero -->", self.state)
woooee 814 Nearly a Posting Maven

There is more than one way, but you could use a for() loop with step=4. We don't have the file so you will have to test and correct this yourself.

def block_generator():
        with open ('test', 'r') as lines:
            data = lines.readlines ()[5::]

            for ctr in range(0, len(data), 4):
                block = []
                for x in range(4):
                    block.append(data[ctr+x]
                print block
Gribouillis commented: I like the " with ... as lines" +13
woooee 814 Nearly a Posting Maven

First, you have to call "hanlderf()" and create the text widget. Since I don't have the file, the text inserted into the widget is different.

from tkinter import *
 
def handler(event):
    print("Clicked at", event.x, event.y)
 
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
 
        for r in range(6):
            self.master.rowconfigure(r, weight=100)    
        #Creating custom buttons
        self.master.columnconfigure(0, weight=100)
        Button(master, text="Red",command=self.colorit).grid(row=6,column=0,sticky=E+W)
        self.master.columnconfigure(1, weight=100)
        Button(master, text="Blue").grid(row=6,column=1,sticky=E+W)
        self.master.columnconfigure(2, weight=100)
        Button(master, text="Green").grid(row=6,column=2,sticky=E+W)
        self.master.columnconfigure(3, weight=100)
        Button(master, text="Black").grid(row=6,column=3,sticky=E+W)
        self.master.columnconfigure(4, weight=100)
        Button(master, text="Open", command=self.hanlderf).grid(row=6,column=4,sticky=E+W)
 
        Frame1 = Frame(master, bg="red", width=100, height=50)
        Frame1.grid(row = 0, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S) 
        Frame1.bind("<Button-1>", handler)
        Label(Frame1, text='frame1').grid(row=0)
 
        Frame2 = Frame(master, bg="blue",width=100, height=50)
        Frame2.grid(row = 3, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
        Frame2.bind("<Button-1>", handler)
        Label(Frame2, text='frame2').grid(row=3)
 
        self.Frame3 = Frame(master, bg="green",width=200)
        self.Frame3.grid(row = 0, column = 2, rowspan = 6, columnspan = 3, sticky = W+E+N+S)
        self.text_in = Entry(self.Frame3,text="this is a text")
        self.text_in.grid(row = 5, column = 2)
        Label(self.Frame3, text='frame3').grid(row=0,column=2)
 
        ## call the function
        self.hanlderf()

    def hanlderf(self):
        """
        try:
            text = self.text_in.get()
            myFile=open(text) # get a file handle
            self.myText= myFile.read() # read the file to variable
            myFile.close() # close file handle
        except Exception as msg:
            print("An error has ocurred: %s" % msg)
            self.myText="An error has ocurred.!"
        """ 
        self.myTextWidget= Text(self.Frame3)
        self.myTextWidget.insert(0.0,"Change this color")
        self.myTextWidget.grid(row = 7, column = 2)
 
    def colorit(self):
        """ changes the text widget foreground color to blue when the 'red'
            button is clicked
        """
        self.myTextWidget.configure(fg='blue')
#        self.myTextWidget.tag_config(self.myText, foreground="blue")
        #text.tag_config("a", foreground="blue")
        #text.insert(contents, ("n", "a"))
        self.myTextWidget.insert(END, "\nColor changed")
        print("changing the color")
 
 
root = Tk() …
woooee 814 Nearly a Posting Maven

Since 2 loops would be required to solve this, you can also use two recursive functions. The following code compares the first number to all other numbers in the list. You would then create a top level function that would pass the original list to this function and then call itself again recursively after deleting the first number, so the second number would then be compared to all other numbers in the list, etc. Note that this function uses a copy of the list. Lists are passed by reference, meaning that the address in memory is passed, so any changes to one list affects all references to the list. When passing a list to more than one function it is a good idea to use a copy of the list.

def test_numbers(this_list, found_list):
    print "  list_in =", this_list
    
    ## if out of numbers, just return found_list
    if len(this_list) > 1:
        print "     comparing", this_list[0], this_list[1]
        if this_list[0] + this_list[1] < 0:
            found_list.append([this_list[0], this_list[1]])
        del this_list[1]
        found_list = test_numbers(this_list, found_list)

    return found_list

test = [1,6,7,-4,36,3,4]
print test_numbers(test[:], [])   ## passes a copy of the list
woooee 814 Nearly a Posting Maven
test = input("Enter numbers: ")
neg_sum(test)

I tried to convert the input into a list, however I still got errors

How did you convert it to a list? You also have to convert the numbers to integers also. It is better to ask for one number at a time and use a try/except to convert to an int, and then append to the list.

woooee 814 Nearly a Posting Maven

You have to return the values, see http://www.penzilla.net/tutorials/python/functions/ for starters.

def fcn1(record):
    do some stuff
    write result to a new file
    return data_from_this_function
     
def fcn2(data_from_fcn1):
    do some stuff
    write result to a new file
    return data_from_this_function
     
def fcn3(data_from_fcn2):
    do some stuff
    write result to a new file
    return result
     
#___________main___________
f=open('filename','r'
fread=f.readlines()
for f in fread
    res1=fcn1(f)
    res2=fcn2(res1)
    res=fcn3(res2) 

##------- you can run the following
def func_1(list_in):
    list_in.append("added by func_1")
    return list_in

def func_2(list_in):
    for ctr in range(len(list_in)):
        if list_in[ctr] == "added by func_1":
            list_in[ctr]=list_in[ctr].replace("func_1", "func_2")
    return list_in

def func_3(list_in):
    list_in.append("ADDED by func_3")
    return list_in


res_1=func_1([])
print res_1
res_2=func_2(res_1)
print res_2
res=func_3(res_2) 
print res
woooee 814 Nearly a Posting Maven

Do you want to do this in the console, as the post above, or did you intend on using a GUI. Some sample input and output would also help.

woooee 814 Nearly a Posting Maven

I'm just a beginner trying to learn, but since the problem says that its supposed to check any two numbers in a list that adds up to a negative not just consecutive numbers, wouldn't it work if a for loop was added?

Yes and would be better as loops are almost always better than recursion IMHO, but the problem states that the program must use recursion.

woooee 814 Nearly a Posting Maven

Write a program that creates a linked list of bunny objects

This is just a list of objects, because to create a linked list you have to link one to the other in some way but the link was not given (and I did not read it carefully so may have missed it). Please read and observe the Python Style Guide. It makes someone else's code that much easier to read and increases your chances of getting some help. There are other ways to do this, like keeping track of the total males and females to create an equal number, so experiment if you wish. This is a subset of what you want to do, and is not tested.

import random

class Bunny:
 
    def __init__(self, female, male, fur, tot_males, tot_females):
        ## all of these are filled in by the functions
        self.gender = self.bunny_gender(tot_males, tot_females)
        self.name = self.bunny_name(female, male)
        self.fur = random.choice(fur)
        self.age = random.choice(range(0,11))
 
        print "Created", self.name, self.gender, self.fur, self.age
   
    def bunny_name(self, female, male):
        if 'Male' == self.gender:
            return random.choice(male)
        return random.choice(female)
 
    def bunny_gender(self, tot_males, tot_females):
        choice = random.choice([0,1])
        if choice:
            if tot_males < 5:
                return 'Male'
            else:
                return 'Female'
        elif tot_females < 5:
            return 'Female'
        return 'Male'
        
female_names_list = \
"Fufu.Ophelia.Oryctolagus.puddles.Nidoran.Cherry.Holly.Stacy.Lucy.Rona".split(".")
male_names_list = \
"Bill.Fred.Tex..Max.Fluffy.Thumper.Harvey.Romeo.Chocolate.Pebbles".split(".")

#fur = open("BunnyFur.txt").read().strip('\n').split(".")
fur = ["white", "brown", "spotted", "black"]

bunny_class_instances=[]
total_males=0
total_females=0
for b in range(10):
    BY = Bunny(female_names_list, male_names_list, fur, total_males, total_females)
    if 'Male' == BY.gender:
        total_males += 1
        male_names_list.remove(BY.name)
    else:
        total_females += 1
        female_names_list.remove(BY.name)
    bunny_class_instances.append(BY)


for instance in bunny_class_instances: …
woooee 814 Nearly a Posting Maven

[13, 9, 15, -10, 11] would return True, because 9 + -10 is a negative number

You have to compare each number to all of the other numbers, not just side-by-side pairs. I would suggest that you sort the list in reverse order so all negative numbers are at the end, and send to a function to compare the first element with all others and return a list of "True". You can then remove the number tested and call the function recursively,

woooee 814 Nearly a Posting Maven

Normally you would use line.strip().split() and the length of the resulting list.

woooee 814 Nearly a Posting Maven

Vegaseats' code did not work here because you are already reading the file with
"for line in myFile".
Since you already have a individual line, it is better to use that line than read the file all over again.

woooee 814 Nearly a Posting Maven

You should be passing line to the function.

def percount(line):
    periods = 0
    for char in line:
        if char == '.':
            periods +=1
    return periods

for line in myFile:
...
##    for char in line:
    p = percount(line)
    total_periods += p

Also, in the real world
if line == ('\n'):
is rarely used as there may a space in the line as well. You can use instead:

if len(line.strip()):
bigredaltoid commented: Wooee has been an immense amount of help to this new Python user! +1
woooee 814 Nearly a Posting Maven

Everything should be under the while loop.

number = int(raw_input("Please enter a number: "))
largest = number
while (number>0):
    number = int(raw_input("Please enter anohter number: "))

    if (largest>number):     ## this will give the smallest
         number = largest
    ##if (number<0):    not necessary as the while loop takes care of this
print "The largest number was: ",number
woooee 814 Nearly a Posting Maven

Recursion = a function that calls itself and is along the lines of

def recursion_funct(list_in):
    print "list is now", list_in
    if len(list_in) > 1:
        recursion_funct(list_in[1:])
    else:
        return    ## out of entries in the list

test_list=[13, 9, 15, -10, 11]
recursion_funct(test_list)

First figure how to use a function that calls itself (maybe tests the first entry against all negative numbers and then return a list from each successive call, but then what do you do if there is a positive number after a negative number). You'll have to figure that out before you can start coding.

woooee 814 Nearly a Posting Maven
myFile = open("inn.txt", "r")
 
for line in myFile:
    lines +=1
 
    if line == ('\n'):
        blanklines +=1
 
for char in myFile:

When you get to "for char in myFile" you are already at the end of the file (because "for line in myFile" went through the entire file) so there is no data read. It should be:

myFile = open("inn.txt", "r")
 
for line in myFile:
    lines +=1
 
    if line == ('\n'):
        blanklines +=1
 
    for char in line: 
        if char == period:             #3
        if char not in [" ", "\n"]:    #4 do both in the same loop
    #etc...#5 will also be under the "for line in myFile" loop and use "line".

Python does have a count() function but I assume that you are supposed to code this for yourself.

woooee 814 Nearly a Posting Maven

Please mark the thread as solved to save others the time it takes to read through this post only to realize it is solved. I think the "solved" button is just above the box where replies are posted..

woooee 814 Nearly a Posting Maven

You would use readlines() to read the file into a list, process the list however many times you want, and then write the list to another file.

def f1(data_list):
    """ add one to even numbered elements
    """
    for ctr in range(1, len(data_list), 2):
        data_list[ctr] = int(data_list[ctr].strip()) + 1
    return data_list

def f2(data_list):
    """ subtract one from odd numbered elements
    """
    for ctr in range(0, len(data_list), 2):
        data_list[ctr] = int(data_list[ctr].strip()) - 1
    return data_list

"""
def f3(result2):
    do something 
    return res3
"""

#test_data = open(filename1, 'r').readlines()
## simulate open and readlines
test_data = [ '1\n', '2\n', '3\n', '4\n', '5\n', '6\n']
test_data = f1(test_data)
print "after f1", test_data
test_data = f2(test_data)
print "after f2", test_data

## write file here after all processing has been done
woooee 814 Nearly a Posting Maven

A basic principle is that you have bytes of data. In your case you want to modify and store the bytes several times. It does not matter how you store them. You can create files to store them, as in this program, or you can store them in a list or SQLite database and pass the container around. Also, in program 2, you open and read a file each time through the loop. Read it once only.

#program 2
f2=open('filename1', 'r')  # open file created in newfile in program 1
newfile=('file_name2', 'w')

f3_data=open(filename3. 'r').readlines()

for lines in f2.readlines():
#	f3=open('filename3', 'r')
	for data in f3_data:
		if lines.split('\t')[0] in datat:
			write to new_file	
#	f3.close()    ## open + readlines on one line does this for you

f2.close()
new_file.close()
woooee 814 Nearly a Posting Maven

If you use a loop then you should also use "update_idletasks" or no updates will happen until the loop exits. Note that this code is for Python2.x

from Tkinter import *
import time
 
class MyGui():
   #state = 1 ---> label is green
   #state = 0 ---> label is red
   #state = 0
 
   def __init__(self, master=None):    # 1
#      Frame.__init__(self)    # 2
      self.master=master
      self.master.title( "Traffic Light Control EGR 101")
      self.master.grid()
      self.master.rowconfigure(0, weight=1)  # 3
      self.master.columnconfigure(0, weight=1)  # 4
      
      self.canvas = Canvas(self.master, width=100, height=100)
      self.canvas.grid(row=0, rowspan=3, column=0)
 
      self.canvas.create_oval(10,10,90,90, width=2, tags="topLight")    # 5
      self.state=0
      self.greenButt = Button(self.master, text="Green", command=self.fillGreen)  # 6
      self.greenButt.grid(row=0, column = 1, sticky=W+E+N+S)   # 7
 
      self.redButt = Button(self.master, text="Red", command=self.fillRed)
      self.redButt.grid(row=1, column=1, sticky=W+E+N+S)
 
      self.autoButt = Button(self.master, text="Auto", command=self.fillAuto)
      self.autoButt.grid(row=2, column=1, sticky=W+E+N+S)
 
      self.label1 = Label(self.master, text="Hello", font=16)
      self.label1.grid(row=3, column=1)
 
   def fillGreen(self):
      self.canvas.itemconfigure("topLight", fill="green")   # 8
      self.label_color()
 
   def fillRed(self):
      self.canvas.itemconfigure("topLight", fill="red")
      self.label_color()
 
   def fillAuto(self):
      for ctr in range(10):     ## cycle 10 times and quit
          print ctr
          if self.state:
             self.fillGreen()
          else:
             self.fillRed()
          self.master.update_idletasks()
          self.state=not self.state
          self.label_color()
          time.sleep(1)
 
   def label_color(self):
      if self.state == 1:
         self.state = 0
         self.label1.configure(fg="red")  # 9
      else:
         self.state = 1
         self.label1.configure(fg="green")
 
root=Tk()
MG=MyGui(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

You did not say anything about also finding "align=top". To do that, check if the string starts with a quotation mark, in which case the first function works fine. If no quotation mark is found, then split on white space. You will have to code some of this yourself instead of giving us one task after another until the program is written for you. This forum is for helping those with code, so if you post code then we will help.

woooee 814 Nearly a Posting Maven

For the example line you gave

def find_attribute_value(html_tag, att):
    ## is att in html?
    if att in html_tag:
        ## find the location of att
        idx = html_tag.find(att)
        ##split on the quotation marks for everything after att
        first_split = html_tag[idx:].split('"')
        print first_split[1]
    else:
        print "attribute %s Not Found" % (att)

def find_attribute_value2(html_tag, att):
    """ this is the way you were trying to do it
    """
    first_split = html_tag.split()
    for x in first_split:
        if att in x:
            second_split = x.split("=")
            fname=second_split[1].replace('"', "")
            print fname
            return

test_line = find_attribute_value('<img align=top src="photos/horton.JPG" alt="Image of StG instructor (Diane Horton)">', "src")

test_line = find_attribute_value2('<img align=top src="photos/horton.JPG" alt="Image of StG instructor (Diane Horton)">', "src")

and note that this will only find the first instance of "att". And you can split on "=" as a second split(), if you know there is always space after the file name.

Hikki_Passion commented: YOU MADE IT WORK! :O Genious! +1
woooee 814 Nearly a Posting Maven

if '123' not in os.uname()[1]:

woooee 814 Nearly a Posting Maven

There is no way to tell without a complete error message which the contains the errant line. Also, do you instantiate the class and then call the setupUI function with a parameter? As the code stands now, nothing will happen even if the code does not contain errors.

woooee 814 Nearly a Posting Maven

You don't save the original file name so there is no "copy from" name. Be sure to back up the directory before testing any rename code.

import os
 
#read in file from the directory
for filename in os.listdir("."):
 
#    f = open(filename, "w")
 
#    i = True
 
#    while i:  doesn't do anything
	#if filename starts with a digit, lose first index by renaming and 
        #try again
     new_filename = filename
     while new_filename[0].isdigit():
 
	    new_filename = new_filename[1:]
 
     if new_filename != filename:
         print "renaming %s to %s" % (filename, new_filename)
         os.rename(filename, new_filename)

 
print 'Any filename starting with a digit has been renamed.'
woooee 814 Nearly a Posting Maven

Use a return from the function (untested code).

def callcard ():
    IOU="0"
    while IOU not in ["1", "2", "3", "4"]:
        print
        print "1. For $5 or $10."
        print "2. For a $25 charge, you get $3 of extra phone time."
        print "3. For a $50 charge, you get $8 of extra phone time."
        print "4. For a $100 charge, you get $20 extra phone time."
        print " "
        print " "
        IOU = raw_input ("Please enter the number for the amount you wish to charge: ")
    print " "
 
    loop=True
    while (loop):    ## not necessary as the above guarantees correct input
        if (IOU == '1'):
            amount = "0"
            while amount not in ["5", "10"]:
                print "You have chosen to charge $5 or $10."
                amount = raw_input ("Please enter '5' for $5 or '10' for $10: ")
            if (amount == '5'):
                print "You have charged $5, thank you for your purchase."
            elif (amount == '10'):
                print "You have charged $10, thank you for your purchase."
#            else:
#                print "Incorrect value"
            return  ## exit function 
#
# etc for the other options

again="Y"
while again == "Y":
    callcard()
    print  
    again = raw_input("Enter 'Y' for a transaction;  any other key to exit ")
    again = again.upper()

Since options 2, 3, & 4 are all the same except for the amount, you can pass the necessary parameters to a function, and use it for any of those three options.

PlUmPaSsChIcKeN commented: Awesome +0
woooee 814 Nearly a Posting Maven

You can pack them all into a Frame and destroy the Frame.

try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

class DestroyTest():
    def __init__(self, top):
        self.top=top
        self.top.geometry("+10+10")

        self.frame=tk.Frame(self.top)
        self.frame.grid()

        test_label=tk.Label(self.frame, text="Label")
        test_label.grid(row=1, column=0)

        destroy_button=tk.Button(self.frame, text="Destroy Frame", \
                                 command=self.destroy)
        destroy_button.grid(row=10, column=0)

        exit_button=tk.Button(self.top, text="Exit", command=top.quit)
        exit_button.grid(row=10, column=0)

    def destroy(self):
        self.frame.destroy()
        self.new_toplevel=tk.Toplevel(self.top, takefocus=True)
        self.new_toplevel.geometry("+50+50")
        self.new_toplevel.grid()

        lbl=tk.Label(self.new_toplevel, text="New Toplevel")
        lbl.grid()


root=tk.Tk()
DT=DestroyTest(root)
root.mainloop()
JoshuaBurleson commented: PERFECT! +4
woooee 814 Nearly a Posting Maven

Use itertools.

import itertools
x = [['foo'], ['bar', 'baz'], ['quux'], ("tup_1", "tup_2"), {1:"one", 2:"two"}]
print list(itertools.chain(*x))
woooee 814 Nearly a Posting Maven

There should be a "Mark as Solved" link below the last post.

woooee 814 Nearly a Posting Maven

Please make the post "Solved" so you aren't rude to those who would otherwise read this unnecessarily.

woooee 814 Nearly a Posting Maven

Dictionary keys have to be unique, so if you try to add a key that is already in the dictionary, it will not add a new key but write over the existing key, so add some code to test if the key already exists in the dictionary and print a message if it does. Finally, this code does not add to the dictionary on each pass through the loop but only adds the final pass, and I can't tell from the code if that is what you want to do or not so can't give any more help.

for b in miau2:
    print (b + '\n\n')
    l2.write(b + '\n\n')
    g +=1
 
dic[b]=i
woooee 814 Nearly a Posting Maven

And you might want to use a tuple for the key, ("man1", "car"), ("man1", "wallet"), etc. as a dictionary of dictionaries gets messy fast.

woooee 814 Nearly a Posting Maven

Check out the difference between copy and deepcopy as well. You probably want deepcopy (not a copy, and not a reference pointer to the list) since b is a list of tuples

a=[[(34,5),(34,6)],[(35,5),(35,6)]]
b=[(36,5),(36,6)]
a.append(copy.deepcopy(b))
JoshuaBurleson commented: good advice, didn't even think of it. +3
woooee 814 Nearly a Posting Maven

If you want to eliminate certain common words like "the and "and", etc. use a list.

omit_words = ["the", "a", "and", "but", "i"]
    for w in sorted_words[0:30]:
        if w not in omit_words:
woooee 814 Nearly a Posting Maven

The Tkinter keyword is "image" not "self.image"; see the example here. Also, a label is usually in a frame or some other container. Finally, you can not mix grid() and pack() so choose one or the other.

gmail=PhotoImage(file='gmail.gif')
self.lab=Label(image=gmail)
self.lab.photo=gmail
self.lab.pack()
woooee 814 Nearly a Posting Maven

You would bind <TAB> to a function that would set the focus to the next button. The program would then know which button the <RETURN> should be bound to. See the examples at this page. The program becomes more complicated if you also want to include a button click to set the focus. You would have to then bind <Button-1> to a function that determines the location of the mouse and sets the focus, also allowing the program to know that the <RETURN> is in an entry box or where ever.

woooee 814 Nearly a Posting Maven

You can pass the acceptable values to the checkInput() function and let it do the work. For the getFloat() function, use a try/except to test for correct input.

def checkInput(prompt, values_list):
    print "\n"
    while True:
        result = input(prompt).strip()
        if result.lower() in values_list:
            return result

        print("Please enter an appropriate value --> " + ", ".join(values_list))


deg = checkInput("Do you have Celsius, Fahrenheit, or Kelvin? ", \
                ['c', 'celsius', 'f', 'fahrenheit', 'k', 'kelvin'])
cdeg = checkInput("Convert to: Fahrenheit or Kelvin? ", \
                 ['f', 'fahrenheit', 'k', 'kelvin'])
print deg, cdeg


def getFloat(prompt):
    while True:
        result = input(prompt)
        try:
            return float(result)
        except:
            print("Enter a number only\n")

fcel = getFloat("What is the degrees in Celsius? ")
print fcel
TrustyTony commented: Good code (except not functions first) +13
woooee 814 Nearly a Posting Maven

However, for just the input(), I need to check to make sure it's not a number and to check to make sure it isn't blank

To make sure it isn't blank, check that len(variable.strip()) > 0
To make sure that it is not a number, you can use not variable.isdigit(), although a number with a comma or decimal point in it is not isdigit() so you can also use

found=False
for ltr in input_string.strip():
    if "a" <= ltr.lower() <= "z":
        found=True
if found...etc 
#
# list comprehension
x = [ltr for ltr in variable if "a" <= ltr.lower() <= "z"]
if len(x)
woooee 814 Nearly a Posting Maven

I would suggest that you print "ab" prior to the search. Since it is not passed to the class, the class has no idea what it is.

if __name__=='__main__':
    ab={'josh':'me'}
    AB=AddressBook(ab)  ## AB=class instance, ab=dict

class Interface(Frame):
    def __init__(self, master, AB_instance):
        self.AB_instance=AB_instance

        if query==self.AB_instance.book:

Interface(root, AB) 
#
##--------- or -------------------------------------------------------
if __name__=='__main__':
    ab={'josh':'me'}
#    AB=AddressBook(ab)  ## AB=class instance, ab=dict

class Interface(Frame):
    def __init__(self, master, ab_dict):
        self.ab_dict=ab_dict

        if query in self.ab_dict:  ## search for "josh"

Interface(root, ab)
woooee 814 Nearly a Posting Maven

A numpy array is accessed by row and column. Add some print statements to find out what the data looks like. Also, a numpy array is overkill. Read the records one by one and store/calculate the values. Start with some sample data that is small, say 10 records, so you don't have to go through all of the files and data each time. Also, read the directory tree and send each file name to a common function to process.

woooee 814 Nearly a Posting Maven

A class does not exist, it is a prototype for actual objects. Only a class instance exists. That is why we declare an instance for each class object desired.

class Person(object):
    def __init__(self, name, health=100):
        self.name=name
        self.health=100

    def hurt(self, amount):
        print("%s health = %d - %d" % (self.name, self.health, amount))
        self.health-=amount
     
class Killer(object):
    def __init__(self):
        import random
        power= random.randint(10, 21)
        self.power=power
        print("power:", self.power)
     
    def stab(self,Person):
        Person.hurt(self.power)
     
K = Killer()
James=Person('James')
Karen=Person('Karen')
K.stab(James)
K.stab(Karen)
K.stab(James)
JoshuaBurleson commented: Exactly what I needed. Rather than simply showing the code you explained the mechanical issue at hand. Great post! +2
woooee 814 Nearly a Posting Maven

As I see it, the function UUT_Info() does not know about __name__, wx, or InfoUUT() as they are all declared/defined somewhere else and not passed to the function, but without a complete error message there is no way to tell which name is undefined. You would use something like

from wx import *
import file_that_contains_InfoUUT

def UUT_Info():
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    Display = file_that_contains_InfoUUT.InfoUUT(None, -1, "")
woooee 814 Nearly a Posting Maven

"self" is just a reference to the class, so that the class knows that the function or variable is in it's name space, so you have to include it when calling a function of the class from/within the class, otherwise the compiler will default to looking outside of the class for the function or variable.

class OffSwitch(object):
    def __init__(self):
        self.keycheck='off'
        print self.keycheck

        self.turn_off('yellow')   
  
    def turn_off(self,key):
        self.keycheck = key
        print self.keycheck
     
OS = OffSwitch()
#
# outside the class
OS.turn_off("outside")
woooee 814 Nearly a Posting Maven

The solutions to all problems are blindingly obvious __after__ you know what it is. Also, you can check the database to make sure that there are pv0 recs with a SELECT * and a fetchall. If the resulting list has a length, then there are records.