snippsat 661 Master Poster

Make TT a datetime object with strptime.
Change to datetime.now().
Now we have 2 datetime object that we can subtract.

>>> from datetime import datetime
>>> TT = "2012-01-16"
>>> tt_date = datetime.strptime(TT, '%Y-%m-%d')
>>> tt_date
datetime.datetime(2012, 1, 16, 0, 0)
>>> now = datetime.now()
>>> now
datetime.datetime(2012, 2, 29, 21, 4, 29, 491000)
>>> print now - tt_date
44 days, 21:04:29.491000
snippsat 661 Master Poster

You have to convert to int() or float().
If you concatenate two string then is just strings not numbers.

>>> '5' + '2'
'52'
a = raw_input("enter 2 numbers separated by a /: ") #5/2 entered
b = a.split("/")
c = int(b[0]) + int(b[1])
print c

You can also do it like this if you have a list with string.

>>> l = ['5', '2']
>>> [float(i) for i in l]
[5.0, 2.0]
>>> l = ['5', '2']
>>> map(int, l)
[5, 2]
>>> sum(float(i) for i in l)
7.0
snippsat 661 Master Poster

When you dont give path to "names.txt" as do in my example.
"names.txt" will be in same directory as you run the script from. open(r'C:\test\names.txt', 'w') here i give a path.
Read a little more in doc as Tony suggest.

snippsat 661 Master Poster

Look a a little messy,here a couple of way to write a list to a file.
If you need more help post a sample of list and how you want it to look in a file.

l = ['Fauntleroy Duck', 'Mickey Mouse']
with open('names.txt', 'w') as f_out:
    f_out.write(', '.join(l))

'''Output-->
Fauntleroy Duck, Mickey Mouse
'''
l = ['Fauntleroy Duck', 'Mickey Mouse']
with open('names.txt', 'w') as f_out:
    for line in l:
        f_out.write('%s\n' % line)

'''Output-->
Fauntleroy Duck
Mickey Mouse
'''
snippsat 661 Master Poster

sort() dos a in place sort of orginal list and it dont return anything.

>>> mystring = 'blue, pink, red, red, red, white, long, short, blonde, blonde'
>>> s = mystring.split(', ')
>>> s
['blue', 'pink', 'red', 'red', 'red', 'white', 'long', 'short', 'blonde', 'blonde']
>>> s.sort()
>>> s
['blonde', 'blonde', 'blue', 'long', 'pink', 'red', 'red', 'red', 'short', 'white']

>>> help(s.sort)
Help on built-in function sort:

sort(...)
    L.sort(key=None, reverse=False) -- stable sort *IN PLACE*

Use sorted() for store result in variable.

>>> s_sort = sorted(set(mystring.split(', ')))
>>> s_sort
['blonde', 'blue', 'long', 'pink', 'red', 'short', 'white']
snippsat 661 Master Poster

A dictionary can ofen short down long if/elif statement.
Something like this.

def find_numb(phone_dict, user_input):
    try:
        return [k for k, v in phone_dict.items() if user_input in v][0]
    except IndexError:
        return('Not found')

user_input = input("Enter a single letter: ") #Return a string
phone_dict = {2: ('a', 'b', 'c'), 3: ('d', 'e', 'f')}
print(find_numb(phone_dict, user_input))
snippsat 661 Master Poster

Dont use file as variable/argument is a built-in functions.

>>> f = open(file, 'a')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, type found
>>> file
<type 'file'>
>>>
snippsat 661 Master Poster

I am new to python and cant figure out what I am doing wrong with the global variables

Dont use global statement,because it is ugly.
Function should receive arguments and return value/s out.
Code should stay local to function,with global statement you are destoring that.
Use code tag,now i think it work as you expected.

#number = 0 why

def test():
    #global number ugly
    number = raw_input("Please type a number.") #return a string
    return number

def prints(number):
    #global number ugly
    #if number2 != 1: #Where is number2 coming from?
    if int(number) != 1: #make number an integer
        print "Yes"
    else:
        print "NO!"

number = test()
prints(number) #we give function test() return value as an argument to function prints()
snippsat 661 Master Poster
import re

def main():
    name = 'francis ford coppola'
    #space = name.find(" ") #will only find first space at 7
    space = [m.start() for m in re.finditer(' ', name)] #[7, 12]
    first = name[:space[0]]
    middle = name[space[0]+1:space[1]]
    last = name[space[1]+1:]
    print(first)
    print(middle)
    print(last)

main()

Without using regex module.

def find_index(name):
    name_index = []
    found = name.find(" ")
    while found > -1:
        name_index.append(found)
        found = name.find(" ", found + 1)
    return name_index

def main():
    name = input("Please enter a full name with 3 names, separated by one space: ")
    #name = 'francis ford coppola'
    space = find_index(name)
    first=name[:space[0]]
    middle=name[space[0]+1:space[1]]
    last=name[space[1]+1:]
    print(first)
    print(middle)
    print(last)

main()
snippsat 661 Master Poster

Hi use code tag next time,mark your code and press "code"
You only find first space at index 7.
The second one is at index 12

>>> name = 'francis ford coppola'
>>> space=name.find(" ")
>>> space
7

This:

name = 'francis ford coppola'
l = []
found = name.find(" ")
while found > -1:
    l.append(found)
    found = name.find(" ", found + 1)

print(l) #[7, 12]

Or simpler.

>>> import re
>>> name = 'francis ford coppola'
>>> [m.start() for m in re.finditer(' ', name)]
[7, 12]

Then you can use it like this.

>>> name = 'francis ford coppola'
>>> space = [m.start() for m in re.finditer(' ', name)]
>>> space
[7, 12]
>>> name[:space[0]]
'francis'
>>> name[space[0]+1:space[1]]
'ford'
>>> name[space[1]+1:]
'coppola'

There is a simpler way,i guess this is to learn about string slice.
Look at this.

>>> name = 'francis ford coppola'
>>> first, middle, last = name.split()
>>> first
'francis'
>>> middle
'ford'
>>> last
'coppola'
snippsat 661 Master Poster

I'm working on the py2exe convertor, which will convert files from .py to .exe

It seems like you are making this to diffcult and you are missing stuff like setup option.
Look at this,will convert py file to exe.

from distutils.core import setup
import py2exe
import sys

def py2_exe(file_in=None):
    if len(sys.argv) == 1:
        sys.argv.append('py2exe')

    setup(options = {'py2exe': {'compressed': 1, 'optimize': 2, 'ascii': 1, 'bundle_files': 3}},
           zipfile = None,

           ## Can use console or window
           ## Filpath to '....py' run this script in same folder as file_in
          console = [{'script': file_in}])

if __name__ == '__main__':
    #Use raw string then you dont need \\ or /
    file_in = r'c:\test\singel_digits.py'
    py2_exe(file_in)

There is also Gui2exe you can look at.

snippsat 661 Master Poster

See if this help,it seems to work for me in this test
This script dos delete the file and create a new file in one go.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)

print "It didn't exist so I'm creating it"
f = open('t.txt', 'w+')
f.close()

Here it will delete file at first run and stop.
Second run the file dont exist,so then else block will run and create the file.

import os

ofile = r'c:\test4\t.txt'
if os.path.exists(ofile):
    print 'ofile exists'
    os.unlink(ofile)
else:
    print "It didn't exist so I'm creating it"
    f = open('t.txt', 'w+')
    f.close()
snippsat 661 Master Poster

Just to clear tings up.
Is ofile referring to a path or a file?
Just a example,and you missing a else block.

import os

ofile = r'c:\test4'
if os.path.exists(ofile):
    print 'ofile exists'
else:
    print 'ofile dont exist'

os.path.exists return True if path refers to an existing path.
Returns False for broken symbolic links.
So if "c:\test4" exist it will print "ofile exists" else "ofile dont exist"
The name ofile is confusing when os.path.exists check for path.

snippsat 661 Master Poster
>>> d = {'ric':24, 'ric1':46, 'ric2':23, 'mike':1, 'mike1':47}
>>> l = ['ric', 'mike']
>>> for name in l:
...     if name in d:
...         print '{0} has a value of {1}'.format(name, d[name])
...         
ric has a value of 24
mike has a value of 1
snippsat 661 Master Poster

Here we go again:ooh:

>>> a = 1
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 1, '__package__': None}

What`s happen here is that we take a look into the global namespace.
We see that global namespace store 'a': 1 as a dictionary.
Let create a visible dictionary.

>>> d = {'a': 1}

Now we shall use both.

>>> globals()['a']
1
>>> d['a']
1
>>>

So a advice dont use python internal working like global namespace as a dictionary.
The code get much clearer if you make a ordinary dictionary.

snippsat 661 Master Poster

The above code creates an array but, each element is 4 bytes each.

Not an array in python we call it a list.
A list in python is much more flexible than "array" as it`s called in C/C++,java.

Python has 3 types ints, longs or floats.
eight bits unsigned(can store 0-->255) so in python it`s a int.

I would like it to be as large as possible. I need it for a sieve prime number program.

In Python integers have a size only limited by your computer's memory.
If you want to force compatibility with C you can use Python module struct

snippsat 661 Master Poster
>>> a = 1
>>> b = 2
>>> ranking = ['a', 'b']
>>> sum(globals()[i] for i in ranking)
3

Like this,but not nice.
You see PyTony make a dictionary and than take out values.

But you have to rethink this.
string 'a' and 'b' in ranking is just string not pointing to anything.
You can bind string 'a' 'b' to variable a b.

>>> d = {}
>>> d[ranking[0]] = a
>>> d[ranking[1]] = b
>>> d
{'a': 1, 'b': 2}

Or just make a dictionary in first place,not confusing stuff like now.

snippsat 661 Master Poster
>>> a = 1
>>> ranking = "a"
>>> print 'ranking is %s' % globals()[ranking]
ranking is 1

This is more of a ugly hack and dont do it like this.
You are better of bulding a dictionary.
Something like this

>>> d = {'ranking_a': 1, 'ranking_b': 2}
>>> d['ranking_a']
1

If problems post a better description of what you are trying to do.

snippsat 661 Master Poster
with open('numb.txt') as f:
    print [i.split() for i in f]
    #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']]

A little mistake like this for 1 list.

with open('numb.txt') as f:
    print f.read().split()
    #['1', 'string1', '2', 'string2', '10', 'string3']
snippsat 661 Master Poster

Just to simplify little and use better names.

import os

for root, dirs, files in os.walk(r'C:\test'):
    for f in files:
         if f.startswith('roads.'):
            print f
            #print os.path.join(root, f)

So this will print only files that starswith "roads" in directory c:\test.
we iterate over files and last line we can join root(path) with filename.

snippsat 661 Master Poster

Something like this should do it.

import re

text = '''\
BEGIN:VCARD
VERSION:2.1
REV:20110913T095232Z
UID:aac119d5fe3bc9dc-00e17913379d6cc8-3
N;X-EPOCCNTMODELLABEL1=First name:;Maj;;;
TEL;VOICE:09120000000
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083215Z
UID:aac119d5fe3bc9dc-00e17b0693898c98-4
N;X-EPOCCNTMODELLABEL1=First name:;Ali jahan;;;
TEL;VOICE:09120000001
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083510Z
UID:aac119d5fe3bc9dc-00e17b069df653a0-5
N;X-EPOCCNTMODELLABEL0=Last name;X-EPOCCNTMODELLABEL1=First name:Eqlimi;Mostafa;;;
TEL;CELL;1:+989120000002
TEL;VOICE:09180000003
X-CLASS:private
TEL;CELL;2:09390000004
X-CLASS:private
END:VCARD
'''

for match in re.finditer(r"CELL;\d:(.*)", text):
    print match.group(1)

'''Output-->
+989120000002
09390000004
'''
snippsat 661 Master Poster

I see that you have solved it,that`s god.
I did mix something together with regex when i saw the post.
Here it is not the cleanest soultion,but shoud work ok.

import re

text = '''\
BEGIN:VCARD
VERSION:2.1
REV:20110913T095232Z
UID:aac119d5fe3bc9dc-00e17913379d6cc8-3
N;X-EPOCCNTMODELLABEL1=First name:;Maj;;;
TEL;VOICE:09120000000
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083215Z
UID:aac119d5fe3bc9dc-00e17b0693898c98-4
N;X-EPOCCNTMODELLABEL1=First name:;Ali jahan;;;
TEL;VOICE:09120000001
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083510Z
UID:aac119d5fe3bc9dc-00e17b069df653a0-5
N;X-EPOCCNTMODELLABEL0=Last name;X-EPOCCNTMODELLABEL1=First name:Eqlimi;Mostafa;;;
TEL;CELL;1:+989120000002
TEL;VOICE:09180000003
X-CLASS:private
TEL;CELL;2:09390000004
X-CLASS:private
END:VCARD
'''

#Find names
name_re = []
for match in re.finditer(r"name:;.*|name:.*", text):
     name_re.append(match.group())
temp = re.sub(r'name|[:;]', ' ', ','.join(name_re))
temp = temp.strip().split(',')
names = [i.strip() for i in temp]

#Find voices
voice = []
for v in re.finditer(r"VOICE:(.*)|1:(.*)", text):
     voice.append(v.group(1)),voice.append(v.group(2))
voice = [i for i in voice if i != None][:3]


#Zip list together
result = dict(zip(names, voice))
print result
"""Output-->
{'Ali jahan': '09120000001', 'Eqlimi Mostafa': '+989120000002', 'Maj': '09120000000'}
"""
snippsat 661 Master Poster

You cannot just open an ordinary txt file with pickle.
You have to dump something to it first.

# Save a dictionary into a pickle file.
import pickle

favorite_color = {"lion": "yellow", "kitty": "red"}
pickle.dump(favorite_color, open("Ex.txt", "wb"))

favorite_color = pickle.load(open("Ex.txt", "rb" ))
print(favorite_color) #{'lion': 'yellow', 'kitty': 'red'}
snippsat 661 Master Poster

You can look at this,and type is a reserved word in python.

class Object_refs(object):
    def __init__(self, descriptor_type, my_type, reference_count, flags=None):
        '''initializer method can be compared with constructor C++,but are not the same'''
        self.desctype = descriptor_type
        self.my_type = my_type
        self.refcount = reference_count
        self.flags = flags

Use class.

>>> descriptor_type = 1
>>> my_type = 'string'
>>> reference_count = 10
>>> obj = Object_refs(descriptor_type,my_type,reference_count)
>>> obj.my_type
'string'
>>> obj.my_type = '\u01'
>>> obj.my_type
'\\u01'
>>>
snippsat 661 Master Poster

Best way to create one is to not to.

Pseudo-random number generators are a very complex subject, so it's better off to use the implementations produced by the people that have a good understanding of the subject.

Python uses the Mersenne twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1.
The underlying implementation in C is both fast and threadsafe.

You can of course look at all code for python.
http://svn.python.org/projects/python/trunk/Modules/_randommodule.c
http://svn.python.org/projects/python/trunk/Lib/random.py

Pitfalls in Random Number Generation

def get_random_number():
    '''Chosen bye a fair dice roll,guaranteed to be random'''
    return 4
Gribouillis commented: nice post +13
snippsat 661 Master Poster

Almost always nothing after else: .
You have some cases like a ternary operator,list comprehension where else is not bare.
You can you use if or elif in this case.

It is almost always best to try avoiding global statement.
Pass variable in as an argument and in most cases return result out(insted of print in function)
So these 3 function do the same.

def room_4b(medical_kit):
    if medical_kit >= 1:
        print "You have a medical kit."
    elif medical_kit <= 0:
        print "If only you could revive him somehow."
    else:
        print 'Someting else'

medical_kit = 0
room_4b(medical_kit)
def room_4b(medical_kit):
    if medical_kit >= 1:
        print "You have a medical kit."
    else:
        print "If only you could revive him somehow."

medical_kit = 0
room_4b(medical_kit)
def room_4b(medical_kit):
    if medical_kit >= 1:
        return "You have a medical kit."
    return  "If only you could revive him somehow."

medical_kit = 0
print room_4b(medical_kit)
snippsat 661 Master Poster

Do you use python 3 or 2?
By your print statement it look like you use python 3.

I dont want to reindented your code.
Here is a couple basic versions that may help you.

#python 2.x
import random

secret_number = random.randint(1,20)
counter = 0
guess = 0
print 'Guess the number between 1 and 20'
while guess != secret_number:
    guess = int(raw_input("Take a guess: "))
    if guess > secret_number:
        print 'Lower'
    elif guess < secret_number:
        print 'Higher'
    counter += 1
print 'You guessed it! The number was %s in %d tries' % (guess,counter)
#python 3.x
import random

secret_number = random.randint(1,20)
counter = 0
guess = 0
print('Guess the number between 1 and 20')
while guess != secret_number:
    guess = int(input("Take a guess: "))
    if guess > secret_number:
        print('Lower')
    elif guess < secret_number:
        print('Higher')
    counter += 1
print('You guessed it! The number was %s in %d tries' % (guess,counter))

Look at the difference in input() and print statement python 2 and 3,and i use string formatting.
There is also new string formatting it look like this,from python 2.6-->

print('You guessed it! The number was {0} in {1} tries'.format(guess,counter))

This new string formatting has a lot of power,so look into it.

Edit:looked into your syntax error link,so i se now that you use python 3.
But is good for you to learn the differnce python 2/3,most of the code books/tutorials/forum are python 2.x.

snippsat 661 Master Poster

but I would at least be able to choose how many digits it goes out to, and not have it end prematurely. Do you have any suggestions?

There is no problem to control how many digits you want with decimal module use getcontext().prec or python string formatting.

>>> from decimal import *
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 2
>>> Decimal(1) / Decimal(7)
Decimal('0.14')
>>> print Decimal(1) / Decimal(7)
0.14
>>> getcontext().prec = 7
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571')
>>> '%.2f' % (Decimal(1) / Decimal(7))
'0.14'
snippsat 661 Master Poster

Just to give you a hint with modulo operator as pyTony mention.

>>> 38 % 10
8
>>> 369 % 10
9
>>> 36 % 10
6
>>> 36999 % 10
9
>>>

So loop over element in list with modulo operator ,and use build in sum() to get result.

snippsat 661 Master Poster

but it says its not right, whats wrong with it?

The code works,python always give you Traceback.
Post Traceback next time.

Run of code.

>>> generateNumber(0,10,2)
[0, 2, 4, 6, 8, 10]
>>> generateNumber(20,0,-3)
[20, 17, 14, 11, 8, 5, 2]
>>>
snippsat 661 Master Poster

If you think of something else than code under,give an example of list and task.

>>> l = [1,2,3,4]
>>> l[:2]
[1, 2]
>>> l[2:]
[3, 4]
>>> #Sum up last 2 digits
>>> sum(l[2:])
7
snippsat 661 Master Poster

With list comprehension it can look like this.
Just a little thing capitale letters should only be used in class name.
Not in function name or method name.

def gen_numbers(num):
    return [i for i in range(num+1)]
snippsat 661 Master Poster

You most explain better,there are several scenarios for this.
Look at this.

>>> s = 'foo bar foo bar foo'
>>> len(s.split())
5

So 5 substring in s.

>>> s[:2]
'fo'

"fo" is a substring of s.

import re
[m.start() for m in re.finditer('oo', s)]
[1, 9, 17]

"oo" is substring,to find all i use regex.

>>> s = 'ttt'
>>> [m.start() for m in re.finditer('(?=tt)', s)]
[0, 1]

Find overlapping matches

Also look at build in string function can help.

>>> help(s.find)
Help on built-in function find:

find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

>>>
snippsat 661 Master Poster

Can I use the same method to contiue copying lines under e.g. two or three lines under the "key-word"-line?

Yes just pratice with code you have got.
Here something you can look at.

#test.txt
line 1
line 2
line 3 
line 4
line 5
line 6 a keyword
line 7
flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag: #Try if to
            print line.strip()
'''
Output-->
line 3
line 4
line 5
line 6 a keyword
line 7
'''

Next we want to stop at line 6.

flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag:
            print line.strip()
            if 'keyword' in line:
                flag = False
'''Output-->
line 3
line 4
line 5
line 6 a keyword
'''

There are differnt way of doing this as you se i you flag as a start/stop mechanism.

snippsat 661 Master Poster

Or "flag = False" after write in my code.
As you se pyTony use only with open ,wicht is an better option.

snippsat 661 Master Poster

Something like this, with open() close fileobject auto.
If you want line 2 also,change elif to if .

#test.txt
line 1
line 2
line 3 
line 4
f_out = open('outfile.txt', 'w')

flag = False
with open('test.txt') as f:
    for line in f:
        if 'line 2' in line:
            flag = True
        elif flag:
            f_out.write(line)

f_out.close()
'''Output-->
line 3
line 4
'''
snippsat 661 Master Poster

Just some points,always use raw string r' ' with regex.
For email validation re.match(),for extracting re.search, re.findall().

There is no simple soultion for this,diffrent RFC standard set what is a valid email.
This has been up in several forum,here is a good one you can read.
http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses

Just a quick test with a invalid email address.

>>> e = 'Abc.@example.com'
>>> if re.match(r'(\w+[.|\w])*@(\w+[.])*\w+', e):
...     print 'Successful match'
... else:    
...     print 'Match attempt failed'
...     
Successful match

Good effort this is not so much criticism,i think you as many stumple into this.
So a regex that validate email addresses accordingh to RFC 822,look like this.
http://ex-parrot.com/~pdw/Mail-RFC822-Address.html

snippsat 661 Master Poster

Well thanks for your suggestion,but in this case its not working.I am getting "IndexError: list index out of range" error.May be its because i am trying with huge page.And one more thing is the part of this html code is inactive means its between <!-- --> this tags.

That may be because you making and error,impossibile to say without seeing some code.
Regex ...no,but here something you can look at.

>>> import re
>>> re.findall(r'class="test" src="(.*?)"', html)
['http://www.test.com/file.ext']
>>> ''.join(re.findall(r'class="test" src="(.*?)"', html))
'http://www.test.com/file.ext'
>>>
snippsat 661 Master Poster

Read this.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

So regex it not the right tool when it comes to html/xml.
There is a reason why parser excit,python has 2 very good lxml and BeautifulSoup.

from BeautifulSoup import BeautifulSoup

html = """\
<div class="test" src="http://www.test.com/file.ext" style="top:0px;width:100%;>"
"""

soup = BeautifulSoup(html)
tag = soup.find('div')
print tag['src']
#--> http://www.test.com/file.ext

So in a lager page your search would be more specific something like this.

from BeautifulSoup import BeautifulSoup

html = """\
<div class="test" src="http://www.test.com/file.ext" style="top:0px;width:100%;>"
"""

soup = BeautifulSoup(html)
tag = soup.findAll('div', {'class': 'test'})
print tag[0]['src']
#--> http://www.test.com/file.ext
snippsat 661 Master Poster

Like this with correct indentations.

I double checked my indentation and this still doesn't work for me,

Do not post that code dont work,python always give you Traceback.
Next time post code and Traceback,then is`t much eaiser to help.
Understanding Traceback is very important part of programming in python.
1 line you get syntax error because of missing #

Also code from HiHe works,so now you have a couple working example with pyside.

#!/usr/bin/python 
# -*- coding: utf-8 -*-

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        # Create widgets
        self.edit = QLineEdit("Write my name here")
        self.button = QPushButton("Show Greetings")
        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        # Set dialog layout
        self.setLayout(layout)
        # Add button signal to greetings slot
        self.button.clicked.connect(self.greetings)
        # Add button signal to exit slot
        exit_button = QPushButton("Exit")
        exit_button.clicked.connect(sys.exit)

    # Greets the user
    def greetings(self):
        print ("Hello %s" % self.edit.text())

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication([])
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())
vegaseat commented: good point +15
snippsat 661 Master Poster

Pyhon has Tkinter,wxpython,PyQt(pyside),PyGTK that you can make GUI with.
Also ironpython,jython can be used to make GUI.

You say window form builder it is used by Visual Studios to make GUI as mention by Theh B.
Just same can you do with GUI-toolkit mention above.
And better those GUI-toolkit are crossplatform,something windows form(CLR) are not.

There are very good sticky thread you can look at here.
http://www.daniweb.com/software-development/python/threads/191210
http://www.daniweb.com/software-development/python/threads/128350

You should learn basic python first,GUI with python is not so hard to learn.
But if your python knowledge is not so good,then to make GUI becomes a lot harder to learn.

Those crossplatfrom GUI-toolkit mention above are used by many program you may use or have heard of.
Just a couple of example is.
http://www.videolan.org/vlc/
http://www.dropbox.com/

If you want to make websites then you look at this.
http://wiki.python.org/moin/WebFrameworks

snippsat 661 Master Poster

What are you trying to do?,explain better what you want to count.
Your code now dosent make much sense.

snippsat 661 Master Poster
from BeautifulSoup import BeautifulSoup

html = '''\
<tr id="index_table_12345" class="index_table_in">
<td><a href="/info/12345">string 1</a></td>
<td><a href="/info/12345">string 2</a></td>
<td><a href="/info/12345">string 3</a></td>
<td><a href="/info/12345">string 4</a></td>
<!--td></td--></tr>'''

soup = BeautifulSoup(html)
tag = soup.findAll('a') #all "a" tag in a list

print [i.text for i in tag] #[u'string 1', u'string 2', u'string 3', u'string 4']
print [i['href'] for i in tag] #[u'/info/12345', u'/info/12345', u'/info/12345', u'/info/12345']
#Code over is list comprehension

#As a ordinary loop,it look like this without append to a list
for i in tag:
    print i.text
'''Out-->
string 1
string 2
string 3
string 4
'''
snippsat 661 Master Poster

Something like this,if you want sting 1,string 2.... just iterate over the content.

from BeautifulSoup import BeautifulSoup

html = '''\
<tr id="index_table_12345" class="index_table_in">
<td><a href="/info/12345">string 1</a></td>
<td><a href="/info/12345">string 2</a></td>
<td><a href="/info/12345">string 3</a></td>
<td><a href="/info/12345">string 4</a></td>
<!--td></td--></tr>'''

soup = BeautifulSoup(html)
tag = soup.findAll('td') #all "td" tag in a list
tag_a = tag[0].find('a')

print tag_a.text #string 1
print tag_a['href'] #/info/12345
snippsat 661 Master Poster

For python 2 and 3,i think you use pyhon 3 because you get error on print.

#Python 2.7
>>> print r"pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1", pow(2,3), pow(2,3,1)
pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1 8 0
#Python 3
>>> print(r"pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1", pow(2,3), pow(2,3,1))
pow(2,3) returns 2^3 pow(2,3,1) returns 2^3 modulo 1 8 0
>>> help(pow)
Help on built-in function pow in module builtins:

pow(...)
    pow(x, y[, z]) -> number
    
    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

>>>
snippsat 661 Master Poster

Tk GUIs don't look and behave like a native application, which affects the "look & feel" in multiple small ways,
which make a complex app feel weird and clunky compared to native apps on given system.
So Tkinter will not look god on windows.

For more better looking GUI look into wxpython,PyQt(pyside),PyGTK.

snippsat 661 Master Poster

There are many postet how to use py2exe and cx_freeze on this site.
Just search.

snippsat 661 Master Poster

Some code that should help,it is close to what pyTony suggests.
Making a dictionary will be suited for this.

with open('fruit.txt') as f:
    l = [i.strip() for i in f]
    my_dict = dict(zip(l[0::2], l[1::2]))

Test in IDLE.

>>> my_dict
{'apple': '1.99', 'coconut': '1.59', 'orange': '9.99'}
>>> search = 'apple'
>>> if search in my_dict:
...     print my_dict[search]
...     
1.99
>>>
snippsat 661 Master Poster
def ziword(filename):
    count = {}
    for aline in filename:
        words = aline.lower().split()
        for word in words:
            if word in count:
                count[word] += 1
            else:
                count[word] = 1
        return count


#The point is that file is outside the function
filename = open("fox.txt")
print ziword(filename)

The point is that you give filename as argument to the function.
You also have forget to retun something out of the function.
Watch you indentation always use 4 space,and look how i use 1 space after an operator(=+-*).
Look at PEP-8 python style guide.

snippsat 661 Master Poster

You can do like this.

infile = open("afile.txt")
count = {}
for aline in infile:
    words = aline.lower().split()
    for word in words:
        if word in count:
            count[word]  +=1
        else:
            count[word] = 1

print(count)

Also remove punctuation,this is an other way than isalpha() ,use string.punctuation .
This has advangtes that is also count words that can have number.
So car nr5 will be two words, isalpha() will also remove numbers.

from string import punctuation

infile = open("afile.txt")
count = {}
for aline in infile:
    words = ''.join(c for c in aline.lower() if c not in punctuation)
    words = words.split()
    for word in words:
        if word in count:
            count[word]  +=1
        else:
            count[word] = 1

print(count)

Just to take out that line and show you how it works in IDLE.

>>> from string import punctuation
>>> s = 'The quick,,, brown?? fox... jumps!! over the lazy++ dog....'
>>> ''.join(c for c in s.lower() if c not in punctuation)
'the quick brown fox jumps over the lazy dog'

A little python power;)