snippsat 661 Master Poster

This is a compressed version,if you see me post in link you see more how it works in part.

>>> from collections import Counter
>>> import random
>>> Counter(map(lambda x : 'even' if x % 2 == 0 else 'odd', (random.randint(0,1000) for i in range(100))))
Counter({'even': 58, 'odd': 42})
snippsat 661 Master Poster

First page 8 post down.
Generating count for odd & even

snippsat 661 Master Poster

Some hint and look at differnt ways to count.
For counting this is a standar way.

import random

n = 100
even = 0
for item in range(n):
    if random.randint(1,n) % 2 == 0:
        even += 1

print('Even numer count is {}\nOdd number count is {}'.format(even, n - even))

"""Output-->
Even numer count is 53
Odd number count is 47
"""

So here i just count and dont't show numbers,if you need to show numbers use "else" and lists you append number to.

Your list comprehension stuff in last post is wrong.
A quick demo.

>>> lst = [random.randint(1,10) for i in range(10)]
>>> even = [i for i in lst if i % 2 == 0]
>>> odd = [i for i in lst if i % 2 == 1]
>>> even
[4, 10, 10, 2, 8, 8]
>>> odd
[5, 5, 5, 7]
>>> len(even)
6
>>> len(odd)
4

In first post you have a is_even helper function,this is a good way.
So here almost same function i use name to make it clearer.

def odd_even(n):
    if n % 2 == 0:
        return 'even'
    return 'odd'

Use function.

    lst = [random.randint(1,10) for i in range(10)]
    >>> map(odd_even, lst)
    ['even', 'even', 'odd', 'even', 'odd', 'odd', 'odd', 'even', 'odd']
    >>> # Or list comprehension
    >>> [odd_even(i) for i in lst]
    ['even', 'even', 'odd', 'even', 'odd', 'odd', 'odd', 'even', 'odd']

So here it show odd/even next step can be …

snippsat 661 Master Poster

Php will be still around because it can work on almost any host.

So the future is php python javascript.

Yes all of this languages will be there in the future.
I wish that PHP would be less popular because it's a messy language,but i dont think so.
PHP: a fractal of bad design

I wrote a little about Python and web here.
http://www.python-forum.org/viewtopic.php?f=10&t=3546

snippsat 661 Master Poster

The import statement will return the top level module of a package.
You can try this.

varhelp = __import__("sys").path

But be careful and try to keep "magic stuff" away from import statement.
import(doc)

Note This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

snippsat 661 Master Poster
>>> from collections import OrderedDict
>>> s = "Mathematics".upper()
>>> ''.join(OrderedDict.fromkeys(s))
'MATHEICS'
snippsat 661 Master Poster

How do you run PyPy?

Run PyPy is very easy.
Windows download Windows binary (32bit)
Pack out to example C:\pypy
Navigate to folder in cmd then.
C:\pypy>pypy some_file_to_run.py

Linux example Mint,search software manager for PyPy install.
Navigate to folder.

tom@tom-VirtualBox:/usr/lib/pypy/bin > ./pypy-c -m timeit [1,2,3,4]
1000000000 loops, best of 3: 0.000777 usec per loop
tom@tom-VirtualBox:/usr/lib/pypy/bin > 

So pypy or pypy-c just replace python as run command.

For even better performance,look at video from 9 min.
There is possible to run translate.py -Ojit on your computer.

snippsat 661 Master Poster

Doesn't PyPy actually translate to C?

Yes that one of the process,if you look at video bye David Beazle you get a better overview.
There is a lot of heavy stuff under the cover.

snippsat 661 Master Poster

So how would speed test over look in PyPy?

C:\pypy>pypy -m timeit (1,2,3,4)
1000000000 loops, best of 3: 0.00102 usec per loop

C:\pypy>pypy -m timeit [1,2,3,4]
1000000000 loops, best of 3: 0.00102 usec per loop

Hmm faster and no time differnce,don't ask why PyPy is the diabolical work of super programmers.
A god a funny video when David Beazley look into PyPy.

snippsat 661 Master Poster

A tuple uses much less memory than a list.

And should be faster.

C:\>python -m timeit (1,2,3,4)
10000000 loops, best of 3: 0.0226 usec per loop

C:\>python -m timeit [1,2,3,4]
10000000 loops, best of 3: 0.194 usec per loop

Yes tuple are faster than list.

snippsat 661 Master Poster

it seems you are using the new version of python

No he is using Python 2.4,do you not see output from sys.version in his post?

snippsat 661 Master Poster

Use Python 2.7.5
The try to run code again.

Python 3.3.2 is also ok,but most of tutorial/books are still for python 2.
Most of us still use python 2,until most 3 party module is rewritten for python 3.

snippsat 661 Master Poster

Why are you using Python 2.4 wish is 8 year old?
Code works for Python 2,even if there some ugly stuff in it.

Post full Traceback.

snippsat 661 Master Poster

Download numpy for Python 3.3 here,try again.

snippsat 661 Master Poster

You are trying to install pyhook for Python 2.7,
wish you don't have installed.
Many modules work still only for python 2.x that's why most of us still you Python 2.

Pyhook works for python 3.3 you can find a version here.

snippsat 661 Master Poster

Date and time measurement is a complex area full of tricky problems and unexpected edge-cases.
This is why we have and should use libraries for this.
It can of course be fun to do this manually,but also painful if you try for a long periods of time like this.

Just a demo how it can look with datetime module.

import datetime

date = datetime.date(1901, 1, 1)
days = 0
while date.year < 2001:
    if date.weekday() == 6 and date.day == 1:
        days += 1
    date += datetime.timedelta(days=1)

print 'Sundays that felled on the first month during the twentieth century was {}'.format(days)

"""Output-->
Sundays that felled on the first month during the twentieth century was 171
"""
ddanbe commented: Nice answer. +14
snippsat 661 Master Poster

sorry, but what prevents the code from only ever reaching the first '****optimisation achieved****' and counting that line repeatedly?

Here is an another way to this.
Here i want to get file name and count back,and also correct line number back.

file_1.txt:

fire
fox
**** Optimisation achieved ****

file_2.txt:

**** Optimisation achieved ****
car ¨
123
**** Optimisation achieved ****
**** Optimisation achieved ****
**** Optimisation achieved ****

file_3.txt:

**** Optimisation achieved ****
hello
world
**** Optimisation achieved ****

So a manual count would be.
file_1 has 1 "Optimisation" count at line 3
file_2 has 4 "Optimisation" count at line 1,4,5,6
file_3 has 2 "Optimisation" count at line 1,4

Some code for this.

import re
from glob import glob

count = {}
line_numb = []
for files in glob('*.txt'):
    #print(files)
    with open(files) as f_in:
        for num, line in enumerate(f_in, 1):
            line = line.strip()
            if '**** Optimisation achieved ****' in line:
                count[f_in.name] = count.get(f_in.name, 0) + 1
                line_numb.append(num)
        line_numb.append(f_in.name)

line_numb = ' '.join(str(i) for i in line_numb)
line_numb = re.split(r'\w+.txt', b)
line_numb.pop()
opt_count = (sorted(count.items(), key=lambda x: x[0]))

print('-'*5)
print(line_numb)
print(opt_count)
print('-'*5)

with open('result.txt', 'w') as f_out:
    for line, count in zip(line_numb, opt_count):
        print('{} has "Optimisation" count of {}\n"Optimisation" occur at line nr: {}\n'.format(count[0], count[1], line.strip()))
        #f_out.write('{} has "Optimisation" count of {}\n"Optimisation" occur at line nr: {}\n'.format(count[0], count[1], line.strip()))


"""Ouptput-->
-----
['3 ', ' 1 4 5 6 ', ' 1 4 ']
[('file_1.txt', 1), ('file_2.txt', 4), ('file_3.txt', …
snippsat 661 Master Poster

Use urlretrieve,something like this.

import winsound    
try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

def play(sound):
    winsound.PlaySound(sound, winsound.SND_FILENAME)

# Download wave file and save to disk
url = "http://www.villagegeek.com/downloads/webwavs/adios.wav"
filename = url.strip().split('/')[-1]
urlretrieve(url, filename)
print("Sound saved as {}".format(filename))

# Play wave file
play(filename)
snippsat 661 Master Poster

but in any case, I never found out how to set the interpreters...
so debugging was also a pain...

Hmm interactice interpreter has always been in botton part.
http://imageshack.us/a/img197/6707/sbin.jpg

snippsat 661 Master Poster

IMO, VS2010 with PythonTools 1.5 is the best IDE.

Say that you mean that,don't speak for everyone.

PyScripter has alot of glamour, but it doesn't have an interactive interpreter

PyScripter has always had a interactive interpreter.

Spyder is ok,and istall with winpython,to get a lot of tools as addon.

is there anything like VS but with more glamour and conveniency??

Not free but has a lot stuff like VS.
PyCharm a newer big IDE for python.
Supported: Python 2.x or 3.x, Jython, IronPython and PyPy,Django.....

Wingware
KomodoIDE

snippsat 661 Master Poster

I need to do simple things like list the file and folders in a directory 'ls' and change director 'cd'. I found these two pages that looked promesing but I still didn't fine what I was looking for. Any ideas?

Maybe you need to broaden your Python knowledge,because this is basic stuff when working with files and folders in Python.

list the file and folders os.listdir(), glob.glob() or os.walk()
os.walk() will recursively walk a directory,means that it will find all subfolders and files.

change director 'cd' os.chdir(path)
os.getcwd() # Returns the current working directory
os.chdir('/path/to/directory') Change the current working directory to 'path/to/directory'.
Also accepts bash commands like '..' and '/'.

snippsat 661 Master Poster

Can use isinstance.

>>> weight = float(raw_input("enter the weight: "))
enter the weight: 100.0
>>> weight
100.0

>>> type(weight)
<type 'float'>

>>> isinstance(weight, float)
True

>>> isinstance(weight, int)
False

>>> weight = 50
>>> isinstance(weight, float)
False

>>> #If you want both int and float to be True
>>> isinstance(weight, (int,float))
True

>>> a = 'hello'
>>> isinstance(a, (int,float))
False

As info.
In Python type checking is someting we try to avoid.
A couple lines you sure will hear more about if you continue to use Python.

If it looks like a duck, quacks like a duck - it's a duck.
it's Easier to Ask Forgiveness than Ask Permission.

snippsat 661 Master Poster
snippsat 661 Master Poster

Shorter.

>>> strng = '1002-1004,1 1444'
>>> re.findall(r'\W', strng)
['-', ',', ' ']

Or the same without regex.

>>> strng = '1002-1004,1 1444'
>>> [c for c in strng if c in ['-', ',', ' ']]
['-', ',', ' ']
snippsat 661 Master Poster

i have even re installed pywin32 but still

Strange.
Ok here are files.
http://pastelink.me/dl/0b94d2

snippsat 661 Master Poster

ImportError: No module named 'win32com.gen_py'
when i run your cx_run.py script

Hard to say because it works for me.
Some info.
win32com.gen_py is part of Pywin32 package.
Placement on my hdd is C:\Python27\Lib\site-packages\win32com\gen_py
See if you have this placement.

Make sure that Environment Variables is set to python27.
http://www.nextofwindows.com/how-to-addedit-environment-variables-in-windows-7/
To path add ;C:\python27\;C:\python27\scripts

snippsat 661 Master Poster

I have done some tesing and got it to work(windows 7 Ultimate)
First my test code.

#sound_test.py
import pyttsx
import time
from datetime import date
from datetime import datetime

engine = pyttsx.init()

date = date.today()
time_now = datetime.now()
date = date.strftime("%A %d %B")
time_now = time_now.strftime('%H:%M:%S')

engine.say('The date is {} and time is now {}'.format(date, time_now))
time.sleep(1)
engine.runAndWait()

Cx_freeze setup.

#cx_run.py
from cx_Freeze import setup,Executable

includes = ["pyttsx", "pyttsx.drivers.sapi5"]
excludes = []
packages = ['win32com.gen_py']

filename = "sound_test.py"
setup(
    name = 'myapp',
    version = '0.1',
    description = 'test pyttsx',
    author = 'no',
    author_email = 'someting@my.org',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'includes':includes}},
    executables = [Executable(filename, base = "Win32GUI", icon = None)])

The hard part to figure out was pyttsx.drivers.sapi5 and win32com.gen_py
To run it sound_test.py and cx_run.py in same folder(freeze).
From command line(cmd)
C:\freeze>python cx_run.py build

snippsat 661 Master Poster

As posted over itertools izip is ok to use and fast.
Python has also build in zip

>>> zip(names,surnames)
[('Jake', 'Cowton'), ('Ben', 'Fielding'), ('Rob', 'Spenceley Jones')]

---

for first,last in zip(names,surnames):
    print first,last

    Jake Cowton
    Ben Fielding
    Rob Spenceley Jones        
snippsat 661 Master Poster
dir(__builtins__)
#list of what's in the built-in namespace

If you not sure do a simple test.
You get a NameError if python can't find the name.

>>> reload
<built-in function reload>

>>> my_reload
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'my_reload' is not defined

>>> list
<type 'list'>

>>> lst
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'lst' is not defined

So my_reload and lst is ok names to use.
Also pay attention to modules names,so dont name someting random.py
When Python has a module named random.

snippsat 661 Master Poster

As a addition to slate explanation,do a test in interactive interpreter.

The 'is' operator is not another way to type '=='.

In most cases the use of == or != is what you want.
Normal way to use is are to test if something is identical to None like a is None or b is not None.

>>> help(id)
    Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)


>>> name1 = "rahul"
>>> name2 = "rahul"
>>> id(name1)
50933056
>>> id(name2)
50933056
>>> 
>>> name1 = [1,2,3]
>>> name2 = [1,2,3]
>>> id(name1)
52135216
>>> id(name2)
50904000
snippsat 661 Master Poster

hmm you have ask similar question before and got good answers.
So two word in s1.

>>> s1 = "Hello World"
>>> len(s1.split())
2

Some really basic mistake.
What happends if you iterate before you split() like you do?

s1 = "Hello World"
for word in s1:
    print word #?

s1 and s2 this dos dos not mean concatenate s1 with s2.
and or not are logical operators,is in every Python tutorial/book.
and,If both the operands are true then then condition becomes true.

Fix.

def count_word():
    s1 = "Hello World"
    s2 = "Computer Programming for Kids and Other Beginners"
    numCount = 0
    for word in s1.split() + s2.split():
        numCount += 1
    print "Total strings is", numCount

count_word()

Better.

s1 = "Hello World"
s2 = "Computer Programming for Kids and Other Beginners"    
total_words = s1.split() + s2.split()

print len(total_words)    
sort_key = lambda s: (-len(s), s) #in case of equality by the alphabetical order?
print sorted(total_words, key=sort_key)
snippsat 661 Master Poster

I think import can be used to access functions from another .py file but I'm not sure and haven't used it yet

Yes and here dos if __name__ == "__main__": play and important part.
You have made a fantastic name multiplier code,and you whant to import it so you can use it in other code or share it.
Version 1.

#name_multiplier.py
def name_multiplier(*arg):
    return arg * 2

#Tests
print name_multiplier('hello', 'world')
print name_multiplier(1, 9)

Save it as name_multipler.py in PYTHONPATH,just use python27 folder or your version of Python folder.
Now code is an module and you can import it,ohh easy.
Test it out.

>>> import name_multiplier
('hello', 'world', 'hello', 'world')
(1, 9, 1, 9)

Hmm i dont want test code to get run when i import it.
Version 2.

#name_multiplier.py
def name_multiplier(*arg):
    return arg * 2

if __name__ == '__main__':
    #Tests
    print name_multiplier('hello', 'world')
    print name_multiplier(1, 9)

Test it out.

>>> import name_multiplier
>>> #Now it works as it should and dont run test code
>>> name_multiplier.name_multiplier('a', 5)
('a', 5, 'a', 5)

>>> #I want to type name_multiplier 1 time
>>> from name_multiplier import name_multiplier
>>> name_multiplier('.', '_','~')
('.', '_', '~', '.', '_', '~')

So in version 2 it work as a standalone program and also as a module should(not run code when import is used)

snippsat 661 Master Poster

so maybe newFile can be temporary and then it can be used with to reoverwrite the oldFile?

Yes this is normal way,you iterate over contend and do what you need,then save contend in a new file.
If you need newtext to be oldtext you rename the files.
os.rename(oldtext','newtext') or shutil.move('oldtext','newtext')

Python has fileinput that can do inplace edit of orginal file.
It's ok,but the method over with rename is just as good.
If order doesn't matter,soultion by pyTony is good.

'''lines.txt-->
line 1
line 2
line 2
line 3
'''

import fileinput
import sys

def remove_dup(fname):
    text = []
    for line in fileinput.input(fname, inplace=True):
        if line not in text:
            text.append(line)
            sys.stdout.write(line)

fname = 'lines.txt'
remove_dup(fname)

'''lines.txt-->
line 1
line 2
line 3
'''
snippsat 661 Master Poster

A little more about *args and **kwargs

First vehicle take only 'car' as agument.
Next *args take 'hello', 'world' and make it a tuple.
Next **kwargs take key_a='value 1', key_b='value 2' and make it a dictionary.

def func(vehicle, *args, **kwargs):
    #argument vehicle
    print(vehicle) #--> car

    #argument *args
    print(args) #--> ('hello', 'world')
    print(args[1]) #--> world

    #argument **kwargs
    print(kwargs) #--> {'key_b': 'value 2', 'key_a': 'value 1'}
    print(kwargs['key_a']) #--> value 1


func('car', 'hello', 'world', key_a='value 1', key_b='value 2')

*args can take many arguments.

def bar(*args):
    print(sum(args)) #--> 45

bar(1,2,3,4,5,6,7,8,9)

**kwargs can take many arguments.
So here iterate over dictionary and print key --> value.

def foo(**kwargs):
    for key in kwargs:
        print("Values from dict--> {}: {}".format(key, kwargs[key]))

foo(Name='Zara', Age=7, Class='first')

"""Output-->
Values from dict--> Age: 7
Values from dict--> Name: Zara
Values from dict--> Class: first
"""
snippsat 661 Master Poster

Ok i am not sure about your input,so i wirte something that may be what you want.
Remember you have to use close() on fileobject when you write to file or nothing gets written.
Always use close() when open/close like this open('input', 'r')
I use with open(),then is no need to close() fileobject because it's done automatic.

'''
textfileA.txt-->
bar
world

textfileB.txt-->
foo bar hello bar
'''

with open('textfileA.txt') as file_a, open('textfileB.txt') as file_b,\
open('textfileC.txt', 'w') as file_c:
    file_a = [i.strip() for i in file_a]
    file_b = file_b.read().split()
    for index,item in enumerate(file_b):
        for word in file_a:
            if word == item:
                file_b[index] = 'error'
    file_c.write(' '.join(file_b))

'''
textfileC.txt-->
foo error hello error
'''
snippsat 661 Master Poster

textfileB: "word","word","word"

So dos your text file look like this when you read it?

with open("textfileB.txt") as f:
    your_file = f.read()

print your_file

Can you post the output?
The reason why i ask is because it not normal to have quotes in file.
If it's quotes you have to remove them,so you can get word without quotes.

>>> your_file
'"foo","bar","hello"\n'
>>> your_file.split(',')
['"foo"', '"bar"', '"hello"\n']
>>> your_file.split(',')[0]
'"foo"'
>>> print your_file.split(',')[0]
"foo" #You see it's not the word foo, but "foo" 

Remove quotes.

>>> [i.strip().strip('"') for i in your_file.split(',')]
['foo', 'bar', 'hello']
>>> [i.strip().strip('"') for i in your_file.split(',')][0]
'foo'
>>> print [i.strip().strip('"') for i in your_file.split(',')][0]
foo
snippsat 661 Master Poster

How can I read from data.txt?

This is in every tutotial/book out there,so it should not be a problem.
I try to always use with open(),this is the prefered way(with statement has been in Python since 2006)
One short way.

import re
from collections import Counter

with open('your.txt') as f:
    no_punct = re.findall(r'\w+', f.read())
print Counter(no_punct)

remove punctuation marks from text file?

Without regex.

>>> from string import punctuation
>>> s = 'We@.._ love the?# pytho,..,n progr"""ammi@"ng'
>>> text = ''.join(c for c in s if c not in punctuation)
>>> text
'We love the python programming'
snippsat 661 Master Poster

unfortunately, I have to have a lot of the mess in there for what our teacher wants. the focus of the assignment is on global variables(randint) and try/except(error handling)

No you can stucture your code better,i don't think your teacher want you to write as you do in first post.
Here is an example of try/except,as you see i make a function for it.
An game code still look clean an nice.

import random

def user_input():
    '''Function to make sure that integers are used'''
    while True:
        try:
            guess = int(input("Take a guess: "))
            return guess
        except ValueError:
            print('Only numbers as input,try again')

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = user_input()
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))
snippsat 661 Master Poster

but I am rather confused

Yes that's normal when you new to programming.
Some help,you are writing more code than you need for this and it's a little messy.
Forget errohandling(try,except),function this can you do later.
Her is the basic of the game,look at code and see if it make any seense.

import random

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = int(input("Take a guess: "))
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))

You can do error checking,but don't mess code up to much.
Game code you can put in one fuction.

Here is a simple menu function that loop,you will always fall back into this menu.
Here you can start a new game or quit.
Try to type lot of mess,you see that it cacth all error with a simple else block(no try,except)
For other input types like(int,float) you may need(try,except),but dont overuse it.
Traceback in Python are very clear and not dangerous for any user.

def game():
    '''Code for game'''
    Print('You now in game function')
    input('Press enter to return to menu')    

def menu():
    while True:
        print('(1) Play guess game')
        print('(q) Quit')
        choice = input('Enter your choice: ')
        if choice == '1':
            game()
        elif choice.lower() == 'q':
            return False
        else:
            print('Not a correct choice: {} try again'.format(choice))

if __name__ == '__main__':
    menu()

"import randint" out of the function,

snippsat 661 Master Poster

IndexError: list index out of range

>>> l = [1,2]
>>> l[1]
2
>>> l[2]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: list index out of range

A simple print should tell you what is wrong print passWord.

If it split at at :,you will be able to call index 1 as shown in this example.
If not you get a IndexError.

>>> s = 'hello:world\n\r'
>>> s.split(':')
['hello', 'world\n\r']
>>> s.split(':')[1].strip()
'world'
snippsat 661 Master Poster

It returns, 'zip' is not recognized as an internal or external command

zip command works only on linux.
You can get it in windows by install GnuWin32 project,and to PATH in environment variables,
you need to add ;C:\%PROGRAMFILES%\GnuWin32\bin

But you shold really use module zipfile as suggsest by Grib.
zipfile is crossplatform and work on all system.

A fast rewrite of code to something like,with use of zipfile module.

import glob, os, time
import zipfile

source = r'C:\test_1\*'
target_dir = r'C:\test_2/'
target = target_dir + time.strftime('%Y%m%d') + '.zip'

f_zip = zipfile.ZipFile(target, "w")
for name in glob.glob(source):
    f_zip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
f_zip.close()
Gribouillis commented: good help +13
snippsat 661 Master Poster

Use cx_Freeze
You should also set up Environment Variables to point to Python32.
http://www.daniweb.com/software-development/python/threads/359605/python-not-recognized
This mean that you can type python in any path in cmd(windows command line) and Python will start.

'''
my_cx_freeze.py
To run code from cmd
python my_cx_freeze.py build
Eksp from cmd:
C:\Python32\Scripts>python my_cx_freeze.py build
'''
from cx_Freeze import setup,Executable

includes = []
excludes = []
packages = []

filename = "your_code.py"
setup(
    name = 'Myapp',
    version = '0.1',
    description = 'Gui test',
    author = 'no',
    author_email = 'someting@my.org',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'includes':includes}},
    executables = [Executable(filename, base = "Win32GUI", icon = None)])
bdheeraj commented: thanks it worked +0
snippsat 661 Master Poster

I was welcomed with a lot of negative feedback, due to "Hmm PEP-8 falling on my head", thus my next move would be to offering you some exemplified links to help you figure that out. So here it is:

Sorry it's was more about how your code was indented,your help was very good.
So write more stuff like that,and don't take criticism to serisous PEP-8 it's just as suggestion how Python code shold look.
I myself do not follow all in PEP-8,and i have gotten criticism for this before.

snippsat 661 Master Poster

urlopen() take string as argument.
So no need to use input() that return integer,use raw_input().
You should by the way never use input() in python 2.x,use int(raw_input()) for integer return.
input() in python 2.x has some safty issues,this has been fixed in python 3.

String formatting is natural way to do this in python.

>>> width = 640
>>> height = 480
>>> "http://www.placekitten.com/%s/%s" % (width,height)
'http://www.placekitten.com/640/48

New string foramtting,this is the preferred way

>>> width = 640
>>> height = 480
>>> "http://www.placekitten.com/{}/{}".format(width,height)
'http://www.placekitten.com/640/480'
snippsat 661 Master Poster
>>> #Python2.x
>>> key = 5
>>> print "module {0}".format(key)
module 5

>>> #Python 3.x
>>> print("module {0}".format(key))
module 5
snippsat 661 Master Poster

Hmm PEP-8 is gone fall in our head.

def __str__(self): return 'Name: '+self.name+', Salary: '+str(self.salary)+', Description: '+self.desc 

And not to happy with all that +

def __str__(self):
    return 'Name: {} Salary: {}  Description: {}'.format(self.name, self.salary, self.desc)
snippsat 661 Master Poster

You can use itertools permutations for this.
If this is a school task,follow woooee explanation.
And try to figure a way to get permutation without using build in tools like itertools.

Can simplify class to you dont need a method(printNum),class already has that info as you see a take out in obj.word.
And Capital letters is for class name only,work_out_combinations read PEP-8.

import itertools

class getNum:
    def __init__(self):
        self.word = input('Enter a number')

    def work_out_combinations(self):
        '''Return permutation for entred number'''
        return list(itertools.permutations(int(i) for i in self.word))

Test class.

>>> obj = getNum()
>>> obj.word
'123'
>>> obj.work_out_combinations()
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

>>> obj.work_out_combinations.__doc__
'Return permutation for entred number'
>>> help(obj.work_out_combinations)
Help on method workOutCombinations in module __main__:

workOutCombinations(self) method of __main__.getNum instance
    Return permutation for entred number
aVar++ commented: Very helpful & made a working programme, Thanks! +1
snippsat 661 Master Poster

Some more ways,i use numbers.txt as shown by Lucaci.

with open('numbers.txt') as f:
    print [i.strip() for i in f]

#['1', '2', '3', '4', '5', '6', '7', '8']

So we get a list of numbers that are strings.
To get a list with integer or float,use int() or float()

with open('numbers.txt') as f:
    print [float(i) for i in f]

#[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]

Rembere output is always strings when you read from file.
Can test with sum() and output is as expected.

with open('numbers.txt') as f:
    print sum(float(i) for i in f) #36.0
snippsat 661 Master Poster

Test print will show you files to be removed.
If ok remove comment(#) from #os.remove(files)
Remember never use C:\
Use raw string r'C:\' or C:\\ or C:/

import os, glob, time, sys

def file_remove(folder, exp_date, ext):
    '''Remove files older than than set exp_date'''
    for files in glob.glob('{}\*.{}'.format(folder, ext)):
        lastmod_date = time.localtime(os.stat(files)[8])
        ex_date = time.strptime(exp_date, '%d-%m-%Y')
        if  ex_date > lastmod_date:
            try:
                #Test print
                print 'Removing {} {}'.format(files, time.strftime("<Older than %d-%m-%Y>",ex_date))
                #os.remove(files)
            except OSError:
                print 'Could not remove {}'.format(files)

if __name__ == '__main__':
    folder = r'C:\test'
    #Expiration date format DD-MM-YYYY
    exp_date = '07-02-2013'
    #File extension to search for
    ext = 'txt'
    file_remove(folder, exp_date, ext)
snippsat 661 Master Poster

All txt files in blah.

import glob

for files in glob.glob(r'C:\blah\blah\*.txt'):
    print files

Run all files through os.stat
What you need is st_mtime,nr 8.

Now you can use time(import time),make a time object for 14_days back.
Make a time object from os.stat(files)[8]call it lastmod_date.
Compare 14_days > lastmod_date use os.remove(files) on files it give back.