woooee 814 Nearly a Posting Maven

The problem is here

while os.stat(filename).st_size < size:

Both input and output are buffered on computers. First create a list of what you want to write and check the size each time. Then use .join() to write the file. Writing each number to the file is inefficient and slower anyway, so keep the data in memory where you have more control.

Also, Python has universal newline support so you can just use "\n".

woooee 814 Nearly a Posting Maven

Append the count + word to the new list.

words = ["engine","ant","aeiou"]
count = 0
vow_count = []
for chars in words:
    for letter in chars.lower():
        if letter in 'aeiou':
            count += 1
    vow_count.append([count, chars])
    count = 0
vow_count.sort()
print vow_count
print [word for count, word in vow_count]
woooee 814 Nearly a Posting Maven

The easiest to understand is to use two loops, the first going up to the halfway point and the second going down. You have to first decide how to find the halfway point for an even or odd number for the size of the mountain (note the use of two different values below). You can also use one loop, incrementing a counter by adding to it going up and subtracting from it going down but you then have to allow for two numbers in the middle that could be equal.

My preference would be to use list slicing. The following is not meant to be ready to hand in code but a rough example.

too_many_nums = [1, 3, 5, 7, 9, 11]

for length in (3, 4, 5, 6, 10):
    middle, remain = divmod(length, 2)
    if remain:
        middle += 1
    list_of_odds = too_many_nums[:middle]
    ## length-middle because if an odd length, the back half 
    ## has one less value than the front, i.e. they are not equal
    junk_list = too_many_nums[:length-middle]
    junk_list.reverse()
    list_of_odds.extend(junk_list)
    print length, list_of_odds
woooee 814 Nearly a Posting Maven

You can do this with list comprehension. A hint

x=3
print range(x, 0, -1)
woooee 814 Nearly a Posting Maven

You have to explicitly call the init method in child classes. Also, I am guessing that the widgets are not showing because they are not explicitly placed in the root widget. Finally, there is no reason to assign the return of place() to a variable as it is always "None", and you do not call mainloop() anywhere.

from tkinter import * #Allows GUIs to be created
from random import randint #allows random integers to be generated

class StudentSkeleton:  #This class contains the basic layout for the student part of the application

    def __init__(self):
        ##-----------------------------------------
        ##"self." = visible throughout the class, including parent
        self.StudentGui = Tk()
        ##-----------------------------------------
        self.StudentGui.title('Thomas Hardye Sixth Form Application Program')
        self.StudentGui.geometry('800x640+200+200') #sets the size of the window
        self.StudentGui.resizable(width = FALSE, height = FALSE) #stops resizing of window
        #StudentSchoolLogo = PhotoImage(file='N:\Computing\A2 Computing\F454\part 3 Development\crest1-edited.gif')#brings in file of school Logo*
        #StudentSchoolImage = Label(self,image = StudentSchoolLogo).place(x=630,y=0)#places school image on screen    
        print "__init__ called"


class MainMenu(StudentSkeleton):#inheriting the student skeleton for the main menu GUI
    def __init__(self):
        ##-----------------------------------------
        ## call init method of child class
        StudentSkeleton.__init__(self)
        ##-----------------------------------------
        Label(self.StudentGui, text = 'Welcome to the Thomas Hardye Sixth Form Application Program',font=('TkDefaultFont',14)).place(x=80,y=30) #setting up welcome message to users
        Label(self.StudentGui, text = 'Are you a student or member of staff?',font = ('TkDefaultFont',14)).place(x=200,y=80)
        Button(self.StudentGui, text = 'Student',height = 3, width = 15, 
               font = ('TkDefaultFont',14)).place(x=100,y=300) #button to select student side of program
        Button(self.StudentGui, text = 'Staff', height = 3, width = 15, font = ('TkDefaultFont',14)).place(x=540,y=300) #button to select staff side of program
        Label(self.StudentGui, text = 'This lets …
woooee 814 Nearly a Posting Maven

You are printing separate variables. MemberCounter.members is different from m1.members="Two". Print the id() of each, which will show that they all occupy different memory locations. You might also want to study up on the difference between class objects/attributes and instance objects/attributes Click Here Sometimes you are printing an instance object and sometimes you are printing a class object, which are different variables even though they have the same name. m2 does not have an instance object named "members" so it prints the class object. If you created one
m2.members="Three"
it would print that instead, and
MemberCounter.members will always print the class object.

woooee 814 Nearly a Posting Maven

And is input from the command line, or are you using a GUI toolkit to get input and show the dice.

woooee 814 Nearly a Posting Maven

This homework question comes up every year so there are other posts that you can look at. We do not do your homework for you however. Also, posting on multiple forums reduces your chances for an answer because no one wants to waste time on a question that has possibly already been answered on another forum.

ganapathy24 commented: Its not a homework u sherlock... I jus forgot my rar password, but i know the words used in it, in order to generate all the possible combination i raised it.... +0
woooee 814 Nearly a Posting Maven

I don't understand what "stuck in a loop" means. The only loop(s) are the two for() loops and they exit when the data is exhausted.

## with open("SearchText.txt").readlines() as test_records:
test_records =["JOHN",
               "EGGS,24,BEEF,36,BACON,56,HAM,66",
               "ALICE",
               "TOMATOES,16,HAM,35,BEANS,35",
               "PAT",
               "APPLES,20,ORANGES,30,LETTUCE,50"]

response = 2
## response item location 1-->0, 2-->2, 3-->4 == response *2 -2
item_location = response*2-2
for ctr in range(0, len(test_records), 2):
    name = test_records[ctr]
    items = test_records[ctr+1].split(',')
    print items[item_location],
print 
woooee 814 Nearly a Posting Maven

Try using readlines instead, and check that searchWord actually contains something otherwise you can write blanks to the file.

 with open("SearchText.txt").readlines() as records:
     for num, line in enumerate(records):
 ......
         ## the following line will yield an error on the
         ## last record because there is no num+1
         response=records[num +1]
woooee 814 Nearly a Posting Maven

Traceback (most recent call last):
File "C:UserslinuxDesktopscreenshot1.py", line 11, in <module>
img.save(SAVE_PATH)

Print SAVE_PATH to see what name the program is trying to use (not the one you think it is). Also you can use
from os import environ
My computer likes environ['HOME'] instead of 'HOMEPATH' but it may be different on different OS's.

Gribouillis commented: good +14
woooee 814 Nearly a Posting Maven

You copied two separate answers to your thread from StackOverflowand combined them which yields the indentation mistakes and the orphaned else statement.

woooee 814 Nearly a Posting Maven

There is no reason to reinvent the wheel. You can use the identify program from ImageMagick to do that for you.

Gribouillis commented: indeed! +14
woooee 814 Nearly a Posting Maven

You can bind the <BackSpace> key to a function just like any other key. If you want to erase the last character in and entry widget for example, then get the value and set it as value[:-1] For button examples, like a quit button see a tutorial like this one

woooee 814 Nearly a Posting Maven

Running this stripped down version works on my machine

from tkinter import *
root = Tk()
calc = Frame(root)
calc.grid()

root.title("Calculator")
text_box = Entry(calc, justify=RIGHT)
text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)
text_box.insert(0, "0") 

root.mainloop()
woooee 814 Nearly a Posting Maven

Geometry managers, pack, grid, and place return None

canvas = Canvas(mainGUI, width=c_width, height=c_height, bg= 'white').place(x=(4.5*(widthOfScreen/12)),y= (2*(heightOfScreen/5)))
print canvas

Take a look at Vegas's code again and I'm sure you will find that the geometry manager is on a separate line.

canvas = Canvas(mainGUI, width=c_width, height=c_height, bg= 'white')
print canvas
print canvas.place(x=(4.5*(widthOfScreen/12)),y= (2*(heightOfScreen/5)))
CodingCabbage commented: Thankyou, very helpful +0
woooee 814 Nearly a Posting Maven

Generally you add each "button_name" instance to a list that remains after the loop exits. Note that you also want to increment/change the values for the place manager.

woooee 814 Nearly a Posting Maven

You have to pass the "numbers" list to do_analysis. Now it is using the "numbers" from the import numbers statement. This is not a complete solution but should get you started: passing parameters to a function

def main ():
    # create empty list
    intro()
    numbers = get_values()
    ## get_values()         Huh!!
    do_analysis(numbers)
    input("press enter to continue.") # required
woooee 814 Nearly a Posting Maven

Is this question solved or was clicking the solved button a mistake?

woooee 814 Nearly a Posting Maven

Note that you don't use the "j" variable. It is not necessary. Just iterate through the the list up to the next to last element. You do this over and over until there are no more swaps. In your code you loop enough times to do all of the swaps but this is not an efficient way to do it. Also using letters like i, l, and O is not a good idea as they look too much like numbers.

import random

test_list = [random.randint(1, 10) for ctr in range(20)]
print "original", test_list
found = True
swaps_ctr = 0
while found:
    swaps_ctr += 1
    found = False       ## initial state
    for ctr in range(0, len(test_list)-1):
        if test_list[ctr] > test_list[ctr+1]:
            test_list[ctr+1], test_list[ctr] = test_list[ctr], test_list[ctr+1]
            found = True     ## loop again

print swaps_ ctr, "swaps"
print test_list
for num in set(test_list): ## reduce to one entry per number
    print num, test_list.count(num)

## another way
print "-" * 20
previous_num = -1
for num in test_list: 
    if num != previous_num:
        print num, test_list.count(num)
        previous_num = num
woooee 814 Nearly a Posting Maven

You want to increment count after every input. You do not increment it after the first input statement. Also the final else is not necessary.

import random

count = 0
secret = random.randint (1, 100)

print ("Guessing game - Guess my secret number - number between 1-100")
guess = int(input("Your Guess? "))
count +=1     ## <----------------- or count=1
while (guess != secret):
    count += 1

    if (guess > secret):
        print ("Your guess is higher")
        guess = int(input("Guess again:"))

    elif (guess < secret):
        print ("Your guess is lower")
        guess = int(input("Guess again:"))

print ("You Guessed it!It took you", count, "tries.")
woooee 814 Nearly a Posting Maven

You may also have problems with capitalized vs all lower case words. Since I have no idea what "nltk.pos_tag(token_text)" is and don't have the time to search for it, the following code will count the number of words but will have a problem with punctuation you want to keep, like "don't", so this is not a complete solution but is the general idea.

from collections import defaultdict

dict_words = defaultdict(int)
text = "This ball is blue, this small and extraordinary. Like don't other ball."
this_word=[]
for word in text.split():
    for chr in word:
        if ("a" <= chr.lower() <= "z") or (chr in ["'", "`"]):
            this_word.append(chr.lower())
    if len(this_word):
        dict_words["".join(this_word)] += 1
        this_word = []
print dict_words
woooee 814 Nearly a Posting Maven

You have not done anything to find out what is going on so that is why you don't know. Two added print statements will show what pyTony said, i.e. you don't accumulate the count but just return each individual count from each recursion.

def lengthR(mystring):
    '''
    recursive function to count char in mystring
    excluding spaces
    '''
    count=0
    if mystring == '':
        return count

    mystring = mystring[0:-1]
    count += 1
    if mystring.endswith(' '):
        count -= 1
    print "testing", mystring, count
    x = lengthR(mystring)
    print " x =", x
    return x

mystring = "Hello Earth"
print(lengthR(mystring))
woooee 814 Nearly a Posting Maven

Use "if len(a_list)". Also this is what sets are for
if set(a_list).issubset(set(a_string)) ## if all list is in string

woooee 814 Nearly a Posting Maven

but it returns : _iNone

The "None" is returned by the function so apparently you are calling it with "print function_name()" instead of "function_name". If that does not help then post the entire code including how you call it.

woooee 814 Nearly a Posting Maven

Your code is a good example of why we use the Python Style Guide You use an upper and lower case "L" for the same field name so the code you posted does not run. The style guide says to use lower_case_with_underscores so to avoid that problem and make your code more readable by others. Try the following code and see if it does the random part. It does not matter if you have the keys in 2 lists or use [0][1] and [2][3] so it is up to you if you want to divide it into two lists or use as is. Note on the first print that the keys are in "dictionary order" not the order they were added.

import random
test_dict = {'One': 3, 'Two': 5, 'Three': 1, 'Four': 4, 'Five':7 }
dict_keys = test_dict.keys()
print dict_keys
random.shuffle(dict_keys)
print dict_keys
TrustyTony commented: clear thinking +12
woooee 814 Nearly a Posting Maven

There is a logic error in the code, if someone answers "no" as q_two they still get the q_three = raw_input("Do you pick the revolver up?") statement. Also, you want to limit the input to specific answers.

q_two = ""
while q_two.lower() not in ("no", "yes"):
    q_two = raw_input("Do you investigate ")

As to the Reference Error, you will have to include the complete error message to get any help.

woooee 814 Nearly a Posting Maven

It sounds like we are being given an assignment to "write a program" etc. for someone else. Not a good way to get assistance.

woooee 814 Nearly a Posting Maven

Convert to a list of lists with highest score first, then time, then name. Or take a look at "Complex Sorts" in the Howto Sorting

woooee 814 Nearly a Posting Maven

An example of placing a gif image on a canvas Click Here Most people who are attempting a hangman game use a canvas and [draw lines, circles] (http://effbot.org/tkinterbook/canvas.htm) etc. to get the hangman, but it is your program. You might also consider a Toplevel i.e. a second window for the hangman image

woooee 814 Nearly a Posting Maven

For the record, the way to achieve the results that I think the OP is looking for is to use

from sys import path

I prefer to import sys and use sys.path because it makes the namespaces obvious.

woooee 814 Nearly a Posting Maven

You first have to be able to access each individual row and know what format the row is in; string, list, etc. We do not know this so any code would be shooting in the dark.

woooee 814 Nearly a Posting Maven

The else statement in the following code executes if the number is equal to or greater than since you don't test for an equal condition and will print "try a lower number" when equal. You should test for greater than only as the while loop catches the equal condition. Your Tryz variable is off by one (try the program with 2 attempts). Consider using a function that returns True or False and the number of tries. Also the Python style guide says that lower_case_with_underscores are to be used for variable names and Upper or CamelCase is for class names.

    if Guess < Number:
        Guess = int(raw_input("Try a higher number: "))
    else:
        Guess = int(raw_input("Try a lower number: "))
woooee 814 Nearly a Posting Maven

There is a little hiccup for stars with 3 and 4 sides. You can divide 360 by the number of sides for stars with 5 sides and up, but for 3 or 4 sides this gives an angle greater than or equal to 90 which will not work. I will leave this conundrum up to the OP to solve for now. Both star_angle and left_angle have to be calculated differently for angles >= 90. Draw it out on a piece of paper and measure the angles and you should be fine.

def draw_star(number_of_sides):
    star_angle=360.0/number_of_sides  ## float for Python 2.X
    left_angle = star_angle*2
    print number_of_sides, star_angle
    turtle.penup()
    turtle.goto(-150, -100)
    turtle.pendown()
    for _ in range(number_of_sides):
        turtle.forward(100)
        turtle.right(star_angle)
        turtle.forward(100)
        turtle.left(left_angle)

    raw_input("Press a key")
    turtle.clear()

for num_sides in range(3, 8):
    draw_star(num_sides)
woooee 814 Nearly a Posting Maven

10 to the 5=100,000 and you only have to test up to the square root and every other number, i.e. not even, which is slightly more than 150 numbers if my arithmetic is correct. So it has to be some other problem. Check any while() loops and that you are not sending the same number(s) through the test over and over.

woooee 814 Nearly a Posting Maven

I would strongly suggest that you print "p" to see what it contains and then look at what you are sending to the function

for p in primes:
    if n % p == 0:
        return False
woooee 814 Nearly a Posting Maven

set a StringVar or IntVar in the command callback, "get" example here but set works the same way. Start at "This example creates an Entry widget, and a Button that prints the current contents:"

woooee 814 Nearly a Posting Maven

999 can't stop your program because of

elif grade > 101:

Try using (but it still errors if a non-number/letter is entered)

grade = -1
while grade != 999:
    grade = int(input('Enter a grade that is greater than zero: '))
    if 0 <= grade < 101: 
        ## do calcs for a correct entry
    else:
        print "incorrect entry"
woooee 814 Nearly a Posting Maven

and Moisture for the 31 day of the month,

and Moisture for the 31 day of the month

Split the rec to isolate the date and split the date into month, day, and year.

rec="1/01/2011, 00:00, 23, 50, 2,"
split_on_space = rec.split()
print split_on_space[0]
mm, dd, ccyy = split_on_space[0].split("/")
if 31 == int(dd):
    print "Found the 31st"
else:
    print "%s is Not the 31st" % (dd)
woooee 814 Nearly a Posting Maven

I get errors on lines 3, 11, and 14 so I can't get any output to test for a float.

woooee 814 Nearly a Posting Maven

You zero the totals before the loop instead of under it

for i in range(stop1)  :
    totalgp = 0
    totalgp1 = 0

    stop = int(input('Enter the number of classes you have: '))

and you can now delete

    stop -= 1

stop1 -= 1 

since the for() loop uses a different variable, i.e. a list of numbers.

woooee 814 Nearly a Posting Maven

A simple example

class Massage_DontCallMeMessage():
    def __init__(self):
        gui = Tk()
        gui.geometry('1500x100+10+600')                 
        gui.title('ALARTS')
        gui.config (bg = 'blue')                       
        self.massage = Label(gui, text = 'this is a demo')
        self.massage.config (fg = 'white',bg = 'blue', font=('times','60'))
        self.massage.place( x = 1,y = 0,)

        self.ctr = 0
        self.change_it()
        gui.mainloop()

    def change_it(self):
        orig_text='this is a demo          '
        display_text = orig_text[-self.ctr:] + orig_text[:-self.ctr]
        self.massage["text"]=display_text
        self.ctr += 1
        if self.ctr > len(orig_text):
            self.ctr = 0
        self.massage.after(200, self.change_it)

MM = Massage_DontCallMeMessage()
woooee 814 Nearly a Posting Maven

This works per your example. However you don't have a queue.put() so you won't get anything from the get() call. I don't think that is what you want however. Look up shared data perhaps a dictionary or list would be easiest to understand depending on the size of the data. Also please try to conform to the Python Style Guide (CamelCase is for classes, lower_case_with_underscore for functions) as it makes you code easier for others to understand.

import multiprocessing as mp
import time

DELAY_SIZE = 1

def Worker(q):
    sleep_for = DELAY_SIZE / 2.0
    for ctr in range(10):       
        print "I'm working... %s"  % (ctr)
        time.sleep(sleep_for)

def Process(): 
    print "          I'm processing.."

queue = mp.Queue(maxsize=DELAY_SIZE)
p = mp.Process(target=Worker, args=(queue,))
p.start()

while p.is_alive():
  time.sleep(DELAY_SIZE)
  Process()
woooee 814 Nearly a Posting Maven

A simpler way to add up the first two numbers.

def addFirstNums(num_in):
    multBy2 = num_in*2
    y = 0
    ## convert to string and cut to two digits if more than two
    ## doesn't matter if one or more digits
    newDig = str(multBy2)[:2]
    for num in newDig:
        y += int(num)
    print num_in, multBy2, y


for num in [2, 6, 102]:
    addFirstNums(num)
woooee 814 Nearly a Posting Maven

You can not have any character, including a space, after the line continuation character "\"

print('Based on a weight of', format(package_weight, '.2f'),\ 'pounds, the shipping charge is $', format(cost, '.2f'),sep=' ')
woooee 814 Nearly a Posting Maven

I am not an expert, and this is more code than I want to wade through, so am not positive about what you are trying to do. The first part, to get the difference between numbers that occur in more than one set, is below. The program breaks the test into two separate parts, first it finds all matches and adds to a dictionary, and since I am not sure if you want everything greater than "n" or equal to, it does both.

from collections import defaultdict

def occur(lists_in):
    ## key = search number pointing to a list of numbers of 
    ## the "sets" that contain the search number
    return_dictionary = defaultdict(list)

    ## loop though each list in order using a counter to reference the list
    for outer in range(0, len(lists_in)):
        for outer_num in lists_in[outer]:
            ##loop through other lists starting with outer+1
            for inner in range(outer+1, len(lists_in)):
                if outer_num in lists_in[inner]:
                    return_dictionary[outer_num].append([outer, inner])

    return return_dictionary

list_of_lists=[['34','45','67','56'],
               ['12','71','78','20'],
               ['76','73','36','32'],
               ['34','57','67','88'],
               ['78','45','82','28'],
               ['52','10','67','41'],
               ['58','78','77','80'],
               ['57','45','68','20'],
               ['67','36','29','53'],
               ['78','79','69','21'],
               ['64','90','35','33'],
               ['45','90','52','72']]

return_dictionary = occur(list_of_lists)
n=2
for key in return_dictionary:
    for each_list in return_dictionary[key]:
        lit = ""
        dif = each_list[1] - each_list[0] ## found-original "set"
        if n+1 == dif:
            lit="skips exactly the required number"
        elif n < dif:
            lit="          skips the required number"
        print "%s occurs in %d and %d %s" % \
              (key, each_list[0], each_list[1], lit)
woooee 814 Nearly a Posting Maven

You can send a tuple to startswith

 ## note that opt is never set back to "" or "n"
 if s.startwith(('Total number of defects', 'Total charge on defect', etc.))

Are you saying that you want to stop looking after the second if s=='**** Optimisation achieved ****':

if s=='**** Optimisation achieved ****':
    if opt=='y':
        opt='n'
    else:
        opt="y"            
Gribouillis commented: I forgot about the tuple ! +14
woooee 814 Nearly a Posting Maven

That is more code than I want to trudge through for a simple question, so will just say that generally you use Toplevels as the code below illustrates. If there is more that you wish to know, post back. Note that you can use a function or third class to call (separate instance) each class as many times as you want, with individual parameters.

class one():
    def __init__(self, root):
        self.root = root
        top = tk.Toplevel(root)
        top.title("First")
        top.geometry("150x75+10+10")

        tk.Button(top, text="open new window", command=self.openit).grid()
        tk.Button(top, text="Quit", command=self.root.quit).grid(row=1)

    def openit(self):
        two = Two(self.root)

class Two():
    def __init__(self, root):
        self.root = root
        top = tk.Toplevel(root)
        top.title("Second")
        top.geometry("150x50+10+125")

        tk.Label(top, text="second window").grid()

root = tk.Tk()
root.withdraw()
one(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

Whoops, indentdataion and spelling is off in the previous post (ran past 30 minutes-those interruptions!!)

Ohhhh....I would never have noticed that, thank you! (So embarrassing...)

We've all been there.

woooee 814 Nearly a Posting Maven
        Try:
            float(outputt) == float(abs(int(outputt)))
        except ValueError:
            print("Not a valid number. Please enter a valid number.")
        else:
            return float(outputt)

"try" is not capitalized

This statement does not make sense,
float(outputt) == float(abs(int(outputt)))
and there is no reason to convert to an int and then convert to a float since converting to an int removes the decimal portion of the float, and finally the return should be under the try.

def inputt(input_string):
    while True:
        outputt = raw_input(input_string):
        try:
            return float(outputt)      
            ## or better
            float_val = flaot(input_string)
            if float_val > 0:  ## won't divide by zero
                return float_val
            else:
                print("Not a valid number.")
            except ValueError:
            print("Not a valid number. Please enter a valid number.")