snippsat 661 Master Poster

Look into dictionary.
Example Banana is the key and price is the value.
So if you call key you get price.

Here is a code example you can look.
This code will run in a loop given bye argument number given to function.
And save result to a dictionary,that you can use later.

def question(times=None):
    '''Dok string some info about code'''
    grocery_ditch = {}
    print 'Enter grocery item and price'
    for i in range(times):
        key = raw_input('item %d' % int(i+1))
        value = int(raw_input('price'))
        grocery_ditch[key] = value
    print grocery_ditch  #Or use return to get result out of function

question(3)
snippsat 661 Master Poster

griswolf soultion is ok.
You should not get error whit code i fixed over.

Testrun.

>>> 
enter 1 for sin, 2 for cos, 3 for tan1
Type in angle value: 35
0.573576436351
 
enter 1 for sin, 2 for cos, 3 for tan3
Type in angle value: 45
1.0
>>>
snippsat 661 Master Poster

You can do that in IDLE(python shell),you most du that in cmd(windows) or terminal(linux)
If you shall run code in IDLE you have to import it.

Or when in IDLE file->new window(write code) or open code(..py)
Save and run it with F5.
Or as most off do use and editor when running code pyscripter is good for windows or SPE(for linux)

Example.

#save as hello.py,just save it in python27 folder
def foo(your_name=None):
    return 'Hello world from %s' % your_name

my_name = 'Mical'
print foo(my_name)

Run it from cmd
C:\python27>python hello.py
Hello world from Mical

You can import hello.py py in IDLE and use it as an module.

>>> import hello
Hello world from Mical
>>> dir(hello)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo', 'my_name']

>>> hello.foo
<function foo at 0x02A950F0>  #Just show an memory adress
>>> hello.foo()               #Use it with no argument
'Hello world from None'
>>> my_name = 'Tom'
>>> hello.foo(my_name)        #Give it and argument
'Hello world from Tom'
>>>
snippsat 661 Master Poster

1. I need to convert string to integer

>>> a = '5'
>>> type(a)
<type 'str'>
>>> a
'5'
>>> b = int(a)
>>> type(b)
<type 'int'>
>>> b
5

>>> a = raw_input()
5
>>> type(a)
<type 'str'>
>>> a = int(raw_input())
5
>>> type(a)
<type 'int'>
>>>

I was planning on doing sin instead of 1, cos instead of 2, etc. Possible?

a = raw_input("Enter sin,cos for calulate ")
if a == 'sin':
    #do something
    #and you should have a else statement
else:
    print 'Input not correct'

3. Why does the print lines result in a syntax error?

Do you use python 2.7(advisable)
If python 3.x print has become a function so use print (tan)

snippsat 661 Master Poster
from __future__ import division
from math import sin
from math import cos
from math import tan
from math import radians
a = raw_input("enter 1 for sin, 2 for cos, 3 for tan")
if a == '1':  #most be string when compare(raw_input return string)
    degree1 = int(raw_input("Type in angle value: "))  #missing )
    radian_1 = radians(degree1)  #degree1
    sin = sin(radian_1)
    print sin
elif a == '2':
    degree2 = int(raw_input("Type in angle value: "))  #missing )
    radian_2 = radians(degree2)
    cos = cos(radian_2)
    print cos
elif a == '3':
    degree3 = int(raw_input("Type in angle value: "))  #missing )
    radian_3 = radians(degree3)
    tan = tan(radian_3)
    print tan
snippsat 661 Master Poster

Byte of python has also a python 3.x.
The best advice is to stay with 2.7 for now,and later switch to python 3.
Most pepole stay with python 2.x,because off many famous 3.party moduls has to be rewritten.
There are many books tutorials that are really good for beginner and the are most in python 2.x.
Dont worry when you learn python 2.x you also learn python 3.x
That you will understad later,and python 3.x is the future(but not quite yet)

snippsat 661 Master Poster
>>> 1.0 - 2.718281828**(-(23.0**2)/730)
0.5155095380022271
>>> #Or import division from future
>>> from __future__ import division
>>> 1.0 - 2.718281828**(-(23**2)/730)
0.5155095380022271
>>>

http://www.ferg.org/projects/python_gotchas.html

snippsat 661 Master Poster

What is the general usage area of python? Maybe I can change my question.

Python are useful in many areas,read pytohn quotes
Whatever you want to do python has some excellent soltions in moste areas.

snippsat 661 Master Poster

is there fucntion like goto on C++

No,and i hope we never see goto it in python.
http://xkcd.com/292/

Edsger W.Dijkstra wrote this in 1968.
A Case against the GO TO Statement

snippsat 661 Master Poster

if the ID always is a number without -
If not change the regex.

import re

text = '''\
xxxxx(xxxxx);xxx=xxxx,ID=1234-xxxxxxx
(ID=4321),xxxxxxx/xxxxxxx-xxxxxxxxxxx
(ID=3802))(xxxxxx=(xxxxxx=xxx)(xxxxx=xxxxxxx)(ID=3802)))
'''

out_match = re.findall(r'ID=\d+', text)
print out_match
#-->['ID=1234', 'ID=4321', 'ID=3802', 'ID=3802']
snippsat 661 Master Poster

self has an important role in a class,it like a transporter off data in a class.
You use self.discountinput in onAction() method.
Then off course it will not find anything if you not using self on what it`s looking for.
Here is a fix so wx.TextCtrl return data in to method onAction()

import wx

class CashTransaction(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, title = "Cash Transaction",
                                                  size = (450, 470))

            mainpanel = wx.Panel(self)

            font = wx.Font(20, wx.SWISS, wx.NORMAL, wx.NORMAL, False, "Mangal")
            title = wx.StaticText(mainpanel, label = "Cash Transaction", style = wx.ALIGN_CENTRE)
            title.SetFont(font)

            titleholder = wx.BoxSizer()
            titleholder.Add(title, 1 , wx.EXPAND)
            mainpanel.SetSizer(titleholder)

            calcpanel = wx.Panel(self)


            self.btn_list = [
                
            "7", "8", "9",
            "4", "5", "6",
            "1", "2", "3",
            "0", ".", "BackSpace"
                            ]

            gsizer = wx.GridSizer(4, 3, 0, 0)

            self.btn = range(len(self.btn_list))
            for ix, b_label in enumerate(self.btn_list):
            
                id = 10 + ix
                self.btn[ix] = wx.Button(calcpanel, id, label=b_label, size=(-1, -1))
                
                gsizer.Add(self.btn[ix], 0, wx.ALL|wx.EXPAND)
                calcpanel.SetSizer(gsizer)


            infoandinputpanel = wx.Panel(self, style = wx.SUNKEN_BORDER)


            totalamount = 0.00


            font2 = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False, "Mangal")

            totallabel = wx.StaticText(infoandinputpanel,
                            label = "Transaction Total\n""%s" %(totalamount))
            totallabel.SetFont(font2)

            discountlabel = wx.StaticText(infoandinputpanel, label = "Discount\n")
            discountlabel.SetFont(font2)
            
            
            self.discountinput = wx.TextCtrl(infoandinputpanel)  #**
            self.discountinput.Bind(wx.EVT_TEXT_ENTER, self.onAction) #**


            discspacer1 = wx.BoxSizer()
            discspacer2 = wx.BoxSizer()

            discsizer = wx.BoxSizer(wx.VERTICAL)
            discsizer.Add(discountlabel, 1)
            discsizer.Add(discspacer1, 1)
            discsizer.Add(self.discountinput, 1)  #**
            discsizer.Add(discspacer2, 1)

            paidlabel = wx.StaticText(infoandinputpanel,
                                      label = "Amount Recieved")
            paidlabel.SetFont(font2)
            
            paidinput = wx.TextCtrl(infoandinputpanel)          
            paidspacer1 = wx.BoxSizer()
            paidspacer2 = wx.BoxSizer()

            paidsizer = wx.BoxSizer(wx.VERTICAL)
            paidsizer.Add(paidlabel, 1)
            paidsizer.Add(paidspacer1, 1)
            paidsizer.Add(paidinput, 1)
            paidsizer.Add(paidspacer2, 1)

            changefigure = 1.29

            changelabel = wx.StaticText(infoandinputpanel, label = ("Change to give\n""%s" % (changefigure))) …
snippsat 661 Master Poster

Something like this.

def foo(num):
    ''' Return an exponential notation'''
    return '%e' % num

print foo(3000000000000000000000000)
#-->3.000000e+24
snippsat 661 Master Poster

Use Gui2exe
I talk a little of what tool i use her.
http://www.daniweb.com/forums/thread303665.html

snippsat 661 Master Poster

redyugi now you have 2 "int(raw_input" lines that do the same.

To simplify it.
The first function we dont give an argument,just retun value out.
Remember run this code as a script and not in python shell(IDLE)

def get_celsius():
    celsius = int(raw_input("Type in the Celsius temperature:" ))
    return celsius

def main(get_celsius):
    celsius = get_celsius()
    farenheit=(9.0/5.0)*celsius+32
    print "It is %s degrees outside.", farenheit

main(get_celsius)
snippsat 661 Master Poster

If you change Bent Slayer code,to this.
It will give you a list.

initial_date = '9/14/1990'
initial_month, initial_day, initial_year = initial_date.split('/')
final_date = '9/17/1990'
final_month, final_day, final_year = final_date.split('/')

f_in = open('test.csv').readlines()
#f_out = open('filtered_stations_temp.csv', 'w')

my_list = []
for i in range(1, len(f_in)):
    station, date, max_temp, min_temp = f_in[i].split(',')
    month, day, year = date.split('/')
    if initial_month <= month <= final_month and \
    initial_day <= day <= final_day and \
    initial_year <= year <= final_year:
        my_list.append(f_in[i].strip())

#f_out.close()
print my_list

Another way.

start_date = '9/14/1990'
end_date = '9/18/1990'

flag = 1
my_list = []
linelist = open('test.csv')
for line in linelist:
    if start_date in line: # or line.startswith('STATION') ## to get first line
        flag = 0
    if end_date in line:
        flag = 1
    if not flag and not end_date in line:
       #print line,
       my_list.append(line.strip())

print my_list
snippsat 661 Master Poster

indentations 4 space,is important in python.
If you have a good python editor it will auto indent.

import wx

class bucky(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Frame aka window', size=(400,300))
        panel=wx.Panel(self)

        status=self.CreateStatusBar()
        menubar=wx.MenuBar()
        first=wx.Menu()
        second=wx.Menu()
        first.Append(wx.NewId(),"new window")
        first.Append(wx.NewId(),"Open...")
        menubar.Append(first,"File")
        menubar.Append(second,"edit")
        self.SetMenuBar(menubar)

if __name__=='__main__':
    app=wx.PySimpleApp()
    Frame=bucky(parent=None, id=-1)
    Frame.Show()
    app.MainLoop()
vegaseat commented: excellent observation +12
snippsat 661 Master Poster

Does Python offer any way of extracting just the data between my two dates??

Yes more than one way depends how data are organized.

post an short example off that cvs file.
Mark where 'initialDay' and 'finalDay' are.

snippsat 661 Master Poster

It`s about same size,i guess you are talking about packed so it can run as an standalone application.
PyQt is 3-4 mb larger for standalone application.

I have got size down on wxpython quite a lot.
Gui2exe(compressed: 2, optimize: 2 bundle_files: 3)
Delete unnecessary files,so run UPX
Last run Inno setup
For my translate program py-trans(using api off google translate)
Size of setup.exe(one file for windows install) was 3.8mb.
Unpack litte over 5mb.

This is better than uncompressed/unoptimize wxpython that can be 15-20 mb large.

snippsat 661 Master Poster
def foo():
    from random import *
    print randrange(5,8)

foo()
#--><module1>:1: SyntaxWarning: import * only allowed at module level
5

from random import randrange
def foo():
    from random import *
    print randrange(5,8)

foo()
#-->6

Is there anyway from looking at my code that I can determine which items I need to import from pyExcelerator?

Use dir(pyExcelerator)

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random.shuffle)
Help on method shuffle in module random:

shuffle(self, x, random=None, int=<type 'int'>) method of random.Random instance
    x, random=random.random -> shuffle list x in place; return None.
    
    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.

>>>
snippsat 661 Master Poster

from pyExcelerator import *

Import shall always be on the top,not inside a function.
That`s why you get this warning.
SyntaxWarning: import * only allowed at module level

DON'T do this:
from pyExcelerator import *
unless you are absolutely sure that you will use each and every thing in that module.
And even then, you should probably reconsider using a different approach.

Better.
from pyExcelerator import <something>
Then use it like this: something()

import pyExcelerator as Ex
Then use it like this: Ex.something()

import pyExcelerator
Then use it like this: pyExcelerator.something()

Example:

#dir(random) #show functions/methods in random
>>> from random import randrange
>>> randrange(1,10)
3
>>> import random as R
>>> R.randrange(5,14)
12
>>> import random
>>> random.randrange(2,8)
6
snippsat 661 Master Poster

A little more on importing.
First the code.

#make_name.py
#saved in python26 folder
def makeName():
    name = raw_input("Please enter your name")
    return name

So how to use it.

>>> import make_name
>>> dir(make_name)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'makeName']
>>> #We look at spesial methods 2 underscore and makName function
>>> make_name.__file__
'C:\\Python26\\make_name.py'
>>> make_name.__name__
'make_name'
>>> make_name.__doc__
>>> #We have not made a doc string in this function
 
>>> make_name.makeName
<function makeName at 0x01DCFCB0>
>>> #We se function makeName and a memory location
>>> make_name.makeName()
Please enter your nameTom
'Tom'
>>> #Call the function,remember we dont need a print statement when we do this in IDLE.

>>> from make_name import makeName
>>> makeName()
#Now i have put make_name in global namespace and can call only function name
snippsat 661 Master Poster

Like this,i have put function call in variable name and age.

def main():    
    name = makename()
    age = makeage()    
    print "You are" ,age ,"years old", name
def makename():
    name = raw_input("Please enter your name ")
    return name
def makeage():
    year = input("What is the year current year? ")
    byear = input("What year were you born in? ")
    age = year - byear
    return age
main()
snippsat 661 Master Poster
'''-->my_file.txt
x
a
b
'''

text_label = [f.strip() for f in open('my_file.txt')][0]
self.button = wx.Button(panel, label = '%s' % text_label)

Take x from my_file.txt and place it as label text for button.

snippsat 661 Master Poster

Using global is not a good soultion at all,learn to give argument at return value out functions.
A simple example.

def newUser():    
    Username = raw_input('Choose a username? ')
    return Username


def reg_user(newUser):
    '''Make 3 users an save to a list'''
    l = []
    for i in range(3):
        l.append(newUser())        
    return l   
    
if __name__ == '__main__':     
    print reg_user(newUser)

'''-->Out
Choose a username? Tom
Choose a username? Paul
Choose a username? Hans
['Tom', 'Paul', 'Hans']
'''
snippsat 661 Master Poster

Think about your design.
One textbox user enter 3 number.
Then operator / and then user enter new number and you get and average.
Like a normal calculator.

What if user want average of 5 number,should you create 5 textboks?

snippsat 661 Master Poster
>>> import texttable
>>> dir(texttable)
['ArraySizeError',
 'Texttable',
 '__all__',
 '__author__',
 '__builtins__',
 '__credits__',
 '__doc__',
 '__file__',
 '__license__',
 '__name__',
 '__package__',
 '__revision__',
 '__version__',
 'len',
 'string',
 'sys',
 'textwrap']


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


table = texttable.Texttable()  #ok
#We change import line
from texttable import Texttable

table = Texttable()
table.set_cols_align(["l", "r", "c"])
table.set_cols_valign(["t", "m", "b"])
table.add_rows([ ["Name", "Age", "Nickname"], ["Mr\nXavier\nHuon", 32, "Xav'"], ["Mr\nBaptiste\nClement", 1, "Baby"] ])
print table.draw()

'''-->Out
+----------+-----+----------+
|   Name   | Age | Nickname |
+==========+=====+==========+
| Mr       |     |          |
| Xavier   |  32 |          |
| Huon     |     |   Xav'   |
+----------+-----+----------+
| Mr       |     |          |
| Baptiste |   1 |          |
| Clement  |     |   Baby   |
+----------+-----+----------+
'''
snippsat 661 Master Poster
import time

def foo():
    for i in range(100000):
        i

def time_code(arg):    
    start = time.clock()
    arg()
    end = time.clock()
    print 'Code time %.3f seconds' % (end - start)

if __name__ == '__main__':
    time_code(foo)

Most off the time code is to fast to measure only with one run,that`s why man use timeit modulen for measurement of code time.
From command line or script.

C:\>python -m timeit "for i in xrange(100): pass"
1000000 loops, best of 3: 1.77 usec per loop

#Are tuple faster than list?
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

Something like this,look into findall off re module.
Dont use str as variable,it`s a builtin key word.

>>> str
<type 'str'>
>>> help(str)
Help on class str in module __builtin__:
>>> import re
>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.
    
    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.
    
    Empty matches are included in the result.
import re

text = '''\
Subs cars are test driving in space,and many pigs are flying.
'''

test_match = re.findall(r'\w+[s]\b', text)
print test_match
#->['Subs', 'cars', 'pigs']
snippsat 661 Master Poster

Yes,forgot sorted by lenght was thinking alphabetically sort.
Thanks tony.

snippsat 661 Master Poster
def wordPop(text, n):
    nwords = []
    words = text.split()
    for word in words:
        if (len(word) >= n):
             nwords.append(word)
    return sorted(nwords)

w = 'This is a test off word lenght'
print wordPop(w.lower(), 4)
#->['lenght', 'test', 'this', 'word']

So i removed you length_compare function.
sorted(nwords,cmp=length_compare)
So this get wrong,first off cmp is a python key word.
And your "length_compare" function is not comparing anything.

>>> cmp
<function length_compare at 0x0265EF30>
>>> help(cmp)
Help on function cmp=length_compare in module __main__:

length_compare(x, y)
def length_compare(x, y):
    return len(x) - len(y)

x = 'hi'
x = 'test'
print length_compare(x, y)  #->2
#If you call function you have to use 2 argument
#And it`s not comparing anything,just extract test(4) from hi(2)
snippsat 661 Master Poster

Always specify the exceptions to catch.
Never use bare except clauses.
Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.

Let you code run if you catch new exception,you can put them in except(all my catch)

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except (ZeroDivisionError, TypeError, ValueError):
    print 'Your numbers were bogus...'

Or you can split it upp.

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except ZeroDivisionError:
    print "The second number can't be zero!"
except ValueError:
    print "That wasn't a number, was it?"
snippsat 661 Master Poster
snippsat 661 Master Poster

>>>E:\1py\freeze>python my_cx_freeze.py build

You are running from IDLE python shell,that`s not command line.
Dont you understand what command line is?

Windows you push start->run(write cmd)
Then command shell start.
Then you navigate using cd to the dir where you have your py-files.

snippsat 661 Master Poster

I am using command line and I tried using the line of code you gave me and it gives me syntax error: invalid syntax

Then you are doing something wrong,what we dont know because you dont post any code.
We are not mindreaders.

snippsat 661 Master Poster

do I have to save it in a certain spot because It's just keeps telling me invalid syntax

Have you look at my post it should be clear?

You have to run it from command line.
Start->run->cmd

cxfreeze hello.py --target-dir dist
do I have to save it in a certain spot because It's just keeps telling me invalid syntax

This is more a pseudo explations,and will off course give you and syntak error if you dont change it.

E:\1py\freeze>python my_cx_freeze.py build #This is the line that start build process
(Your path)python my_cx_freeze.py build    #Change to wish dir you like

This run the my_cx_freeze.py that has a link to the program i want to make exe of.
Wish is in my case was date.py

snippsat 661 Master Poster

Testet this out with python 2.65
This should work for python 3.xx to.
Made a dir E:\1py\frezze
In that dir i have 2 files.

#cx_freeze test save in dir E:\1py\freeze
#date.py
import time

date_old = "05.26.1999"

#Use strptime(time_str, format_str) to form a time tuple
time_tuple = time.strptime(date_old, "%m.%d.%Y")

#Use time.strftime(format_str, time_tuple) to create new format
date_new = time.strftime("%b-%d", time_tuple)

print(date_old)  # 14-05-1999
print(date_new)  # May-14
raw_input('press enter to exit!')
#Cx_freeze test save in dir E:\1py\freeze
#my_cx_freeze.py
"""
con_setup.exe

Using cx_freeze with Python31 to package a console
program to an executable file (.exe in Windows OS).

Might want to put a console-wait-line in at the end of your program.

Put this setup program and your console program file into the same 
directory.  Change the filename in this setup program and also edit 
name, version and description in setup() if you so desire.

Run the build process by running the command: 
python con_setup.py build

A directory 'build' is created with a subdirectory 'exe.win32-3.1'
containing all the files needed for distribution including the 
.exe file named after the console program file.

The total distribution has a size of about 4.2 Mb.
"""

from cx_Freeze import setup, Executable

# change the filename to your program file
filename = "date.py"

setup(
    name = "date",
    version = "1.0",
    description = "console cx_Freeze script",
    executables = [Executable(filename)])

So then i have 2 files in E:\1py\freeze(date.py and my_cx_freeze.py)

#From cmd
c:\e:
E:\cd 1py
E:\1py\cd freeze
E:\1py\freeze>python my_cx_freeze.py build …
snippsat 661 Master Poster

As ultimatebuster explain return get you out of a function and break get you out off a while loop.
An example.

def find_father():
    pass

def main():
    '''Main menu and info ''' 
    while True:               
        print 'Father finder'
        print '(1) 1 - Find a Father'        
        print '(Q) Quit' 
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            find_father()       
        elif choice.lower() == 'q': 
            return #Get out of while loop
        else: 
            print 'Not a correct choice:', choice 

if __name__ == '__main__':
    main()

I we take out while loop out off the function,we use break.

while True:               
    print 'Father finder'
    print '(1) 1 - Find a Father'        
    print '(Q) Quit' 
    choice = raw_input('Enter your choice: ') 
    if choice == '1':
        print 'Find father'      
    elif choice.lower() == 'q': 
        break #Get out off the while loop
    else: 
        print 'Not a correct choice:', choice
snippsat 661 Master Poster

Keep aspect ratio of the image.

from PIL import Image

def resize(img,percent):
    ''' Resize image input image and percent | Keep aspect ratio'''
    w,h = img.size
    return img.resize(((percent*w)/100,(percent*h)/100))

if __name__ == '__main__':
    img = Image.open('s.jpg')
    #Give argumet to function image and percent
    resized_image = resize(img, 80)
    resized_image_file = 's_new.jpg'
    resized_image.save(resized_image_file)
    print("%s saved!" % resized_image_file)
snippsat 661 Master Poster

For this i think a dictionary approach is most natural.
@Beat_Slayer test your code.

Edit:

lets suppose, South Africa.

South Africa work fine in mine code.
A7 is South Africa

countries = [i.strip() for i in open('countries.txt')]
#Bad variables list
var_list = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']

countries_Dict = dict(zip(var_list, countries))
print (countries_Dict)

#Iterate over Dict
for k,v in countries_Dict.items():
    print ('%s is %s' % (k, v))

'''Out-->
{'A1': 'england', 'A3': 'spain', 'A2': 'america', 'A5': 'germany', 'A4': 'brazil', 
A1 is england
A3 is spain
A2 is america
A5 is germany
A4 is brazil
A6 is australia
'''
snippsat 661 Master Poster
>>> x = 'car'
>>> x.close()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'

As tony mention str has no close() method as a file object.

cStringIO module has close(),or maybe you are trying to use close on what you think is a file object.
You can check type like this.

>>> x = 'car'
>>> type(x)
<type 'str'>
>>>
#cStringIO demo
>>> from cStringIO import StringIO
>>> output = StringIO()
>>> output.write('This goes into the buffer.\n')
>>> output.write('car')
>>> print output.getvalue()
This goes into the buffer.
car
>>> output.close() # discard buffer memory
snippsat 661 Master Poster

I pretty much give you the answer.
"05/26/1999" should be covert to May-26,look at my first code.
Then rebuild your function with that code.
Get the function to work first then you can think of exception handling.

I see an other approach by tony using datetime module,that also work fine.
Tony can also use this format 01.12.2020.

For that to work we have to change like this in my code.

>>> date_old = '05.26.1999'
>>> time_tuple = time.strptime(date_old, "%m.%d.%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>

Or write something better that can handle both or more format.

snippsat 661 Master Poster

This should help you.

>>> import time
>>> date_old = '05/26/1999'
>>> time_tuple = time.strptime(date_old, "%m/%d/%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>
try:
    # use strptime(time_str, format_str) to form a time tuple
    time_tuple = time.strptime(date_old, fmt)
except: #Dont use bare except try to catch specific error that are comming
        #Example except ValueError or something else.
    pass
snippsat 661 Master Poster

Tony rpartition soultion timeit 1000000 loops average 5.92587408782
Vega data.split()[-1] soultion 1000000 loops average 5.90504511194

Not so much differnce but vega solution is a little faster,and simpler to read and understand.
That count as a plus.

snippsat 661 Master Poster

Try this and it should work.

import shutil

shutil.copy('c:\\test\my_file.txt', 'c:\\temp')

You most copy files with shutil.copy.

This will give you and Permission denied.
You can not copy folder to folder with shutil.copy.

import shutil

shutil.copy('c:\\test', 'c:\\temp')

Use copytree.

import shutil

shutil.copytree('c:\\test', 'c:\\new')

This will copy from c:\test and make a new folder c:\new.
It will give and error if c:\new excited

Look also at this for coping folders.
http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree

import os
import distutils.dir_util

distutils.dir_util.copy_tree('c:/test', 'c:/testbak')

Alwas use \\ or /

c:\test  #No \ can be looked at as an escape character
c:\\test #Ok
c:/test  #Ok
snippsat 661 Master Poster

Why is it a bug, then?

Everyone can report what the think is a bug,that dos not mean is a real bug.
This bug report was closed,and was not a bug.
Just something that easy can be misunderstood -1 need to be (-1) to work correct.

snippsat 661 Master Poster

It has been reportet as a bug,and closed with this answer.

This is because the negative sign is evaluated after the power. (-1)**2
works correctly.

http://bugs.python.org/issue4224

snippsat 661 Master Poster

But the point of this thread not exception handling, but short circuit break from middle of list comprehension when solution is found. Exception is just mechanism that we must use if we do not use generator.

Yes i know,and for me the correct anwer is to say that exception cannot be used inside a list comprehension.

snippsat 661 Master Poster

That`s not exceptions handling in list comprehension,i think Alex Martelli answer is the correct answer to exception handling in list comprehension.

so it's impossible, literally speaking, to "handle exceptions in a list comprehension"

snippsat 661 Master Poster

Exception handling in list comprehension is difficult/impossible.
Here is Alex Martelli answer to the question.

There is no built-in expression in Python that lets you ignore an exception (or return alternate values &c in case of exceptions), so it's impossible, literally speaking, to "handle exceptions in a list comprehension"

http://stackoverflow.com/questions/1528237/how-can-i-handle-exceptions-in-a-list-comprehension-in-python

snippsat 661 Master Poster

This expression does not raise the zero division error, so it is not timing the same thing.

Yes i know that,the timing was to shown speed off list comprehension vs ordinary loop.