woooee 814 Nearly a Posting Maven

Copied to preserve the code tags.

def program(List, Name, Detail):
    for entry in List:
        if entry[0] == Name:
            ## changed to add to the entry containing "Name" not 
            ## entry[1] as it is [Detail, Counter] so would become
            ## [Detail, Counter, [Detail_2, Counter_2]]
            entry.append([Detail,Counter])  ## "Counter" has not been declared
#-----------------------------------------------------------
#   return=You exit the function here if the name is found,
#   i.e. the following code is never reached and so is not
#   the problem
#-----------------------------------------------------------
            return
           
    List.append ([Name,[Detail]])
    for entry in index:           ## "index" is never declared
        if entry[0] == Name:
            entry[1].append(Counter)
woooee 814 Nearly a Posting Maven

Use a class and instance variables. You can call separate functions within the class using multiprocessing and they will all have access to the instance variables.

woooee 814 Nearly a Posting Maven

The else statement will execute for all input except 'n'. That includes upper case 'N'. You want something more along the lines of the following. Also, use a while statement to call the function multiple times. When level() calls itself you can reach the recursion limit.

choice = choice.lower()
    if choice in ['go south', 'south', 's']:
        print "You can't get through the trees to the south.\n"
        level()

    elif choice in ['go north', 'north', 'n']:
        import _level1
 
    else:
        print "I don't understand."
        print " "
        level()
HiHe commented: the way to go +5
woooee 814 Nearly a Posting Maven

.join() is more efficient than string concatenation, so I would expect to see at least one join(). Also, don't use "i", "l", or "O" in an interview.

for outer in range(1,13):
    print '\t'.join(str(outer*inner) for inner in range(1, 13))
woooee 814 Nearly a Posting Maven

You have to return the list that stores the textvariables and pass it to the next function. Also, you should really be using a class structure for this.

from Tkinter import *
from functools import partial

data = [
('a', 0, 'liters soda'),
('b', 0, 'liters beer'),
('c', 0, 'liters wine')
]

## Create grid, extracting infos from the data array
## Collect the text variables to list for use
def createWidgets(root, clist=[]):
    L=0
#    global c_w     no help
    first=0
    while L < len(data):
        cg_w=DoubleVar()
        clist.append(cg_w)
        l_w=Label(root, text=data[L][2])
        l_w.grid(row=L)
        c_w=Entry(root, textvariable=cg_w, width=3)
        c_w.grid(row=L,column=1)

        if L==0:
            first=c_w
        L+=1
    first.focus_set()
    return clist

## Example of simple function using values from an edited list (cl)
def Calc():
    L=0
    v=0
    lit=0
    for L,v in enumerate(cl):
        lit+=v.get()
    TotLiters.configure(text='%g' % lit)

def SetToZero(entries_list):
    """ set all textvariables in the input list to zero
    """
    for tk_var in entries_list:
        tk_var.set(0.0)

root=Tk()
root.title('Bar')
##
cl=[]

list_of_entries=createWidgets(root,cl)

compute = Button(root, text=' Total liters = ', command=Calc)
compute.grid(row=0,column=3)

reset = Button(root, text=' reset ',
               command=partial(SetToZero, list_of_entries))
reset.grid(row=2,column=3)

TotLiters=Label(root, width=10)
TotLiters.grid(row=0,column=4)

exit = Button(root, text='Exit', command=root.quit)
exit.grid(row=3,column=3)

root.mainloop()
woooee 814 Nearly a Posting Maven

The dictionary would have to contain lists as you can not duplicate keys in a dictionary, and you would then append to the list each time. So it would be

def common(dict_in, rec, update_dict):
    ...
            new_key = dict_in[key]
            ## add "700" or whatever the first time it is found
            if new_key not in update_dict:
                update_dict[new_key]=[]     ## key points to an empty list
            update_dict[new_key].append(extract_string[0])
    return update_dict
#
# then to write

    headers = ["100a", "100c", "100d", "100q", "245a"]
 
    for line in thelist_:
        for header in headers:
#                if line.has_key(header):
                 if header in line:     ## preferred over has_key
                    print line[header]

                    list_of_recs=line[header]   ## from the dictionary of lists

                    ## added to write each one individually
                    for item in list_of_recs:
                        fileout_.write('|%s' % (item))
                else:
                    fileout_.write('|')
        fileout_.write('\n')

I'm not too sure what you want to do so it this is not quite correct, adjust it a little and post back if there are other questions. And after all of this, it occurs to me to ask if an SQL database would work better. Doh!

woooee 814 Nearly a Posting Maven

There isn't enough data to be exact on the extraction process, but you can use a dictionary to test for "100", "245", etc. and call a function based on the key. I have used a common function to extract the data. If this is possible on all data types then the dictionary can be used to call the common function and send the proper sub-dictionary, otherwise the unique code can be included in each function. Note that the variable "list_" is changed to "dict_" since it is a dictionary. If this is not what you want provide more test data.

def common(dict_in, rec, update_dict):
    for key in dict_in:
        if key in rec:
            rec_as_list=rec.split(key)
            ## the string we want is now in rec_as_list[1]            
            extract_string=rec_as_list[1].split("$")
            new_key=dict_in[key]
            update_dict[new_key] = extract_string[0]
    return update_dict

def func_100(rec, dict_):
    ## =100  1\$aSomeauthor, John$d1746-1818.
    dict_100={"\\$a":'100a', "\\$c":'100c',"\\$q":'100q',"\\$d":'100d'}
    print rec
    dict_ = common(dict_100, rec, dict_)

    return dict_

def func_245(rec, dict_):
    ## =245  13$aSome title$hmicrosomething :$bla bla /$ctranslated from some language.
    dict_245={"$a":'245a', "$h":'245h',"/$b":'245b',"/$c":'245c'}
    print rec
    dict_ = common(dict_245, rec, dict_)
    return dict_


dict_={}
match_dict={"100":func_100, "245":func_245}
records=test_data.split("\n")
for rec in records:
    for key in match_dict:
        if rec.startswith("="+key):
            print "-"*50
            dict_=match_dict[key](rec, dict_)  ## call the function associated with this key
            print "dict_", dict_

And intead of all of the if() statements you can use a loop and write each row if the number in the current record (=001, =100 etc.) is less than the previous record's number=new group, and then write the final row of course.

for line in thelist_:
        if …
woooee 814 Nearly a Posting Maven

It is explained in this tutorial. Also a web search for "python string split" will turn up more examples. You can use a split and specify the character, or replace and then split() with the default=space(s).

woooee 814 Nearly a Posting Maven

You can also use a list of lists

letters_to_numbers= [['ABC', 2], ['DEF', 3]]
for test_it in ["A", "E", "C"]:
    print
    for group in letters_to_numbers:
        print "testing %s in %s" % (test_it, group[0])
        if test_it in group[0]:
            print "     the number for %s is %d" % (test_it, group[1])
#
# or match the letters and the element number of a list
#
print "-"*50
letters_to_numbers= ['*', '*', 'ABC', 'DEF']
for test_it in ["A", "E", "C"]:
    print
    for num, group in enumerate(letters_to_numbers):
        print "testing %s in %s" % (test_it, group)
        if test_it in group:
            print "     the number for %s is %d" % (test_it, num)
woooee 814 Nearly a Posting Maven

This statement will always yield True

elif decision == "north" or "east" or "west"
#
#It breaks down to 
    elif decision == "north" 
         or "east" 
         or "west"

and both "east" and "west" are not empty strings so either will evaluate to True. Instead use

elif decision in ["north", "east", "west"]:
ohblahitsme commented: That was really helpful! +1
woooee 814 Nearly a Posting Maven

This is a common exercise where you group records based on some indicator, an empty line in this case. This code prints the contents but you can also output to a file using .join)() and append a newline, "\n".

lit="""a=1
b=2
c=3

a=4
b=5
c=6
 
a=7
c=8
 
a=9
b=10
c=11"""

test_data=lit.split("\n")
this_group=[]
for rec in test_data:
    rec = rec.strip()
    if len(rec):     ## not an empty line
        this_group.append(rec)
    else:            ## is empty
        print_list=[]
        for value in this_group:
            ltr, num = value.split("=")
            print_list.append(num)
        print "   ".join(print_list)
        this_group = []     ## empty list for next group

## final group - prints differently
for value in this_group:
    ltr, num = value.split("=")
    print num+"  ",
print

Also if the want the a=7, c=8 group to print in the first and third columns, then you will have to test for the letter and place it in the correct column.

test_group=["a=7", "c=8"]
columns=["a", "b", "c"]
print_list = ["*", "*", "*"]
for rec in test_group:
    ltr, num = rec.split("=")
    col=columns.index(ltr)
    if col > -1:            ## letter found in "columns"
        print_list[col]=num
print "   ".join(print_list)
woooee 814 Nearly a Posting Maven

"board" contains references to the same list, not separate lists. The following code lists the id's which are the same. One item in one list in then changed. The print statement shows that all lists reflect the change. To generate one row, see the last line and then use a for() loop to generate multiple rows.

size=5
board = [[0] * size] * size
print board
for row in board:
    print id(row)
board[2][1]="X"
print board

row=[0 for ctr in range(size)]

my translation function is trying to iterate over None type

Include the full error message. No on wants to sift through 125 lines of questionable code to try and find it.

woooee 814 Nearly a Posting Maven

Lists are the easiest and quickest way to work with data IMHO. You can then join the elements into one string http://www.diveintopython.net/native_data_types/joining_lists.html.

a = "01101000011001010111100100000000000000000000"


b = "011000100111100101100101"

combined_list=[]
combined_list.append(b)
combined_list.append(a[len(b):])  ## slice off length of "b"
print "".join(combined_list)

## result
01100010011110010110010100000000000000000000
woooee 814 Nearly a Posting Maven

You have an infinite loop because all of the returns call main() again. BTW main is a bad name for a function because it is not descriptive. Some instructors use it in their beginning courses so as to not confuse the students with functions that have different names. In your case main() serves no purpose as you can just run the code without it. If you know lists, you can reduce a lot of the redundant code using a list.

def inches(start):
    convert_to = [["feet", 0], ["miles", 0], ["millimeters",0],
                  ["centimeters", 0], ["meters", 0], ["kilometers", 0]]
    for item in convert_to:
        print item[0]
    end = raw_input("Convert to? ")
    value = input("Value? ")
    convert_to[0][1] = value / 12.0      ## feet
    convert_to[1][1] = value / 63360.0   ## miles
    convert_to[2][1] = value * 25.4      ## etc
    convert_to[3][1] = value * 2.54
    convert_to[4][1] = value * 0.0254
    convert_to[5][1] = value * .0000254
    for item in convert_to:
        if end == item[0]:
            print "%s to %s, %7.2f = %7.2f" % (start, end, value, item[1])
start = raw_input ("Convert from? ")
inches(start)

Finally, the usual strategy is to convert everything to a common base and then convert from that common base to the desired unit, so there is one function that converts everything to inches or millimeters and passes that value to the conversion function, which reduces code in the remaining functions as they only have one unit to convert.

woooee 814 Nearly a Posting Maven

You have not declared Button1 in the code you posted so there is nothing to disable. But generally it is

b.config(state=DISABLED)

where "b" is the button's ID as returned by Tkinter. Also, you import Tkinter in two different ways (pick one only)

import Tkinter
from Tkinter import *

Do not mix wxPython and Tkinter

import Tkinter
import wx

"os.path" is available once you import os

import os
import os.path

And you only have to import subprocess once.

import subprocess
import subprocess as sp
from subprocess import Popen

One of Grayson's examples (click "He's dead" to disable)

from Tkinter import *

def disable_button():
    b1.config(state=DISABLED)

root = Tk()
root.title('Buttons')
Label(root, text="You shot him!").pack(pady=10)
b1=Button(root, text="He's dead!", command=disable_button)
b1.pack(side=LEFT)
Button(root, text="He's completely dead!", command=root.quit).pack(side=RIGHT)
root.mainloop()
woooee 814 Nearly a Posting Maven

In the OnPlus function, the program will sleep for 1*5000 seconds which is about 1 1/2 hours. In the OnMinus function also, you add/subtract one from value but it has no meaning i.e is not displayed. You should test each function individually as you create it, otherwise you will be stuck with a large block of code and no idea where the error is. Finally, please read the Python Style Guide concerning naming conventions. It makes code easier to read and understand.

woooee 814 Nearly a Posting Maven

Come up with a test suite, with known numbers and known results to test with. Also, you don't know if multiplication or division is done first so this line
a= (sum1 / r*1.0)
can lead to unexpected results. And I think that multiplication and division would evaluate left to right, so division would be done first=division result is an integer*1.0. Print the result to see for yourself. Instead, convert the numerator or denominator to a float as you do later in the code, or convert "r*1.0" on a separate line or add parens.

Don't use the same name as in can confuse the compiler in some situations.

def SD():
    .....
    SD = (float(L)/r)**0.5
vegaseat commented: good point +15
woooee 814 Nearly a Posting Maven

The error appears to be on the previous line. First, make sure that this is actually a Python3 package and not a Python2 package. There are many packages that have not been ported to Python3x.

woooee 814 Nearly a Posting Maven

Instead of the dictionary, which is fine, you can add 12 to the time if "PM" and less than 12. And another point that is picky for the example, but relevant in other things you might do, is to use endswith instead of in, to only catch AM of PM if they are at the end of the string.

t_lower = tstr.strip().lower()
	if t_lower.endswith("am"):
		return am[a[0]] + a[1][:2] + 'hr'
	elif t_lower.endswith("pm"):
		return pm[a[0]] + a[1][:2] + 'hr'
        else:
            return "ERROR in " + tstr
woooee 814 Nearly a Posting Maven

since 1 is less than two

Then it is not one. Add a print statement to show what is being compared.

def Fitness(a,b,c):
	      f = [a,b,c]
              print "comparing", f[0:2], "against 2, 3, and 4"
	      if f[0:2] >= 4 and sum(f) >= 13:
		      print 'Gold'
	      elif f[0:2] >= 3 and sum(f) >= 10:
		      print 'Silver'
	      elif f[0:2] >= 2 and sum(f) >= 7:
		      print 'Pass'
	      else:
		      print 'Fail'

Also, store the sum in a field instead of calculating it several times, and min will give you the smallest number in the list.

def Fitness(a,b,c):
    f = [a,b,c]
    total = sum(f)
    smallest = min(f)
    if smallest >= 4 and total >= 13:
        print 'Gold'
    ## etc.
woooee 814 Nearly a Posting Maven

Indents are incorrect

ag_fname = wx.FileDialog(self, defaultFile="", style=wx.OPEN)
        if ag_fname.ShowModal() == wx.ID_OK:
            gif = ag_fname.GetPath()
 
            gif1 = wx.animate.GIFAnimationCtrl(panel, id, gif, pos=(75,10),
                                            size=(200,200))
            gif1.Play()
        else:
            print "Could not find the file"
woooee 814 Nearly a Posting Maven

the gif-frame stops but the tiny Tk-win wont stop

The stop button is only bound to the wxpython widgets. You would have to have a separate stop button in Tkinter, or as stated above, the usual process is to code everything using the same tool kit.

woooee 814 Nearly a Posting Maven

Assuming both files are the same length (if they are not you will have to account for that), use the same offset for each list, i.e. record 1 from file a-->record 1 from file b

for ctr in len(energy_in):
    ## print them for testing
    print energy_in[ctr], slab_in[ctr]
    energy=energy_in[ctr].split()
    ##for j in slab_in:
    slab=slab_in[ctr].split()

    if energy[0] == slab[0]:
        x = "%0.7f" % (float(energy[1])+float(slab[1]))
    else:
        print "Recs not equal", energy, slab

If you want to find all "A"s and add them together, and the files do not correspond, then you should use a dictionary.

Pls can someone

Please don't turn this forum into a high school.

woooee 814 Nearly a Posting Maven

Just test for it and eliminate the trailing period

test_text="prob=0.345."
test_text = test_text.strip()
if test_text.endswith("."):
    print test_text[:-1]
    print test_text[:-1].split("=")
woooee 814 Nearly a Posting Maven

Christmas marks the birth of Christ, and it is celebrated by Christians around the world. But this holiday has close ties to an older festival known as the "Unconquered Sun." The impact this Pagan tradition had on how Christmas was celebrated is one of the ways in which The Christian tradition changed as it developed through the ages.

December 25th was the date of the winter solstice in the calendar Julius Caesar devised for Rome in 46 BC. Today the winter solstice usually occurs on December 21st. Although Caesar used a 365 1/4 day year, a year is actually a little shorter, and this made the solstice occur a little earlier over the years. There was a discrepancy of 1 day in 128 years.

There is nothing in the Christian Bible to specify the day of Christmas. Prior to the fourth century, Christ’s birth had been associated with Three King’s Day on January 6. But the pagans and the newly converted were being a major problem to the church because they were still celebrating the Unconquered Sun. Nothing the church did or said made a difference; the winter solstice was just too important a festival.

What the Christians did in this dilemma, was execute a move seen over and over in history. If you can’t defeat them, and refuse to join them, at least make it appear that you defeated them. Sometime between AD 354 and 360 a few decades after Emperor Constantine’s conversion to Christianity, the …

woooee 814 Nearly a Posting Maven

That is not list append, but a list insert. Another way to do it to create a new, third list by appending list 1 until "+++++++" is found, then append list 2, then append the rest of list 1.

woooee 814 Nearly a Posting Maven

You either use the grid manager or a separate Frame for each set of 3 buttons.

from Tkinter import *
 
class GUI():
    def __init__(self, r):
        self.r = r
 
        self.i = StringVar()
 
        self.f = Frame(self.r)
        self.f.pack(fill = BOTH)
 
        self.g = LabelFrame(self.f, text = 'Groupbox 1', height = 90, width = 150, font = 'Lucida 8')
        self.g.pack_propagate(0)
        self.g.pack(side = LEFT, pady = 10, padx = 10)
 
        self.id = Entry(self.g, justify = CENTER, textvariable = self.i, font = 'Lucida 8')
        self.id.pack(pady = 22)
 
        self.opt = LabelFrame(self.f, text = 'Groupbox 2', height = 90, width = 200, font = 'Lucida 8')
        self.opt.pack_propagate(0)
        self.opt.pack(side = TOP)
 
        f1 = Frame(self.opt)
        for ctr in range(3):
            but = Button(f1, text = 'Button '+str(ctr+1), height=1, width=5, font='Lucida 8')
            but.pack(side = LEFT, anchor = N, pady = 5, padx = 4)
        f1.pack(side=TOP) 
 
 
        f2 = Frame(self.opt, height = 50, width = 200)
        for ctr in range(3):
            but = Button(f2, text = 'Button '+str(ctr+4), height=1, width=5, font='Lucida 8')
            but.pack(side = LEFT, anchor = N, pady = 5, padx = 4)
        f2.pack(side=BOTTOM)

t = Tk()
t.title('test')
#t.configure(bg = 'white')
t.geometry('400x120')
t.pack_propagate(0)
 
GUI(t)
t.mainloop()
woooee 814 Nearly a Posting Maven

The main problem is that you don't pass board to the function, update it, and then return the new board. Consider using a list instead of a string as it makes things much easier. Also use a loop to get the input instead of 5 separate sets of statements.

import random
 
def compturn(board):
    print 'Computer turn:'
    comp = str(random.randint(1, 9))
    while comp not in board:     ## occupied
        comp = str(random.randint(1, 9))
    """
	if comp == a:
		compturn()
	elif comp == b:
		compturn()
	elif comp == c:
		compturn()
	elif comp == d:
		compturn()
	elif comp == e:
		compturn()
	elif comp == f:
		compturn()
	elif comp == g:
		compturn()
	elif comp == h:
		compturn()
	elif comp == i:
		compturn()
	else:
    """
    board=board.replace(comp, "O")
    print "computer moves to square", comp
    print board
    return board
 
print """ I have yet to make a device that tells you if you win but enjoy!"""
 
board = """ 1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9 """
print board
 
move1 = raw_input('Where do you want to place your X? ')
#a = b = c = d = e = f = g = h = i = move1
board = board.replace(move1, "X")
print board
 
board=compturn(board)
 
#b = comp
 
move2 = raw_input('Where do you want to place your X? ')
#c = d = e = f = g = h = i = move1
board = board.replace(move2, "X")
print board
 
board=compturn(board)
 
#d = comp
 
move3 = …
woooee 814 Nearly a Posting Maven

The easiest to understand is to store the previous record, and find the number for the record previous to the ">" record.

seq=""">s1\n
 MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD\n

 >s2\n
 MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP LRDLLMFPMEDISISVIGRQRRTVQSTVPEDAEKRAQSLFVKECIKTYSTDWHVVNYKYE DFSGDFRMLPCKSLRPEKIPNHVFEIDEDCEKDEDSSSLCSQKGGV\n"""

split_seq = seq.split("\n")
name = ""
pattern = 0
previous_rec = ""
for line in split_seq:
    line = line.strip()
    if line.startswith('>'):     ## print previous name and use previous record
        if len(name):            ## first ">" won't have a previous
            pattern = previous_rec.count('P') 
            print '%s:%s' %(name,pattern)
        name=line
    else:
        if len(line):            ## skip any empty lines
            previous_rec = line

if len(name):
    pattern = previous_rec.count('P') 
    print '%s:%s' %(name,pattern)
woooee 814 Nearly a Posting Maven

You can do it this way, but it would be better to use a for() loop:

ctr = 0
line1 = myFile.readline()
while line1:
    myOut.write(line1.strip("\n"))     ## 4 records without end-of-line
    ctr += 1
    if ctr > 3:                    ## 4 records written
        myOut.write("\n")
        ctr = 0

    line1 = myFile.readline()
woooee 814 Nearly a Posting Maven

Use a list of lists

card_list = [ [], [], [], [], [], [], [] ]
x = 0
while x < 7:     ## number of cards to be dealt to each hand
    ## each for() loop deals one card to each of the hands in card_list
    for ctr in range(len(card_list)):     ## = 7 (# hands in card_list)
        card = mydeck.deal()
        if card != None:
            card_list[ctr].append(card)
    x += 1  
for hand in card_list:
    print hand

or a dictionary which is similiar

card_dict = [1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[] ]
x = 0
while x < 7:
    for ctr in range(1, 8):
        card = mydeck.deal()
        if card != None:
            card_dict[ctr].append(card)
    x += 1
for ctr in range(1, 8):
    print card_dict[ctr]

Also note that you have an infinite loop as you reset "x" so it will never be greater than 7.

Gribouillis commented: very clear explanation +13
woooee 814 Nearly a Posting Maven

I mean how could I do this?

Pass a parameter to the function, and return the desired result as many times as you want. You can start at "A first program" here and also here and here. No on wants to do this for you as it is simple and is something you can do for yourself, and should understand if you are going to write programs.

woooee 814 Nearly a Posting Maven

ouyay areyay elcomeway

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 open movies.txt twice and don't close either one. Delete line #5, the first open is not used. It would work better if you open the file in a function.

def view_existing():
    all_movies = open("movies.txt", "r").readlines()
    ## print the all_movies list and allow the user to select one
    ## something like this, although this is simplified
    for ctr, rec in all_movies:
        name, genre, desc = rec.strip().split("**")
        print "%5d  %-20, %-20s %-s" % (name, genre, desc)


def add_new_movie():
    fp_out = open("movies.txt", "a")

    enter_another = True
    while enter_another:
        msg='Please enter the name of the movie'
        # etc.
        myString = "**".join(fieldValues)  ## the fields require a delimiter for reading
        fp_out.write("%s\n" % (myString))

        msg="Enter another movie?"
        # etc.

    fp_out.close()
huntaz556 commented: this helped alot ! thanks +1
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

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

I you want to use Tkinter then you should also install the Pmw extension. It makes things much easier IMHO, and is a collection of Python/Tkinter files that extend Tkinter. That means it is easy to install as it is installed by copying to anywhere in your PYTHONPATH (sys.path). This is how it would be done with Pmw. Click on any item to print that item to the console.

import Tkinter
import Pmw

class PMWListBox :
   def __init__( self, list_in, min_width=300, min_height=300 ) :
      self.top = Tkinter.Tk()
      self.top.geometry( "300x300+10+10" )
      self.top.minsize( min_width, min_height )
      self.top.option_add('*Font', 'Fixed 14')
      
      Pmw.initialise( fontScheme='default')

      #---  exit button must be first----------------------
      exit = Tkinter.Button(self.top, text='EXIT',
             command=self.top.quit, bg='lightblue', fg='yellow' )
      exit.pack(fill="x", expand=1, side="bottom")

      #----------------------------------------------------------------
      self.sl_box = Pmw.ScrolledListBox( self.top, listbox_selectmode="SINGLE", \
               items=(list_in), selectioncommand=self.getit_2 )
      self.sl_box.pack(fill="both", expand=1, padx=5, pady=5, side="top" )
  
      #----------------------------------------------------------------
      self.top.mainloop()

   def getit_2(self):
#      print "getvalue", self.sl_box.getvalue()
      print "getcurselection", self.sl_box.getcurselection()

##===================================================================
if __name__ == "__main__" :
   list_items = [ "First List Entry", "Second List Entry", \
                  "Third List Entry", \
                  "Fourth List Entry -- W I D E -- W  I  D  E", \
                  "Fifth List Entry", "Sixth Entry", "Seventh Entry", \
                  "Eighth Entry", "Ninth Entry", "Tenth Entry", \
                  "Entry # 11 Test", "Test for 12th Lit", \
                  "Thirteen", "Fourteen", "Fifteen" ]
   PM = PMWListBox( list_items )
Gribouillis commented: great and stylish +13
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

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

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

Adding print statements will tell you what is going on.

for line in in_file:
 print "line =", line
 number = line.split()
 print "number =". number
 for col in number[0]:
  print "comparing", col, number[3]
  if col == number[3]:
   print number[0], number[1], number[2], number[4]
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

I don't know about anyone else, but I'm getting a little tired of the "I goggled for this" lie http://tinyurl.com/3ldotwl Perhaps we should boycott the too obvious fibs and point them out as above.

Edit: But then I guess that's the same thing, as that's doing the search effort which provides the lazy with the code from the search. Back to pointing out the "we only help those who show effort" links. They are http://www.daniweb.com/software-development/computer-science/threads/573
http://www.daniweb.com/software-development/computer-science/threads/573/3625#post3625
http://www.daniweb.com/software-development/cpp/threads/78223

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

Damn pyguy62, that's quite a bit of effort. Hopefully it will be appreciated. Look at the indentation after line 55. I hope you read this before the 30 minute limit is up.

To sort by value can also be done with

from operator import itemgetter
print sorted(word_count.items(), key=itemgetter(1))

but homework probably means the OP is supposed to write a sort method.

The comments looked much nicer in IDLE

IDLE probably uses a fixed width font, i.e. all letter have the same width. A browser generally used a proportional font, i.e. "i" takes up less space than "w", so I just post what I have and ignore the misaligned comments.

JoshuaBurleson commented: good eye. and thanks for the itemgetter reference! +4
woooee 814 Nearly a Posting Maven

From a thread on another forum, I wondered how difficult it would be to create a Tic-Tac-Toe game that could not be beaten. Since it is easiest if the computer goes first and chooses the center square, this code implements that portion. The logic is fairly simple; occupy the center square as that removes both diagonals and both middle options for the opponent. Then choose a corner square since it removes two of the remaining options, leaving two only. Before every move, check for two in a row that can lead to a win or a block of the opponent. I suppose it could be improved a little and pick a square where there are 3 that are not occupied, and so a possible win, but this is all the time I have for now.

TrustyTony commented: Thanks for demonstration of tkinter wait_variable +13
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