woooee 814 Nearly a Posting Maven

Some comments

initialize a dictionary: dictionary 1
dd = {}

"""  indentation is wrong
"""
    dd.setdefault(column3, 0)
    # increment dd[port number] by one
    dd[column3] += 1

"""  get_port_name() does not return anything so the
     dictionary, ports_name, is empty
     Take a look at "1.1. A first program" 
     cut and paste this link
     http://www.pasteur.fr/formation/infobio/python/ch01.html#d0e115
"""
ports_name={} # dictionary 2
get_port_name ('Ports', ports_name)
 
# if the key in dd equals the key (item) in ports_name, insert the value of that item to the third column in the output file:
for key in dd.keys():
    if key in ports_name:
        print ports_name[key]     ## description

##    for item in ports_name.keys():
##        if key == item:
	    #I want the description to be retrievable by the key in dd and then have the description of the numbers on the third column of the output file and that 
##            dd[key][1]= ports_name[item]            
 
f.close()
outfile.write("\n".join(["%s %s %s" % (key, dd[key][0], dd[key][1]) for key in dd]))
outfile.close()
woooee 814 Nearly a Posting Maven

Griswolf's code assumes that you are looking for empty items in the list. If instead, you want to remove spaces within an item, i.e remove the space in "word1 word2", post back.

# help 2 I want to shorten below codes how to
##
## same as Griswolf's code: use a loop to replace code below 
test_list = [text1, text2, text3, text4, text5, text6, \
             text7, text8, text9, text10, text11, text12 ]
mylist = []
for item in test_list:
    if len(item):
        mylist.append(item)
#
#-------------------------------------------------------------------------
#  instead of
if len(text1)<> 0:
	mylist.append(text1)
if len(text2) <> 0:
	mylist.append(text2)
if len(text3) <> 0:
	mylist.append(text3)
if len(text4) <> 0:
	mylist.append(text4)
if len(text5) <> 0:
    mylist.append(text5)
if len(text6) <> 0:
    mylist.append(text6)
if len(text7) <> 0:
    mylist.append(text7)
if len(text8) <> 0:
    mylist.append(text8)
if len(text9) <> 0:
    mylist.append(text9)
if len(text10) <> 0:
    mylist.append(text10)
if len(text11) <> 0:
    mylist.append(text11)
if len(text12) <> 0:
    mylist.append(text12)
woooee 814 Nearly a Posting Maven

A simple example using Tkinter's after feature. You would probably want after to call a clean-up function to check for partial entries, etc., and then call quit().

import Tkinter

class TestClass():

   def __init__(self):
      
      self.top = Tkinter.Tk()
      self.top.title("Test of Timing")
      self.top.geometry("200x150+10+10")

      label_1 = Tkinter.Label(self.top, text="Timer Test ").pack(side="left" )
      entry_1 = Tkinter.Entry(self.top, width=10).pack(side="left")

      self.top.after(5000, self.top.quit)     ## 5 seconds
      self.top.mainloop()
         
if __name__ == '__main__':
   CT=TestClass()
woooee 814 Nearly a Posting Maven

At one time there was a third party package named BitBuffer to work with binary files. I don't know if it is still around and maintained or not. You can also use array

filename = "binary_number.py"
a_long = array.array('H')
fp = open(filename, 'rb')                                                       
a_long.fromfile(fp, 1)
print a_long
a_long.fromfile(fp, 1)
print a_long
ETC
fp.close()
woooee 814 Nearly a Posting Maven

Unless I am missing something, look up the key from the first dictionary in the second dictionary.

woooee 814 Nearly a Posting Maven

Please post what you have so far and some sample data. There is no point opening the file, etc. if you already know how to do that. Usually you would read the file one line at a time, strip the record of spaces and the newline, and then split the record into words. Give it a try and post back with any problems. Note that for testing you probably want to use a shorter version of the file so you can get to the code corrections quicker.

woooee 814 Nearly a Posting Maven

Same old, same old = add some print statements to tell you what is going on.

def fac(a,b): #defining the function that uses Euclid's method
    ctr = 0
    while b>0:
        ctr += 1
        a, b = b, a%b # changing the numbers a to b, and b to remainder of a/b
        print "a & b are now", a, b, ctr
        return a
woooee 814 Nearly a Posting Maven

You have to kill the process, and how you do that is dependent on the OS you are using. You should use subprocess instead (see os.kill() at Doug Hellmann's site).

woooee 814 Nearly a Posting Maven

There are several different ways to do this. One is a dictionary pointing to a list that contains the number of records found for the key, and the thresholds found to test if greater than (if I am reading the question correctly). You could also use two dictionaries, one as the counter, and one to hold the thresholds if that is easier to understand. An SQL file would be in order if this is a large data set. You could also create a class instance for each unique name, but that is probably more trouble and more confusing than the other solutions. A simple example:

test_list = [
"john steve 0.67588",
"john matt 1.00",
"red blue 0.90",
"yellow steve 0.02" ]

test_dict = {}
for rec in test_list:
    substrs = rec.split()
    key = substrs[0]
    if key not in test_dict:
        ## add the new key, counter=1, and a list containing the threshold
        test_dict[key] = [1, [float(substrs[2])]]
    else:
        test_dict[key][0] += 1     ## add one to counter (zero location in list
        test_dict[key][1].append(float(substrs[2]))   ## interaction strength

for key in test_dict:
    ## are any > 0.5
    values = test_dict[key][1]
    for v in values:
        if v > 0.5:
            print key, v, test_dict[key][0]
woooee 814 Nearly a Posting Maven

Use string.lowercase() to generate a list of letters, then use
for letter in test_word:
to iterate through each letter in the word. random.choice() will choose one random letter (from string.lowercase) and compare, (print the letter and random.choice for the first few letters tried to see what is happening). Add the number of tries it took to a total tries field.

woooee 814 Nearly a Posting Maven

You can compare the random letters word and the original word. It took 150,000 and 300,000 iterations to get a word equal to the 10 character word in the test, so expect a 28 character word to take a really, really long time.

import random

test_word = "methinks "
test_list = list(test_word)

## try 10 tries
for ctr in range(10):
    random.shuffle(test_list)
    back_to_word = "".join(test_list)
    print back_to_word
    if back_to_word == test_word:
        print "EQUAL", ctr
woooee 814 Nearly a Posting Maven

And/or is two different things. If you want "a" or "b" then if either one is true the code is executed (the other can be false). If you want "a" and "b", the code is executed only if both are true. "And" is the same as two if() statements, "or" is the same as an if()/else() statement. Some pseudo-code:

## both have to be true
if x =="a" and x == "b" is the same as
if x == "a"
    if x == "b"
#
## either can be true
if x == "a" or x == "b" is the same as
found = False
if x == "a"
    found = True
elif x == "b"
    found = True
woooee 814 Nearly a Posting Maven

The usual method is to go from right to left
factor = 1+rate
factor = factor ** months

rateXfactor = rate * factor
etc.

woooee 814 Nearly a Posting Maven

Please mark the thread "Solved". Be aware that some people do not like using update_idletasks(), and there are at least two other ways; using .after() which does not require an update, or a Tkinter StringVar() which updates whenever the text is changed.

import time
from Tkinter import *
 
class MyApp:
    def __init__(self, parent):
        self.myParent = parent  ### (7) remember my parent, the root
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()
 
        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="Button")
        self.button1.pack()
        self.button1.bind("<Button-1>", self.button1Click)
 
        self.lbl = Label(self.myContainer1)
        self.lbl.pack()
 
        self.lbl2_text = StringVar()
        self.lbl2_text.set("lbl2")
        self.lbl2 = Label(self.myContainer1, textvariable=self.lbl2_text)
        self.lbl2.pack()
 
        self.lbl3 = Label(self.myContainer1)
        self.lbl3.pack()
 
        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Quit", background="red")
        self.button2.pack()
        self.button2.bind("<Button-1>", self.button2Click)
 
 
    def button1Click(self, event):    ### (3)
        # expensive process here
        # simulated by time.sleep
        self.lbl2_text.set("updated also")
        self.myContainer1.after(100, self.lbl3.configure(text='lbl3 Running'))

        self.lbl.configure(text='Running command...')
        self.myContainer1.update_idletasks()
        time.sleep(4)
        self.lbl.configure(text='Finished running command...')
 
    def button2Click(self, event):  ### (5)
        self.myParent.destroy()     ### (6)
 
 
root = Tk()
myapp = MyApp(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

"z" is the same as a print statement will verify, although newx and newy do change.

for n in range(10):     ## only print 10 times
        print "adding math.sin(%f) to %f" % (z, newx)
	newx=newx+math.sin(z)
        print "adding math.cos(%f) to %f" % (z, newy)
	newy=newy+math.cos(z)
print newx
print newy
##
## note that it is inefficient to calaculate sin(z) and cos(z) on every loop
##
sin_z = math.sin(z)
cos_z = math.cos(z)
for n in range(10):
	newx=newx+sin_z
	newy=newy+cos_z
print newx
print newy
##
##   an easier way to generate choices
##
choices = [x for x in range(0, 91)]
choices += [x for x in range(270, 361)]
woooee 814 Nearly a Posting Maven

You can use update_idletasks()

import time
from Tkinter import *
 
class MyApp:
    def __init__(self, parent):
        self.myParent = parent  ### (7) remember my parent, the root
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()
 
        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="Button")
        self.button1.pack()
        self.button1.bind("<Button-1>", self.button1Click)
 
        self.lbl = Label(self.myContainer1)
        self.lbl.pack()
 
        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Quit", background="red")
        self.button2.pack()
        self.button2.bind("<Button-1>", self.button2Click)
 
 
    def button1Click(self, event):    ### (3)
        # expensive process here
        # simulated by time.sleep
        self.lbl.configure(text='Running command...')
        self.myContainer1.update_idletasks()
        time.sleep(4)
        self.lbl.configure(text='Finished running command...')
 
    def button2Click(self, event):  ### (5)
        self.myParent.destroy()     ### (6)
 
 
root = Tk()
myapp = MyApp(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

time.sleep(), however, pauses the entire .py, rendering the ping/pong lines irrelevant and ultimately leading to a ping timeout.

If I understand the question, you would use threading or multiprocessing to run the code that you don't want to sleep/pause. Since it runs as a separate process, time.sleep() won't affect it.

woooee 814 Nearly a Posting Maven

Test with known numbers producing a known output to check your calculations.

##--- this statement
print 'Monthly Payment:', '$',loan * rate * 1 + rate ** 12  / 1 + rate ** -1
##
## is the same as --> there is no reason to multiply loan * rate times 1
(loan * rate * 1) + (rate ** 12)  / 1 + (rate ** -1)
woooee 814 Nearly a Posting Maven

Pass x to the file2 function.

from file2 import *
x = 6
file2Funct(x)
##
##file2.py
##
def file2Function(x):
    print x
TrustyTony commented: More proper usage advice +2
woooee 814 Nearly a Posting Maven

See this link for a tutorial on input http://www.pasteur.fr/formation/infobio/python/ch04s03.html and then test the integer for >0 and <6 to break from the while() loop.

woooee 814 Nearly a Posting Maven

I want to display in a treeview or listbox what I have in Sqlite

I use MultiListbox for that.

woooee 814 Nearly a Posting Maven

Since there aren't any (or almost no) virus protection programs for Linux/BSD/Mac, and millions of users (especially in the server area), they would be a prime target if malware could be developed to target those OS's. It's an open door, but so far the few who have been able to get through have seen that door close rapidly, so there is only one profitable option for crackers and anti-virus companies.

Every once in a while I still get an e-mail where someone wants to transfer $20 million from a third world country and wants me to help. You would think that this scam would have run out of gas years ago, but apparently there are still some suckers out there. It may come down to a variation of spam@utc.gov where you would report malware, and also click some button in the browser to validate the popup's claim before you commit. I'm afraid there is no cure for stupidity (and if someone does have a cure, please send me some)!

woooee 814 Nearly a Posting Maven

Let's create a continuing thread to program Crazy 8's from scratch for learning purposes!

DECK/CARD IDEA'S

My simple starting suggestion:

deck = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC',
        '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD',
        '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH',
        '2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS',]

Start by downloading one of the existing packages, like http://duo.tuxfamily.org/lang/en/about and look at the code. If you don't understand something, then post the question and code. I don't think there are many who volunteer their time here, who want to spend it coding a solution for you when many already exist.

doffing81 commented: good link +1
woooee 814 Nearly a Posting Maven

The error message, and not the error type, were of great help.

i.e. include the entire error message (which usually shows the offending line).

""" ------------------------------------------------
Also, this code can be simplified 
Dictionary key lookup is simply
if key in dictionary_name:
""" ------------------------------------------------
    self._inverted_index = {} #dictionary
## ...
## ...
# check if the key already exists in the dictionary, if yes, 
# just add a new value for the key
    if term in sorted(self._inverted_index.keys()):
woooee 814 Nearly a Posting Maven

Sub/superscript is done by the program displaying the text, and different programs have different ways of doing it. The Tkinter text widget, for example, uses offset (positive is super, negative is sub).

woooee 814 Nearly a Posting Maven

You could use concepts from this vegaseats post of clickable shapes:
http://www.daniweb.com/forums/post1322031.html#post1322031

You could tag all squares as named shapes and change another tag between '','X' and 'O' to mark what shape must be drawn there, when clicked, if square has been clicked you can remove the 'clickable' tag from it.

Good find. And Vegas does code some cherries.

woooee 814 Nearly a Posting Maven

Please mark this thread "solved" so the helpful volunteers don't waste their time reading a solved thread.

woooee 814 Nearly a Posting Maven

Take a look at the trackback docs. You possibly want traceback.format_exc() or extract_tb(traceback[, limit])

woooee 814 Nearly a Posting Maven

But I don't want a StringVar; I want a Canvas image.

To place text on a canvas ('X' or 'O'), you use create_text(), not buttons, which may be why the text is not showing up in the correct place. You will have to use mouse position when clicked to determine where to place the 'X' or 'O'. And keep track of what is placed where to determine the winner of course.

from Tkinter import *

root = Tk()
root.title('Canvas Test')

##----------------------------------------------------------------------------
##--- generally, you only have on3 canvas object
canvas = Canvas(root, width =300, height=300)
##----------------------------------------------------------------------------

##----------------------------------------------------------------------------
##--- from here on, the single Canvas instance is used
##----------------------------------------------------------------------------
canvas.create_line(1, 100, 300, 100, width=3)
canvas.create_line(1, 200, 300, 200, width=3)
canvas.create_line(100, 1, 100, 300, width=3)
canvas.create_line(200, 1, 200, 300, width=3)

canvas.create_text(50,50, text='0', fill='blue', font=('verdana', 36))
canvas.create_text(150,150, text='X', fill='yellow', font=('verdana', 36))

canvas.pack()
root.mainloop()
woooee 814 Nearly a Posting Maven

Because it hasn't been defined. You defined (and should use)
return self.hasFlush()

self.xxx means that it is a member of the class

return hasFlush(self)
is passing self to a hasFlush function outside of the class.

woooee 814 Nearly a Posting Maven

You don't have
if 1 in self.myranks[kitten] and 1 in self.myranks[kat]:
in any of the code you posted. Is there more than one version of this program?

It apparently thinks that self.myranks[kitten] or [kat] is an integer. Do a
print type(self.myranks[kitten])
before the offending line and see what prints. Then you will have to try and discover where self.myranks[x] is set to an integer if it indeed is one now. Note that you initialize it to a list of integers, not a list of lists, i.e. a list would be
if 1 in self.myranks

How should I fix it?

Don't create it in the first place. Don't write long blocks of code without testing and ask someone else to clean up your mess. At a minimum, test each function after you write it.

def evaluateHand(self):
 
        if self.hasStraightFlush():
            return "Straight Flush"
        elif self.hasFourOfAKind():
            return "Four of a kind"
        elif self.hasFullHouse():
            return "Full House"
        elif self.hasFlush():
            return "Flush"
        elif self.hasStraight():
            return "Straight"
        elif self.hasThreeOfAKind():
            return "Three of a kind"
        elif self.hasTwoPair():
            return "Two pair"
        elif self.hasPair():
            return "Pair"
        else:
            return "Nothing"

The above function can be optimized by testing for a pair, and not testing for 3 or 4 of a kind if a pair isn't found. along the lines of:

def evaluateHand(self):
        return_lit = 'Nothing'
        if self.hasStraight():
            return_lit = "Straight"
            if self.hasStraightFlush():
                return_lit = "Straight Flush"
        elif self.hasPair():
            return_lit = "Pair"
            if self.hasThreeOfAKind():
                return_lit = "Three of a kind"
                if self.hasFourOfAKind():
                    return_lit = …
woooee 814 Nearly a Posting Maven

You can also use some indicator that switches on and off for print positive or negative.

counter=1
positive = True
while counter < 9:
    if positive:
        print counter
    else:
        print counter * -1
    counter += 1
    positive = not positive     ## switch it
woooee 814 Nearly a Posting Maven

You want to associate each button with a Tkinter StringVar. That way, you set (change) the contents of the StringVar and it is automatically displayed on the screeen. This is the start of a Tic-Tac_Toe game, to test button use, that I never finished. It uses a dictionary to keep track of the buttons and displays "X" or "O" via a StringVar, but doesn't have a scoring system.

from Tkinter import *

class ButtonsTest:
   def __init__(self, top):
      self.button_dic = {}
      top.title('Buttons Test')
      self.top_frame = Frame(top, width =500, height=500)
      self.buttons()
      self.top_frame.grid(row=0, column=1)
      exit = Button(self.top_frame, text='Exit', command=top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   ##-------------------------------------------------------------------         
   def buttons(self):
      b_row=1
      b_col=0
      for j in range(1, 10):
         self.button_dic[j] = StringVar()
         self.button_dic[j].set(str(j))
         b = Button(self.top_frame, textvariable = self.button_dic[j])
         b.grid(row=b_row, column=b_col)

         def handler ( event, self=self, button_num=j ):
                return self.cb_handler( event, button_num )
         b.bind ( "<Button-1>", handler )

         b_col += 1
         if b_col > 2:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, event, cb_number ):
      print "cb_handler", cb_number, self.button_dic[cb_number]                
      if self.player:          ## True = "X", False = "O"
         self.button_dic[cb_number].set("X")
      else:
         self.button_dic[cb_number].set("O")
      self.player = not self.player

##===================================================================
root = Tk()
BT=ButtonsTest(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

Flirting is good for your health. Studies show that flirtatious people have higher white blood-cell counts, which improve both immunity and health.


There’s more than one way to do it. Scientists have discovered 52 specific “flirting signals” used by humans. The most common signal? The saucy hairflip, of course.


It’s still illegal in some cities. In Little Rock, AR, there’s a law on the books warning that engaging in lascivious banter may result in a 30-day jail term. Another outdated law in New York City decrees that men can be fined $25 for gazing suggestively at a female; a second conviction stipulates the offender don a pair of blinders whenever he goes outside (or just take his wife with him).


We’re doing it while driving. Forget trendy bars—the freeway is the newest meat market. A full 62 percent of drivers have flirted with someone in a different vehicle while commuting, and 31 percent of those flirtations resulted in a date (don't even try if you drive a Yugo).

woooee 814 Nearly a Posting Maven

Another beginner tutorial that might make more sense is Learning To Program http://www.freenetpages.co.uk/hp/alan.gauld/tutcont.htm but note that every print statement becomes print() on Python 3.X for that code as well.

woooee 814 Nearly a Posting Maven

Try either destroy or withdraw on the old label and see if it does what you want.

woooee 814 Nearly a Posting Maven

HelloCallBack is first defined as a variable, then as a function.

class Application(Frame):
    helloCallBack = None
 
    def helloCallBack():
        tkMessageBox.showinfo ("Hello", "Hello, do you like my application?")

Neither is correct, you want it to be a member of the class. Note also that you can not use both grid and pack, so pick one, see the Warning here http://effbot.org/tkinterbook/grid.htm

from tkinter import *
 
class Application(Frame):
##    helloCallBack = None
 
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()
 
    def helloCallBack(self):
        tkMessageBox.showinfo ("Hello", "Hello, do you like my application?")
 
    def createWidgets(self):
        self.helloButton = Button (self, text='Hello', command=self.helloCallBack)
        self.helloButton.pack()
        self.helloButton.grid()
        self.menuFile = Menubutton (self, text='File')
        self.menuFile.grid()
        self.menuFile.hiAgain = Menu (self.menuFile, tearoff = 0)
        self.menuFile["HiAgain"] = self.menuFile.hiAgain
        self.menuFile.hiAgain.add_command(label="Hello", command=self.helloCallBack)
 
 
app = Application()
app.master.title("My Attempt at python")
app.mainloop()
woooee 814 Nearly a Posting Maven

The book teaches Python 2.x. In Python 3.x, print is a function, so the last line would be
print(buildConnectionString(myParams))
In the future please include the actual error message, as it is almost impossible to debug when a program is larger, without knowing exactly what is wrong. Dive Into Python 3 is the only online book on Python 3.X that I know of.

Tenck commented: Thanks +0
woooee 814 Nearly a Posting Maven

I would suggest learning file read/write. Then you can put 101 numbers in the file and read the file to test, instead of entering 100 numbers every time you want to test.

woooee 814 Nearly a Posting Maven

For starters, break your code into smaller pieces and test each piece before moving on. As you have found out, debugging 96 lines of code is not easy. This line should be tested first as it does not do what you think.

##--- test this with a known value (word='the')
if (word != ('the'and'on'and'and'and'are'and'years'and'the')):
##
##--- I think you want something like (but can't tell from the code)
if (word not in ['the', 'on', 'and', 'are', 'years']):
woooee 814 Nearly a Posting Maven

"/ 730" has to be a float (or you have to convert somehow).

##1.0 - 2.718281828**(-(23**2)/730)
a = 23**2
print a
a *= -1
print a
print "---------------"
print a/730
a /= 730.0
print a
print "---------------"
b =  2.718281828**a
print b
print 1.0 - b
woooee 814 Nearly a Posting Maven

As you probably have guessed by now, regular expression are considered bad style by some and so learning them is possibly a complete waste of time. If you aren't aware of Jamie Zawinski's (in)famous quote
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
http://regex.info/blog/2006-09-15/247

woooee 814 Nearly a Posting Maven

Create 2 lists, one per column, and use the shuffle function of random on both,

woooee 814 Nearly a Posting Maven

Print the list fenceLines. It should contain the length of each line which you can add up or do whatever else you want. Add you probably want to use linenum+1 so it starts with one instead of zero.

fenceLines = []
for linenum in range(int(input("Enter number of lines of fence. "))):
    fenceLines.append(int(input("Enter line %s lineal feet. " % linenum+1)))
woooee 814 Nearly a Posting Maven

You have to have a separate list of winning combinations, so one of the combinations would be ([0,0], [1,0], [2,0]) which would be 3 down if all 3 positions are either "X" or "O". Another way to do this is to number the squares and store each position in a dictionary with the key being the square number. Then you would use a separate list of square numbers to find a winning position. As stated above, you also have to know when all of the squares are filled, without anyone winning, to end the game. Note that you can "and" if statements if you want. Either way is fine.

def movecheck():
    if (x in movetype) and (y in movetype):
        if board[x][y] in pieces:
            print 'Invalid move!'
        else:
            board[x][y] = pieces[turn]  ## does this function know what "turn" is??
            turncheck()
            #----- and turncheck() can be eliminated by
            turn = not turn   ## but this uses "True"/"False" not one or zero
    else:
        print 'Invalid move!'

See here for info on how to use functions.

woooee 814 Nearly a Posting Maven

All variables in create_mail are local to create_mail and can not be used in send_mail. One solution is to use one function only, which simplifies things. See here for a starter on how to use funtions.

def create_mail(message):
 
        themail = MIMEMultipart()
        recipient = "xxxxxxx@hotmail.com"
        gmail_user = "asdassdsaadssd"
        gmail_pwd = "asdasdasasdasasd"
        subject = "assadasdasasdass"
	themail['Subject']=subject
	themail['From']=gmail_user
	themail['To']=recipient
 
	themail.attach(MIMEText(message)) 
 
## comment out so everything is now part of create_mail()
##def send_mail():
	smtpserver = smtplib.SMTP("smtp.gmail.com",587)
	smtpserver.ehlo()
	smtpserver.starttls()
	smtpserver.ehlo
	smtpserver.login(gmail_user, gmail_pwd)
	print "Connection established."
	smtpserver.sendmail(gmail_user, recipient, themail.as_string())
	print "Your mail has been sent."
	smtpserver.close()
woooee 814 Nearly a Posting Maven

I would start with Scripy You can also use subprocess. Doug Hellmann has a nice write-up covering input and output pipes amount other things http://www.doughellmann.com/PyMOTW/subprocess/index.html#module-subprocess

woooee 814 Nearly a Posting Maven

You can use array or BitBuffer An eample using array

import array
a_long = array.array('f')     ## float (was 'L' for long hence var name)
fp = open(fname, 'rb')

a_long.fromfile(fp, 1)
print a_long

a_long.fromfile(fp, 1)
print a_long

fp.close()
woooee 814 Nearly a Posting Maven

I assume that you open the port, send the string, and read any returned bytes somewhere else in the code. Check out the PySerial intro and see if it would work for you. There is no point in reinventing the wheel when you have packages that are already tested and tried. It will open the port and you can then send any string you like, and issue a read command for any returned string. There is also USPP if PySerial doesn't work for some reason.

woooee 814 Nearly a Posting Maven

You can/should use a dictionary for the values, although the code you have is fine if it works and you understand it. An example:

## replace the later code with a dictionary

# A dictionary of lists.  List elements are
# position 0=price,  1=hinges,  2=latch,  3=stop
#          4=screw gate,  5=eight foot,  6=ten foot,  7=post
eight_gate_dict ={}
eight_gate_dict[1] = [100, 4, 1, 1, 24, 4, 2, -1]
## and so forth for the others
print "gate type 1"
print "     price =", eight_gate_dict[1][0]
print "     screw gate =",eight_gate_dict[1][4]
#
# which replaces
if eightGate == 1:
    Price = 100
    eightHinges = 4
    eightGateLatch = 1
    eightGateStop = 1
    eightScrewGate = 24
    eightEightFooters = 4
    eightTenFooters = 2
    post = -1