Gribouillis 1,391 Programming Explorer Team Colleague

You need to post some code. The most obvious solution is to write a function reset_my_class_variables() and to call it when it is needed.

Gribouillis 1,391 Programming Explorer Team Colleague

This error happens in the assignment statement when you try to assign the wrong number of values to the wrong number of names, for example

>>> a, b, c = (1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

In your case, getInputs(), returns only 2 values, but the first line in main() tries to assign these 2 values to 3 names.

Gribouillis 1,391 Programming Explorer Team Colleague

You can use the following

neededwordlist= ['a','p','p','l','e']
rawlist = ['a','l','p','p','e']

need, raw = list(neededwordlist), list(rawlist) # make copies
for i in range(min(len(need), len(raw))):
    if need[i] == raw[i]:
        need[i] = raw[i] = '!'
wrongposition = set(need) & set(raw)
wrongposition.discard('!')
print wrongposition

""" --> my output
set(['p', 'l'])
"""

The idea is that the letters in wrong positions are the letters which still belong to both lists after all the correct matches have been removed.

vaucro commented: simple and clear explanation thanks! +0
Gribouillis 1,391 Programming Explorer Team Colleague

Another way

>>> from operator import itemgetter
>>> from itertools import groupby
>>> dic = {'1': ['a', 'c'],'2': ['a', 'b', 'c'], '3': ['b']}
>>> dict((x, list(t[1] for t in group)) for (x, group) in groupby(sorted(((j, k) for k, v in dic.items() for j in v), key=itemgetter(0)), key=itemgetter(0)))
{'a': ['1', '2'], 'c': ['1', '2'], 'b': ['2', '3']}
Max_16 commented: This is superfast and exactly what I needed!! Thank you! +0
Gribouillis 1,391 Programming Explorer Team Colleague

You can also capture the data interactively with your function add_mark(), then save the dictionary to a file and read the dictionary from this file the next time you run your program

from cPickle import dump, load
marks = {"alice" : "A+", "smith" : "A", "daemon" : "B+", "lily" : "B" }

# save dict to file
with open("marks.pkl", "wb") as fout:
    dump(marks, fout)
# read dict from saved file
with open("marks.pkl", "rb") as fin:
    foo = load(fin)
print foo # prints {'smith': 'A', 'daemon': 'B+', 'lily': 'B', 'alice': 'A+'}
Gribouillis 1,391 Programming Explorer Team Colleague

Yes, it's the same problem with tuples

t = (1, 2, ["hello", "world"])
print(t)
t[-1][-1] = "daniweb"
print(t)
""" my output -->
(1, 2, ['hello', 'world'])
(1, 2, ['hello', 'daniweb'])
"""

Immutability never meant true immutability in python. If ConstSequences are immutable like tuples are, it's ok for me.
I approve adding a __str__ method. You could have included the missing 'import types' out of the __getitem__ method.

Gribouillis 1,391 Programming Explorer Team Colleague

This snippet defines a function walk() which generically performs a depth-first traversal of a tree, using preorder, inorder or postorder rules. Here, genericity means here that there are no hypotheses on what the tree nodes are or the implementation of the tree. Walk() only needs an arbitrary object used as a root node and a function generating children 'nodes' for a given 'node'. At any moment during the walk, it exposes the path from the root node to the visited node. Finally, the implementation is fully non recursive, allowing very deep trees to be traversed.

IMPORTANT: this snippet needs class ConstSequence from the snippet
http://www.daniweb.com/software-development/python/code/395101

TrustyTony commented: Neat +13
Gribouillis 1,391 Programming Explorer Team Colleague

This snippet is easy: it defines an immutable wrapper around a sequence type (list, deque, etc) which allows a class, function or module to expose a read only version of a sequence to the outer world. A constant wrapper around mapping types could also be defined in a similar manner.

Gribouillis 1,391 Programming Explorer Team Colleague

I would first parse the lines with adapted datatypes like this

from collections import namedtuple
from itertools import islice
import re
import sys

file1 = iter("""#file  R       plp   trace  class   info
20\tQRT43\t1413\t29\tFIL\tNS=3,DP=14,Bgc=0.5,DB,H2,GT:GQ:DP:HQ 0|0:48:1:51,51 1|0:48:8:51,51 1/1:43:5
30\tQZEE43\t1413\t29\tFIL\tNS=3,DP=14,Bgc=0.2,DB,H2,GT:GQ:DP:HQ 0|0:48:1:51,51 1|0:48:8:51,51 1/1:43:5
15\tZZT43\t1413\t29\tFIL\tNS=3,DP=14,Bgd=0.7,DB,H2,GT:GQ:DP:HQ 0|0:48:1:51,51 1|0:48:8:51,51 1/1:43:5
""".strip().splitlines()) # replace this with your opened file 1

file2 = iter("""foo\tbar\tR\tbaz
13\tABG1324\tQRT43\t23455
13\tABG1324\tQRR43\t23887
13\tABG1324\tORT47\t20993
13\tABG1324\tQR453\t23455
13\tABG1324\tQROR3\t27466
""".strip().splitlines()) # replace this with your opened file 2

# Define a custom datatype to read file1

class LineA(namedtuple("LineA", "file R plp trace klass info")):    
    @property
    def bgc(self):
        return self._find_float("Bgc")
    
    @property
    def bgd(self):
        return self._find_float("Bgd")
    
    def _find_float(self, name):
        match = re.search(r"%s=([^,]*)" % name, self.info)
        if match:
            try:
                return float(match.group(1))
            except ValueError:
                return 0.0
        else:
            return 0.0

F1 = []
for line in islice(file1, 1, None):
    line = LineA(*line.split("\t", 5))
    F1.append(line)

# F1 is now a list of LineA objects, which have
# attributes .file, .R, .plp, .klass, .info, .bgc, .bgd
# the 2 last attributes are floats, with value 0.0 if nothing was found

for line in F1:
    print line
    
for line in F1:
    print line.bgc, line.bgd
    
    
LineB = namedtuple("LineB", "foo bar R baz")

F2 = []
for line in islice(file2, 1, None):
    F2.append(LineB(*line.split("\t", 3)))

# F2 is now a list of LineB objects, which have
# attributes .foo, .bar, .R, .baz

for line in F2:
    print line

# Now try to extract the information you want from these two lists F1 and F2

"""My output -->
LineA(file='20', R='QRT43', plp='1413', trace='29', klass='FIL', info='NS=3,DP=14,Bgc=0.5,DB,H2,GT:GQ:DP:HQ 0|0:48:1:51,51 1|0:48:8:51,51 1/1:43:5')
LineA(file='30', R='QZEE43', plp='1413', …
TrustyTony commented: inherit from namedtuple as factory, interesting +13
Gribouillis 1,391 Programming Explorer Team Colleague

It's a piece of cake for itertools

from itertools import islice, product, chain
import string

print ''.join(tuple(islice(chain.from_iterable(product(string.ascii_uppercase, string.ascii_lowercase, string.digits)), 79)))

""" my output -->
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5A
"""

Notice that the maximum length is 20280 and this code will not complain if you replace 79 with 25000 but it will return a string of length 20280. An alternative is to store the 20 KB string somewhere and slice it directly: pattern20KB[:79]

debasishgang7 commented: Thanks Man.. +3
Gribouillis 1,391 Programming Explorer Team Colleague

The part 'if guess == secret ...' must run only after the while loop is finished

import random
secret = random.randint(1,99)
guess = 0
tries = 0

print "AHOUY! I'm the Dread Pirate Roberts, and I have a secret!"
print "It is a number from 1 to 99. I'll give you 6 tries. "

while guess != secret and tries < 6:
    guess = input("What's yer guess? ")
    if guess < secret:
        print "Too low, ye scurvy dog!"
    elif guess > secret:
        print "Too high, landlubber!"
    tries = tries + 1
if guess == secret:
    print "Avast! Ye got it! Found my secret, ye did!"
else:
    print "No more guesses! Better luck next time, matey!"
    print "The secret number was", secret

indentation matters in python.

Gribouillis 1,391 Programming Explorer Team Colleague

@Rick345, your program works but the print is misleading

print ('This program calculates how many times 2 can be factored into the number entered')

It's a different number which could be obtained with

count = 0
while True:
    num, remainder = divmod(num, 2)
    if remainder:
        break
    else:
        count += 1
Gribouillis 1,391 Programming Explorer Team Colleague

The mathematical result is the logarithm of base 2 of n. It seems to work also for python:

>>> from math import log
>>> n = 444444444444444448888888888888888888888888883333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333336666666666666666666666666666666666666666666666666666666666666666666666666666666666666666677777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777774
>>> k = int(log(n, 2))
>>> n >> k
1L
>>> k
1374

One could expect that this technique fails if n is too large because math.log() normally manipulates float values, but even if it fails, the returned value could be used as a good first approximation which could be refined. Also, even "by hand", an algorithm in O(log(log(n)) is possible.

Gribouillis 1,391 Programming Explorer Team Colleague

A rather straightforward one-liner to do the same thing:

>>> bin(10)[2:].rjust(8, '0')
'00001010'

It's true, only in 2005 we were with python 2.4 which had no bin() function. Also it's useful for beginners to see how one can implement bin() in pure python. It is a classical exercise in programming to display numbers in a different basis.

Gribouillis 1,391 Programming Explorer Team Colleague

I found a faster way than zip (a numpyish way)

data = tuple(ny.loadtxt(filename) for filename in ("data1.txt", "data2.txt"))
    result = ny.column_stack(data)
    print result
    print result.shape

""" my output -->
[[  45.56564    45.56564 ]
 [ 564.8484    564.8484  ]
 [ 114.25477   114.25477 ]
 ..., 
 [ 114.25477   114.25477 ]
 [   1.325588    1.325588]
 [   2.36547     2.36547 ]]
(1000, 2)
"""

the ny.column_stack(data) is 166 times faster than array(zip(*data)), with 0.015 milliseconds.

Gribouillis 1,391 Programming Explorer Team Colleague

Learn about generators and yield statement.

I don't quite agree with Tony on this. The problem here seems to be that the function filest() takes time to complete, and wether you are using yield statements or not does not change this. When a function is busy with a long task in a gui context, a standard solution is to run the time-consuming code in a different thread: the GUI's main loop can then resume its normal work. An old, perhaps not optimal, but simple solution to implement this is given in this recipe http://code.activestate.com/recipes/82965/. You could try to write similar code and execute filest() in the worker thread, sending the generated data in a queue.

Gribouillis 1,391 Programming Explorer Team Colleague

Oh man I can't believe it!!!! It's working!!!! I sweat blood over it!
One last thing if you can: why I'm getting this output in the file:


rather than, you know just a column without list and string symbols like:
54.22953
54.17732
54.13724

and so on...

Instead of write("%s" % block), use writelines(block), it should print a column.

>>> import sys
>>> sys.stdout.writelines([' 54.22953\n', ' 54.17732\n', ' 54.13724\n', ' 54.10664\n', ' 54.08554\n'])
 54.22953
 54.17732
 54.13724
 54.10664
 54.08554
>>>
Gribouillis 1,391 Programming Explorer Team Colleague

As I said, your algorithm is wrong. There is no reason to call blocks_generator() for each output file. It only needs to be called once. Try this first

def tgrid_files ():
    """Creates the t.grid files"""
    times = open ('test', 'r') # what is this ?
    header = header_tgrid_files()
    file_names = open ('receiver_names', 'r')
    blocks = blocks_generator('test')
    for (element, block) in zip(file_names, blocks):
        names = element.split()[0] # the plural is misleading. I guess it's only one name
        print names, block

It should print each output file name with the block that goes in this file. If this works, you only need to open the file and write the header and the block (use output_files.writelines(block))

Gribouillis 1,391 Programming Explorer Team Colleague

File objects have no append() method. To add lines to a file, you must open it in append mode (mode 'a') and use the write() method. If you want to create a new file, it's the same code with mode 'w'.

f = open('filename', 'r')
new = open('other_filename', 'a')
for data in f: # f is iterable: no need for readlines()
    if '#' not in data:
        new.write('notExist\n')
    elif ('SRM' in data) or ('%' in data): # elif because a line may contain % and not #
        new.write(data) # data already contains \n
f.close()
new.close()
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a pure "itertool style" solution

from itertools import islice, repeat, takewhile

def blocks(fileobj, size=4):
    blank = " " * 10
    lines = (line for line in fileobj if not line.startswith(blank))
    return takewhile(len, (list(islice(lines, 0, size)) for x in repeat(None)))

with open("blocks.txt") as ifh:
    for b in blocks(ifh):
        print b

""" my output -->
['56.71739\n', '56.67950\n', '56.65762\n', '56.63320\n']
['56.61648\n', '56.60323\n', '56.63215\n', '56.74365\n']
['56.98378\n', '57.34681\n', '57.78903\n', '58.27959\n']
"""

Notice that the file is not loaded in memory.

Gribouillis 1,391 Programming Explorer Team Colleague

I see the problem but I can't figure out how to fix it, I been at it forever

Well, here is my solution. It's not perfect: the next step is to print the numbers in fixed width fields using format(), but I won't help you on this. See http://www.daniweb.com/software-development/python/code/232375

def iround(x):
    return int(x + (0.5 if x > 0 else -0.5))

def windchill(V,T):
    wc = 35.74 + .6215*T-35.75*(V**.16)+.4275*(V**.16)
    return wc # <------------- return a float here because it's a physical quantity

def main():
    print("                         Temperature \n")
    print("Speed \n")
    print("---- -20 70 10 0 10 20 30 40 50 60 ")

    for V in range(0,55,5):
        print(V, end="")
        for T in range(-20,70,10):
            wc = windchill(V,T)
            print(iround(wc), end=" ") # <-------------- V removed !
        print()

main()
Gribouillis 1,391 Programming Explorer Team Colleague

Ah ah! recurrent question. I once started a thread with same issue. The best solution I know is

def iround(x):
    return int(x + (0.5 if x > 0 else -0.5))
Gribouillis 1,391 Programming Explorer Team Colleague

As you wrote your class, i is a static variable (a class member and not an instance member). You can update it with App.i += 1

vegaseat commented: nice and helpful +15
Gribouillis 1,391 Programming Explorer Team Colleague

Here is another solution, using the ast module and the builtin function compile(). I think it is very robust because it only accepts expressions consisting of a single python number or the sum or difference of 2 numbers (to allow complex expressions like "1+2j". It will reject for example "(1,)" or "[1]".

# python 2 and 3
import ast

def signature(astnode):
    return (type(astnode),) + tuple(
                signature(n) for n in ast.iter_child_nodes(astnode))

valid_signatures = set([
    (ast.Expression, (ast.Num,)),
    (ast.Expression, (ast.BinOp, (ast.Num,), (ast.Add,), (ast.Num,))),
    (ast.Expression, (ast.BinOp, (ast.Num,), (ast.Sub,), (ast.Num,))),
])

def is_number_string(s):
    expression = compile(s, "<string>", "eval", ast.PyCF_ONLY_AST)
    return signature(expression) in valid_signatures

def eval_number_ast(n):
    try:
        1 + n
        return n
    except TypeError:
        if is_number_string(n):
            return eval(n)
        else:
            raise ValueError(n)
        
def main():
    f = eval_number_ast
    assert f(32) == 32
    assert f(3.0) == 3.0
    assert f(1+3j) == 3.0j + 1.0
    assert f("32") == 32
    assert f("3e2") == 300.0
    assert f("12j-3") == -3.0 + 12.0j
    
if __name__ == "__main__":
    main()
TrustyTony commented: Interesting. +13
Gribouillis 1,391 Programming Explorer Team Colleague

Any sequence of python strings can be disguised to look like a file opened for reading, which can then be passed on the fly to functions expecting such an input file. This code snippet defines the necessary adapter class. The obtained file-like objects store only one string of the sequence at a time (which limits some file operations, seek() doesn't work backwards for example). This code was inspired by the standard library's StringIO module. Please note that when memory or disk access is not an issue, it may be more efficient to write a temporary file than to use this adapter class (for example in linux one could write a file in /dev/shm).

Gribouillis 1,391 Programming Explorer Team Colleague

You could define 3 functions which take 2 arguments, a file opened for reading and a file opened for writing. Then you could use StringIO objects instead of temporary files on the disk. StringIO are memory files. They can be used like opened files (for reading or writing or appending). Here is an example with 3 file transform functions and a main function which calls the 3 transform functions one after the other to chain their action, using StringIOs as intermediary files

try:
    from cStringIO import StringIO # python 2
except ImportError:
    from io import StringIO # python 3

def funcA(infile, outfile):
    for line in infile:
        outfile.write(line.upper())

def funcB(infile, outfile):
    for line in infile:
        outfile.write(line[:-1][::-1]+"\n")
        
def funcC(infile, outfile):
    for line in infile:
        outfile.write(line.replace('E', 'e'))

def main():
    with open("inputfile.txt", "r") as fh1:
        fh2 = StringIO()
        funcA(fh1, fh2)
    fh3 = StringIO()
    fh2.seek(0) # go to the beginning of file 2 because we're now going to read it.
    funcB(fh2, fh3)
    fh3.seek(0)
    with open("outputfile.txt", "w") as fh4:
        funcC(fh3, fh4)
        
if __name__ == "__main__":
    main()

Another good solution would be to use generator functions, but since you're new to python, you must learn ordinary functions before generators.

Notice that you can see the content of a StringIO by calling fh2.getvalue() for example, which returns a string that you could print or write in a file.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you could start by reading Doug Hellmann's python module of the week on the threading and multiprocessing modules: http://www.doughellmann.com/PyMOTW/threading/index.html and http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html .

Gribouillis 1,391 Programming Explorer Team Colleague
print(' '.join(''.join(z[0] for z in y) for y in x))
Gribouillis 1,391 Programming Explorer Team Colleague

You can use a second argument to split

>>> "1900 120 Date Night".split(" ", 2)
['1900', '120', 'Date Night']

Otherwise, use a regular expression (the re module).

Gribouillis 1,391 Programming Explorer Team Colleague

The normal solution is to use a 'with' statement

from contextlib import contextmanager

@contextmanager
def threadmgr_running(*args, **kwd):
    threadmgr = ThreadManager(*args, **kwd)
    threadmgr.start() # or whatever
    try:
        yield threadmgr
    finally:
        threadmgr.waiting = False

# in code

with threadmgr_running(...) as threadmgr:
    etc # the threadmgr terminates automatically after this block
JoshuaBurleson commented: for the props you deserve but didn't get +3
Gribouillis 1,391 Programming Explorer Team Colleague

The trouble is, it shouldn't become None at all..

Here is the whole code:

from tkinter import *

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
        
    def create_widgets(self):
        self.inst_lbl = Label(self, text = "Enter the password for the secret of longevity").grid(row = 0, column = 0, columnspan = 2, sticky = W)
        self.pw_lbl = Label(self, text = "Password: ").grid(row = 1, column = 0, sticky = W)
        self.pw_ent = Entry(self).grid(row = 1, column = 1, sticky = W)
        self.submit_bttn = Button(self, text = "Submit", command = self.reveal).grid(row = 2, column = 0, sticky = W)
        self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD).grid(row = 3, column = 0, columnspan = 2, sticky = W)
        
        
    def reveal(self):
        contents = self.pw_ent.get()
        if contents == "secret":
            message = "Here's the secret to living to 100: live to 99 and then be VERY careful."
        else:
            message = "That wasn't the right password, I can let you know the secret."
        
        self.secret_txt.delete(0.0, END)
        self.secret_txt.insert(0.0, message)
        

root = Tk()
root.title("Secret of Longevity")
root.geometry("300x150")
app = Application(root)
root.mainloop()

As mentioned, I just changed 'WORD' to 'CHAR', and that's when the error began, and it didn't help to change it back.

As I said before, grid() returns None and for each of your subwidgets, you must use 2 lines, one to create the widget and the second line to call grid(). See my first post and compare carefully to your code.

Gribouillis 1,391 Programming Explorer Team Colleague

I just finished a program, it worked perfectly, then I changed a bit of it, and now it won't work at all, even if I change it back.

self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD).grid(row = 3, column = 0, columnspan = 2, sticky = W)

That it the code which is faulty.
I tried to change wrap = WORD to wrap = CHAR (just to see the change), and got this error: AttributeError: 'NoneType' object has no attribute 'delete'
'delete' comes from here:

self.secret_txt.delete(0.0, END)

Now I always get the error, even when using wrap = WORD, and also in new programs.

Help please!

What is the return value of the grid() method ? Try to write on two lines

self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD)
self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W)
Gribouillis 1,391 Programming Explorer Team Colleague

The easiest solution is to have both Class A and Button_Manager inherit a common superclass which holds their common methods

class Common(object):
    def data_mod1(self):
        ...

class A(Common):
    ...

class Button_Manager(Common):
    ...
Gribouillis 1,391 Programming Explorer Team Colleague
JoshuaBurleson commented: Thanks Dr.G +3
Gribouillis 1,391 Programming Explorer Team Colleague

it's a GUI 'tkinter' application

Then pop up a Listbox widget with the same list.

JoshuaBurleson commented: thanks. +3
Gribouillis 1,391 Programming Explorer Team Colleague

Gribouillis, your function worked nicely, but it didn't stop the user from entering an incorrect value, it just stopped them from leaving it blank.

I agree, but we're only supposed to help you write your code, not to do all the work for you :)

Gribouillis 1,391 Programming Explorer Team Colleague

Do you think you could maybe explain why the two functions shouldn't be in the Player class?

It's a matter of class design. Normally, functions in a class Player execute player's action or report about player's state, or they may execute code relative to all players (in this case they are class methods or static methods). Technically, one says that each class has a certain number of "responsibilities". General utility functions like ask_yes_or_no() are unrelated to this class.

If you absolutely want to have this functions in the class, write

@staticmethod
    def ask_yes_or_no(): # no self parameter
      ...

and then use game.Player.ask_yes_or_no()

Gribouillis 1,391 Programming Explorer Team Colleague

I'm still an ameture at programming, so could you please be a bit more specific about the solution. I don't quite know what you mean by 'Unindent'. Thanks for helping me! :)

I mean remove the definitions from the Player class and write them at the beginning of the line.

abders commented: Clear and precise aid. +1
Gribouillis 1,391 Programming Explorer Team Colleague

okay, I understand, I've just yet to use the yield function. Is it essentially the same as return? Also, how would it be possible to be done otherwise?

You can do it otherwise with

while True:
    attempt = raw_input("...")
    etc

but I like to use generators.

Generators are very nice and powerful. There are a few great articles by David Beazley on generators, see here for a starting point http://www.dabeaz.com/generators/

Gribouillis 1,391 Programming Explorer Team Colleague

thank you very much it worked.

just one more thing. now that this works i tried a simple programm

import risar
from turtle import Turtle

t = Turtle()

def square(turtle, l):
    for i in range(4):
        turtle.forward(l)
        turtle.left(90)


for i in range(5):
    square(t, 150)
    t.turn(72)

and now it says that
Turtle object has no attribute 'Turn'

Again, beware that python has a builtin module 'turtle'; import turtle and print turtle.__file__ to see which one you are importing.

Gribouillis 1,391 Programming Explorer Team Colleague

Another module may be hiding your module risar. Add print risar.__file__ after the 'import risar' in module turtle to see if it's importing from the expected file.

Gribouillis 1,391 Programming Explorer Team Colleague

Wow, all I had to do was return the function on the exceptions instead of calling it. I don't know why, but that just didn't click. Thank you so much for your reply, it works perfectly now!

A high percentage of errors involving None come from forgotten return :)

JoshuaBurleson commented: sweet and simple +3
Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that you call kcinput() instead of return kcinput(). Use a loop for such problems instead of recursion

from __future__ import print_function
import sys
if sys.version_info < (3,):
    input = raw_input
# these lines were for python before 3.0

def kcinput():
    for i in range(2):
        try:
            return float(input("\nWhat is the degrees in Celsius? "))
        except Exception:
            if i:
                raise
            else:
                print("You must enter a number!")

if __name__ == "__main__":
    print(kcinput())
Gribouillis 1,391 Programming Explorer Team Colleague

does it say how in the documentation? I tried that with an Entry(self) and when I tried stating if the variable I had assigned to it == F1 "how ever I hit the F1 button" nothing happened, it just wouldn't accept the input from the key "while writing the program, not user end."

Here is an exemple, adapted from an old forum post, to show you how to bind the F1 key

from functools import partial
from Tkinter import *

def fonction(text, event):
    text.insert(END,'ok ')

def bind(wid):
    wid.bind('<F1>',partial(fonction, wid))

def unbind(wid):
    wid.unbind('<F1>')

root = Tk()
text = Text(root)
text.pack()
b1 = Button(root,text="Bind",command=partial(bind, text))
b2 = Button(root,text="Unbind",command=partial(unbind, text))
b1.pack()
b2.pack()
b1.invoke()
text.focus_set()
root.mainloop()

Also read this http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm

Gribouillis 1,391 Programming Explorer Team Colleague

Consider the following class hierarchy

import inspect

class A(object):
    def func(self):
        return "A.func"

class B(A):
    def func(self):
        return "B.func"
    
class C(A):
    def func(self):
        return "C.func"
    
class D(B, C):
    def func(self):
        return "D.func"
    
class E(D):
    def func(self):
        return "E.func"
    
if __name__ == "__main__":
    def printmro(k):
        print "mro({0}): {1}".format(k.__name__,
                ", ".join(klass.__name__ for klass in inspect.getmro(k)))
    for k in (A,B,C,D,E):
        printmro(k)
    x = E()
    print "type(x):", type(x).__name__
    print "x.func():", x.func()
    print "super(D, x).func():", super(D, x).func()

""" my output-->
mro(A): A, object
mro(B): B, A, object
mro(C): C, A, object
mro(D): D, B, C, A, object
mro(E): E, D, B, C, A, object
type(x): E
x.func(): E.func
super(D, x).func(): B.func
"""

The mro of a type is the 'method resolution order'. It means that when looking for the method x.func, since x is a E instance, the interpreter looks for a method func() in each of the classes E, D, B, C, A, object in this order, because this is class E's mro.

Now, since x is also an instance of D, we can write super(D, x).func(). Then the method will be searched in D's mro without the class D itself. Since D's mro is D, B, C, A, object, python looks in the list of classes B, C, A, object, and it finds B.func().

In python 2, super is not very useful because one must explicitely use a reference to the class (Application in your example). In python 3, you can use super() in a method without the class name …

Gribouillis 1,391 Programming Explorer Team Colleague

A part of the question is what do you want to do when a user is busy using the telnet connection. Should other users receive an error message, or should they wait ? If your server runs in a posix environment, your cgi script could perhaps acquire a system's semaphore before its telnet session and release the semaphore after the session. You could use this module for this http://semanchuk.com/philip/posix_ipc/#semaphore . Other instances of the script could try to acquire the semaphore with a timeout and send an error page when the timeout expires.

Gribouillis 1,391 Programming Explorer Team Colleague

In a traditional implementation of linked lists, one distinguishes lists and list elements, so you will have 2 classes like this

class Element(object):
    __slots__ = ("numb", "next")

    def __init__(self, numb):
        self.numb = numb
        self.next = None

class List(object):
    __slots__ = ("first", "last")
    
    def __init__(self):
        self.first = self.last = None

    def add(self, numb):
        if self.first is None:
            self.first = self.last = Element(numb)
        else:
            self.last.next = Element(numb)
            self.last = self.last.next
            
    def show(self):
        elt = self.first
        print "showing list"
        while elt is not None:
            print elt.numb
            elt = elt.next

list1 = List()
list1.show()
list1.add(43)
list1.add(22)
list1.add(938)
list1.show()

""" my output -->
showing list
showing list
43
22
938
"""

Also note that this implementation is naive and inefficient in python. Python already contains a class of doubly linked lists, namely collections.deque which will most certainly be faster than your own implementation in pure python.

Gribouillis 1,391 Programming Explorer Team Colleague

How to create a png image containing a fragment of source code ? Well, don't do it yourself, the pygments module contains all the necessary tools. The example below shows how to produce a png image from python code, but pygments supports lexers for many other languages and its formatter classes can produce other image formats too. The ImageFormatter class allows to set various parameters of the resulting images. See the options here http://pygments.org/docs/formatters/#formatter-classes .

Gribouillis 1,391 Programming Explorer Team Colleague

That is all well and good but how do I interpret this into a GUI where I have say 4 options and I want them to select one therefore changing the the result produced. I tested out that piece of code there and it only seems to work with 1 variable unless I'm mistaken.

Cheers.

You can use functools.partial() like this

from functools import partial
from Tkinter import *
glob = type('Globvars', (object,), {})()
glob.d = 0
master = Tk()

def on_press(value):
    glob.d = value
    print glob.d

buttons = list()
for value in (10, 20, 30):
    b = Button(master, text = str(value), command = partial(on_press, value))
    b.pack(side=LEFT)
    buttons.append(b)

mainloop()
user45949219 commented: Helpful. +0
Gribouillis 1,391 Programming Explorer Team Colleague

The common idiom is

thelist[:] = (x for x in thelist if not criteria(x))

# for example

thelist[:] = (x for x in thelist if not 'a' in x)
JoshuaBurleson commented: Thank you so much! +1