woooee 814 Nearly a Posting Maven

Key in "python first last middle name" in the Daniweb search box. You are one of many asking this question.

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

You don't test for distance becoming negative (which is also a "True" condition-only zero is False) and you want to count the number of steps. As it is now, "steps" will always be slightly greater than 1000 since you add steplen every time. Figure it out by printing where necessary.

""" This is NOT a correct solution
"""
import random

def randomSteps(minStep, maxStep, distance):
    steps = 0
    while distance > steps:  ## changed but not what you want to do
        steplen = random.randint(minStep, maxStep)
        steps += steplen
#        distance -= steplen
        print steplen, steps, distance

    return steps
 
print(randomSteps(2, 5, 1000))

should it be:
step += minStep

Random guessing doesn't count. Figure it out one part at a time and then code it, so first get the while() loop to exit properly before you declare any other variables, then continue on.

woooee 814 Nearly a Posting Maven

So what's new? Don't we always take the round-about way to get somewhere.

woooee 814 Nearly a Posting Maven

If you have 5 rooms shaped as a plus sign, with room #5 in the middle, you would create the relationships with a dictionary as follows.

def room_function(room_no):
    print "running function for %s" % (room_no)

"""
    room #1=North clockwise so room #4=West and room #5=the middle
    rooms_dict is keyed on the room number and points to the direction
    that the player can move from this room and those room number(s)
"""

rooms_dict={1:("S", "5"),
            2:("W", "5"),
            3:("N", "5"),
            4:("E", "5"),
            5:("NESW", "1234")}

room_no=5
to_go="N"
direction, new_room_no = rooms_dict[room_no]
if to_go in direction:
    idx=direction.find(to_go)
    next_room=new_room_no[idx]
    print "go %s to room number %s" % (to_go, next_room)
    room_function(next_room)
woooee 814 Nearly a Posting Maven

You should put this in a function that you can call repeatedly instead of duplicating code.

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

Let us know how this is going whether you are successful or not.

woooee 814 Nearly a Posting Maven

You would substitute a record from a file in place of the raw_input and send it to the function named "change". Opening and reading files.

woooee 814 Nearly a Posting Maven

You are finding the last name to get to the end of middle name. I am finding the last space.

woooee 814 Nearly a Posting Maven

Isn't "a boad" a place where you live (sorry couldn't pass that up). An easy to understand example follows. You will have to substitute the variable for the hard-wired ">", and come up with some decent code to input things, as well as

"or print Invalid board! if the board does not match the length and height, or the contents of the board are not integers and/or strings"

as you haven't even made a decent attempt. Your code is not properly indented and will give an error on the "board= rawinput()" statement. "Thinking in Python" has a section on keyboard input and converting input to integers.

test_list=[1,0,0,1,0,0,2,0,0,0,0,0,3,0,0,0,0,0,4,0]
ctr=0
for item in test_list:
    print item,
    ctr += 1
    if ctr > 4:
        ctr=0
        print
print
#
# you can also do it with 2 for() loops
for out in range(0, len(test_list), 5):
    for inner in range(5):
        print test_list[out+inner],
    print
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

The first column of a list is row[0].
The last column of a list is row[-1] or row[len(row)-1] = same thing

woooee 814 Nearly a Posting Maven

Your indentation is incorrect so it is difficult to tell what you are trying to do.

"i" will never equal -1 (and you should not use "i", "l" or "O" as they can look like numbers)

elif i==-1:

And this statement does not make sense because you seem to be calling two functions and assigning the return value to "a".

a=(row-i)(i-1)

You might want to look through something like Thinking in Python to get you started. Hopefully this will help you.

h=input("Please enter the height: ")
 
for row in range(0,h):
    new_row=['1' for ctr in range(row)]
    new_row.append("1")       ## "1" extra required
    print new_row
woooee 814 Nearly a Posting Maven

You can simplify this as follows (continue and sometimes break often signifies a better logic exists).

import random
 
#i [I] think you wanted strings here
#r = "rock"
#p = "paper"
#s = "scissors"
 
#a list of the weapons
weapons = ["rock", "paper", "scissors"]     ## separate variables are not necessary
 
#you need to indent everything you want looped
user_choice="" 
while user_choice.lower() not in weapons:
 
    #raw input is usually used instead of input - see the docs
    #-----> unless OP is on Python3X
    user_choice = raw_input("Choose yer weapon [rock/paper/scissors]: ")
    if user_choice.lower() not in weapons:
        print "%s is not a valid choice!" % user_choice
 
print "You wield the mystical %s of +1 Awesomeness." % user_choice
computer_choice = random.choice(weapons)
print "A wild programmer appears, swinging a deadly %s!" % computer_choice
woooee 814 Nearly a Posting Maven

You really only need to use the first and last space, but count can be used to find how many spaces to index.

fullname = "one two three four five"
ct = fullname.count(' ')
idx=0
idx_list=[]
for ctr in range(ct):
    idx=fullname.find(" ", idx)
    idx_list.append(idx)
    idx += 1
print idx_list

first=fullname[:idx_list[0]]
print first
middle=fullname[idx_list[0]+1:idx_list[-1]]
print middle
last=fullname[idx_list[-1]+1:]
print last

#easier
idx_first=fullname.find(" ")
idx_last=fullname.rfind(" ")
print "\n", idx_first, idx_last
first=fullname[:idx_first]
print first
middle=fullname[idx_first+1:idx_last]
print middle
last=fullname[idx_last+1:]
print last
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

I wondered how difficult it would be to use a string/list of single bytes for the hangman picture and substitute the single byte every time there is an incorrect guess. Not too difficult, but it may not be worth the time either.

def print_hangman(list_in, wrong_guess):
    print "*"*30
    print "".join(list_in)
    lit = "%d wrong guess" % (wrong_guess)
    if 1 != wrong_guess:
        lit += "es"
    print lit

hangman_pic='''
 
  +---+
  |   |
      |
      |
      |
      |
      |
========='''

wrong_guess_pic = [("O", 21),
                   ("|", 29),
                   ("/", 28),
                   ("\\", 30),
                   ("|", 37),
                   ("/", 44),
                   ("\\", 46)]

new_pic = list(hangman_pic)
wrong_guess=0

## simulate wrong guesses
for ctr in range(len(wrong_guess_pic)):
    tup = wrong_guess_pic[wrong_guess]
    new_pic[tup[1]] = tup[0]
    wrong_guess += 1

    print_hangman(new_pic, wrong_guess)
woooee 814 Nearly a Posting Maven

If you are using Python3.X input is fine. If you are using Python2.x then input captures numbers, and raw_input captures strings.

woooee 814 Nearly a Posting Maven

Use
GetValue().decode('utf-8'))
or what ever character set you wish. Generally, when using a non-English language, you have to use .decode(). AFAIK-which isn't much when it comes to this-
# -*- coding: utf-8 -*-
means the program code can be written in utf-8 characters, so you can use Greek letters in variable names, etc. within the program itself.

If you get a

UnicodeDecodeError: 'utf8' codec can't decode byte X in position Y: invalid continuation byte

you are using the wrong encoding and Greek may be "iso-8859-7" but you will have to research that yourself.

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

2**218 = 421249166674228746791672110734681729275580381602196445017243910144 and
2**50 = 1125899906842624
Either one is going to take a long time. As Tony said you should be using the decimal module.

this is my program maybe you can find a solution
it works but when numbers very big such as 2**50 it don't

Not unless there is a mind reader here who can intuit what "it don't" means. I don't think any one is going to waste hours running the code through bigger and bigger numbers until they find out what "it don't" means.

woooee 814 Nearly a Posting Maven

This code will test every row up to and including the correct row.

for row in range(len(matrixM)):
		if(matrixM[row][0] >= number):  ## greater than all lower rows

If you have a large table this will affect the time it takes. It appears you still have some test code in the program

if(number > matrixM[3][0]):
			for column in range(len(matrixM)):
				if(matrixM[3][column] == number):
					return 3, column

In any case it should not be under the for() and execute on every pass through the loop. The best way to check times is to use a profiler on the code. It will tell you how much time was spent in each part of the code.

woooee 814 Nearly a Posting Maven

2 text fields requires 2 Entry (Dialogs). Although TextCtrl is generally used. A standard example for entering user name and password.

import wx

class TextFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100))
        panel = wx.Panel(self, -1) 
        basicLabel = wx.StaticText(panel, -1, "Basic Control:")
        basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1))
        basicText.SetInsertionPoint(0)

        pwdLabel = wx.StaticText(panel, -1, "Password:")
        pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),style=wx.TE_PASSWORD)
        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
        panel.SetSizer(sizer)

app = wx.PySimpleApp()
frame = TextFrame()
frame.Show()
app.MainLoop()
woooee 814 Nearly a Posting Maven

You check self.hit and self.miss, not the remaining empty squares (so there is some discrepancy between the lists).

def check_hit_miss(self, coodinate):
        '''return True if coodinate in board.hit or board.missed,
        return False otherwise.
        '''
        if (coodinate in self.hit) or (coodinate in self.missed):
            return True
        else:
            return False
#
# change to
        if coordinate in self.remaining_ships:
woooee 814 Nearly a Posting Maven

You should usr "r" instead of guess, and you have to add the letters guessed to letter-g.

r= input("How many rounds do you want to play? (even number only) ")
r=int(r)
 
print (" You only get %d turns to guess the letter" % (d))
print ("Player 1's turn to play the game")
 
 
#guess = 6
letter_g=[]
while r !=0:    letter = input('Guess a letter (a-z): ')
    if letter in letter_g:
        print('Please enter another letter')
    else:
        letter_g.append(letter)
        r = r - 1
woooee 814 Nearly a Posting Maven

You possibly add to the dictionary on line 50, although we can't tell from the code if it is adding a new key or updating an existing one.
FID_GC_dict[Cur_FID] = lr_Value
You possibly want to use a copy of the dictionary and should add some print statements to see what is happening.

woooee 814 Nearly a Posting Maven

The simplest is to use a dictionary

classes_taken={classlistA:["CMSC 201", "CMSC 202", "CMSC 203"],
               classlistB:["MATH 151", "MATH 152"]}
etc.

If you want to use lists then you can just transfer the classes taken to the list, so you would have 3 classes_taken lists or one list with 3 sublists. You can also use one list in this way

print "This program returns a list of classes you still have to take: "
classlistA = ["CMSC 201", "CMSC 202", "CMSC 203", "CMSC 304", "CMSC 313",
              "CMSC 331", "CMSC 341", "CMSC 345", "CMSC 411", "CMSC 421",
              "CMSC 441"]
classlistB = ["MATH 151", "MATH 152", "MATH 221"]
classlistC = ["STAT 334" ,"STAT 451"]

# simulate this data was entered
test_data = ["CMSC 201", "CMSC 202", "STAT 334", "MATH 151", "MATH 152"]
set_test_data=set(test_data)

## print classes to be taken
letters = ["A", "B", "C"]
for ctr, classlist in enumerate([classlistA, classlistB, classlistC]):
    print "You have not taken the following classes in %s" % (letters[ctr])
    for this_class in classlist:
        if this_class not in test_data:
            print "     ", this_class

    print "\nEven easier with sets"
    print set(classlist).difference(set_test_data), "\n"
woooee 814 Nearly a Posting Maven

File "check.py", line 30, in checkvalue
elif(matrixM[row+1][0] < number):
IndexError: list index out of range

I did not state the reason for the range(1, len(matrix)) You get the error message when you access the last row
for row in range(1, len(matrix)):
and then use
elif(matrixM[row+1][0] < number)
i.e row+1 does not exist when you are on the final row. Instead you can iterate through row-1 with your code, or start at 1, not zero, through the last row, and look at row-1 (check_row = row-1) as in my code
for row in range(1, len(matrix)):

Also there is an error in the code above
if number <= matrix[row][0]:
should read
if number < matrix[row][0]:
Testing usually catches some mistake.

woooee 814 Nearly a Posting Maven

Based on the sample data you provided, it would be simpler to find the row that starts with a number greater than the one you are looking for and check the previous row.

def compare_columns(matrix, number):
    for row in range(1, len(matrix)):
        if number <= matrix[row][0]:
            ## number is less than first element so check previous row
            check_row = row-1
            for col in range(len(matrix[check_row])):
                if number == matrix[check_row][col]:
                    return check_row, col
            return -1, -1     ## not found in this row

    ## last row
    row = len(matrix)-1
    for col in range(len(matrix[-1])):
        if matrix[row][col]==number:
            return row, col
    return -1, -1    ## not found
 
matrix = [[2,4,6,8],[10,12,14,16],[20,22,24,26],[28,30,32,34]]
print compare_columns(matrix, 22)
print compare_columns(matrix, 34)
print compare_columns(matrix, 23)
woooee 814 Nearly a Posting Maven

You have to know the relative coordinates of the square and create text usually at a middle location. You will probably want to set the font to use and it's size. To modify your drawing

X1      X2    X3    X4
       Y1      |     |
               |     |
       Y2 _____|_____|_____  
               |     |
               |     |
       Y3 _____|_____|_____  
               |     |
               |     |
       Y4      |     |

you have to know, or be able to calculate these points to draw the lines and place the text. So the 6th square=row 2, column 3. Place and "X" or "O" half way between X3 and X4 for the x value and half way between Y2 and Y3 for the y value. This info can be stored in a list so you can pass the square number and use the list to convert the square number to begin and end coordinates for x and y. If you have problems with the code you generate, post back with the code, and ask any specific questions.

woooee 814 Nearly a Posting Maven

Most of the online tutorials cover input and conversion from on data type to another.

woooee 814 Nearly a Posting Maven

You should also check for values between a certain range, i.e. someone can not enter one million or a letter.

woooee 814 Nearly a Posting Maven

Vegaseat has a nice example in the "Python GUI Programming" sticky, but I refuse to be someone else's research assistant. If memory serves it is somewhere in the middle of the thread's pages.

woooee 814 Nearly a Posting Maven

Assuming "How high" means the number of rows to print, use a for() loop instead:

for ctr in range(num2):
    print "row number", num+1

A link to getting input from the user. It's for Python 2.x but can be easily modified for 3.x.

woooee 814 Nearly a Posting Maven

A similar question on Daniweb http://www.daniweb.com/software-development/python/threads/58916. Note how the lists are created and accessed. There are more examples here and on the web. Search for "list of lists". It is very common with many examples so there is no reason to reinvent the wheel here.

woooee 814 Nearly a Posting Maven

Dive into Python has a chapter on installing Python for both the Python.org and ActiveState versions.

woooee 814 Nearly a Posting Maven

print_max is the maximum number to print on one line. A variable is used so it can be any number input.

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

Quoted to include [code] tags.

Hello guys,

just joined the community. Found it through google. :)

I am basically new to python, only couple of days of knowledge. I am trying to
make all the words in a txt file appear in 4 or 5 in a row.

so the txt file looks like this:

!algiers!
!atlanta!
!baghdad!
!bangkok!
!beijing!
!bogota!
!buenos aires!
!cairo!
!chennai!
!chicago!
!delhi!
!essen!
!ho chi mihn ci
!hong kong!
!istanbul!
!jakarta!
!johannesburg!

and the out put should be:

!algiers! !atlanta! !baghdad! !bangkok!
!beijing! !bogota! !buenos aires! !cairo!

This is the code I used so far

f = file('cities.txt','r')

while True:
    line = f.readline()
    if len(line) == 0:
       break
    x= line.strip()
    x= '!'+x+'!'
    x= x[0:15]
    x= x.rjust(15)
    print x

Use a counter (code is not tested but for illustration only).

f = file('cities.txt','r')

print_max=5
ctr=0
for line in f:
    x = line.strip()
#    x= '!'+x+'!'
#    x= x[0:15]
#    x= x.rjust(15)
    print x,     ## note the comma
    ctr += 1
    if ctr >= print_max:
        print
        ctr = 0
print     ## newline for final print
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

Washington, D.C. driver Danny White thought he had a really good idea for a joke. But the joke's on him--to the tune of $20,000, reports local affiliate NBC4.

White's prank started 25 years ago when he got a vanity license plate reading, "NO TAGS." He told NBC4 that he was "Just having fun!" and that "D.C. don't get the joke. They don't get it."

The issue? Each time a car without proper identification is cited for a violation, a DMV employee enters "NO TAGS" into their paperwork. Because White's vanity plate is registered with the District of Columbia's DMV, his name and vehicle appear in the computer's system whenever a "NO TAGS" violation is entered. Notices for the fines are then mailed to White's residence.

woooee 814 Nearly a Posting Maven

From your original code

name = 'francis ford coppola'
space=name.find(" ")
first=name[:space]
 
remaining_name=name[space+1:]     ## skip the space
space=remaining_name.find(" ")
middle=remaining_name[:space]
last=remaining_name[space+1:]
 
print(first)
print(middle)
print(last)
woooee 814 Nearly a Posting Maven

Some of those codes you posted I have not learned yet. The teacher wants us to post the first middle and last names on 3 separates lines using the whitespaces as the indexes

You did not state any limitations in your question, so how are we to know what you do and do not know, and it is unreasonable to expect others to come up with solution after solution until you find one you like.

name = 'francis ford coppola'
first_name=""
middle_name=""
this_name=""
ctr=0
for ltr in range(len(name)):
    print "testing letter", name[ltr]
    if name[ltr]== " ":
        if ctr==0:
            first_name=this_name
            print "     ", this_name, "to first_name"
        elif ctr==1:
            middle_name=this_name
            print "     ", this_name, "to middle_name"
        ctr += 1
        this_name=""
    else:
        this_name += name[ltr]
        print "this_name is now", this_name
last_name=this_name
print "-"*30
print "first_name", first_name
print "middle_name", middle_name
print "last_name", last_name
woooee 814 Nearly a Posting Maven

That's because of the while() loop in the function. Instead keep track of the number of times the button is clicked.

from Tkinter import *
class App:
 
    def __init__(self,master):
 
        self.master=master
        self.returned_values = {}
        frame = Frame(master)
        frame.grid()
 
        self.Answer_entry = Entry(master)
        self.Answer_entry.grid(row = 0, column = 1, sticky=W)
        self.Answer_entry.focus_set()
        User_Answer=self.Answer_entry.get()
        self.attempts = 0 #sets the attempts = to 0 to start the loop
 
        self.exampleAnswer(master)
 
 
    def exampleAnswer(self,master):
        Answer = 'exampleAnswer'
        self.CheckAnswerButton = Button(master, text="Check Answer", command=lambda: self.Check_Answer(Answer))
        self.CheckAnswerButton.grid(row = 1, column = 3, sticky = S)
    # answer defined in seperate function as it would be in prog
 
 
    def Check_Answer(self,Answer):
 
##        while 1: #starts infinite loop that will stop when break point hit
 
            User_answer= self.Answer_entry.get()#gets users Answer entry
            print User_answer    
 
            if User_answer != Answer: #checks if the user answer = the stored answer
 
                if self.attempts >= 10:
                    self.returned_values['attempts'] = self.attempts
                    self.master.quit()
#                    break #breaks the loop if the user has had 10 attempts
#                else:
                self.attempts += 1 #adds one to attempts and repeats the loop
 
            else: #only reaches this if there input is correct
                self.returned_values['attempts'] = attempts #global variable ti give other functions access
                self.master.quit()
#                break    #breaks the loop
 
root = Tk()
app = App(root)
root.mainloop()
print "returned_values", app.returned_values
woooee 814 Nearly a Posting Maven

"f" is a local variable and does not exist outside of the function unless you return it (which you don't). Also, line 218, print updateprimepage(), will print None because nothing is returned from the function.

woooee 814 Nearly a Posting Maven

Try it and see for yourself. If you have problems post the code you are using for assistance.

"When you create a new text widget, it has no contents. To insert text into the widget, use the insert method and insert text at the INSERT or END indexes:" http://effbot.org/tkinterbook/text.htm

woooee 814 Nearly a Posting Maven

That is impossible because we don't know what code makes it appear and we don't even know which one of the GUI toolkits you are using. Also include the version of Python you are using and the operating system.