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

I have used 3dmax for very many years,but i have not check if there any python libraries/api for python(mayby i should do that for i am big fan of both 3dmax and python)
3dmax has it`s one language called maxscript.
Here are some stuff that i have made in 3dmax.
http://snippsat.cgsociety.org/gallery/

You has off course blender as you mention,where python is the main language for blender api.

snippsat 661 Master Poster

Start to read where you post,this is the python part of Daniweb.
Post in VB forum.

Trying hard since 1 week... Cn u plz provide me a code for d same ??? I got submissions in few days... Pllzzz.... Thanx !!

And nowone post finsih code,if you dont show some effort yourself.

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.

snippsat 661 Master Poster

One soultion with regular expression,not hard to wirte regex for this just a couple of min.

import re

text = '''\
"Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera"
1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d
1801,2008308_017_080.tif,531793.060,5005709.230,2033.170000,0.385000,-0.044790,-0.057690,80,2008308,17,308_17,rightX,Jen73900229d
1802,2008308_017_081.tif,532930.810,5005709.150,2032.250000,0.350180,-0.044950,0.271100,81,2008308,17,308_17,rightX,Jen73900229d
1803,2008308_017_082.tif,534066.230,5005706.620,2037.630000,0.345480,-0.036860,0.234700,82,2008308,17,308_17,rightX,Jen73900229d
1804,2008308_017_083.tif,535212.280,5005706.990,2037.470000,0.336650,-0.045540,0.306690,83,2008308,17,308_17,rightX,Jen73900229d
'''

test_match = re.findall(r'\d{7}\_\d{3}\_\d{3}\.\btif\b',text)
print test_match #Give us a list

#Looping over item in list
for item in test_match:
    print item

'''-->Out
['2008308_017_079.tif', '2008308_017_080.tif', '2008308_017_081.tif', '2008308_017_082.tif', '2008308_017_083.tif']
2008308_017_079.tif
2008308_017_080.tif
2008308_017_081.tif
2008308_017_082.tif
2008308_017_083.tif
'''
snippsat 661 Master Poster

In order for my code to be efficient, loops need to be terminated prematurely to prevent unnecessary iterations

Yes list comprehension are faster than ordinary loop,but dont do to much Premature optimization.

One of the frequently repeated mantras I hear from Python veterans is, "Premature optimization is the root of all evil"

So first write your code in a readable and clear way,before doing to much optimization.
If exception handling with list comprehension is to difficult then dont do it.

Learn to test your code,dont relay on that some code is faster than other code.
More on this later.

To your code.

try:
    print [x if x < 3 else 1/0 for x in range(5)]
except: #Dont ever do this
    pass
#Now this code should break and user dont know anything, no message is coming

#Test in IDLE
>>> print [x if x < 3 else 1/0 for x in range(5)]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 

try:
    print [x if x < 3 else 1/0 for x in range(5)]
except ZeroDivisionError:
    #Always give message to user
    print 'And ZeroDivisionError has happend'

'''-->ZeroDivisionError has happend'''

So write it without list comprehension.

try:
    l= []
    for x in range(5):
        if x < 3:
            l.append(x)
        else:
            1/0
except ZeroDivisionError:
    #Always give message to user
    print 'ZeroDivisionError has happend'
print l
'''-->ZeroDivisionError has happend
[0, 1, 2]
'''

So we test the code …

snippsat 661 Master Poster

Just one small thing is that it is quite rare for the filename to end with with both .txt and .jpg, so I would fix logic little:

See the 2 previos post i just copy that list,and i think most understand it`s just used as an example.

does it. .tar.gz file is however gz file, not tar file

This will check for gz file.

aFile = 'file.tar.gz'
for ext in ['.rar', '.gz', '.zip']:
    if aFile.lower().endswith(ext):
        print 'Do something'

There are many way do this,i think this is quit readable.
"Readability counts" as taken out from the zen of python.
http://www.python.org/dev/peps/pep-0020/

snippsat 661 Master Poster

Yes a good link,i did read it that link some years ago.

Here is a follow up about getters/setters that java programmers can struggle with when they try python.
http://tomayko.com/writings/getters-setters-fuxors

Python java comparison.
http://pythonconquerstheuniverse.wordpress.com/category/java-and-python/

snippsat 661 Master Poster

Here is an alternative with "endswith" thats works fine for this.

aFile = 'test.jpg'
for ext in ['.txt', '.jpg', '.zip']:
    if aFile.lower().endswith(ext):
        print 'Do something'
snippsat 661 Master Poster

Xp i get the same as tony.
Win-7 the same.
Ubuntu it work,diden`t test it to much.
Virtualbox it`s easy to switch between more OS for testing.

I would not use a gui-toolkit for something large.
Because i think i have more control(eaiser to test) building from botton,but if you are comfortable with wx-glade then i guess it`s ok for you.

snippsat 661 Master Poster

There are some ting to think about when doing measurement to get it correct.
Look at post from Alex Martelli and se how he dos it.
As most python fans now,he knows what he is talking about.
http://stackoverflow.com/questions/3054604/iterate-over-the-lines-of-a-string/3054831#3054831

snippsat 661 Master Poster

Another way you can look at.

text = 'ARARAKHTLROGKFMBLFKKGOHMFDGRKLRNGROGINFBLMNFBAEKJGFGOQEITHRGLFDKBN'
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

textletters = list(text)
abcletters = list(abc)

my_list = []
for letter in abcletters:
      letter = textletters.count(letter)
      my_list.append(letter)

#Now we have a list,but not easy to understand
print my_list

'''zip demo-->
>>> l = ['a','b','c']
>>> n = [1,2,3]
>>> zip(l,n)
[('a', 1), ('b', 2), ('c', 3)]
'''

#We can use zip in a for loop to par it up
for item, letters in zip(my_list, abcletters):
    print item,letters

'''Out-->
[4, 4, 0, 2, 2, 7, 8, 3, 2, 1, 7, 5, 3, 4, 4, 0, 1, 7, 0, 2, 0, 0, 0, 0, 0, 0]
4 A
4 B
0 C
2 D
2 E
7 F
8 G
3 H
2 I
1 J
7 K
5 L
3 M
4 N
4 O
0 P
1 Q
7 R
0 S
2 T
0 U
0 V
0 W
0 X
0 Y
0 Z
'''
snippsat 661 Master Poster

Now it will match any text,so if your file start with asms or psms
It will do the same as my pervious post.

If there are are gap more than 1 space you mean as postet by vega,specify this better.

import re

#Open file for write
fout1 = open('join.txt', 'w')

for item in open('my_file.txt'):
    test_match = re.findall(r'.',item,re.IGNORECASE)   
    if item.startswith(str(test_match)) or '\n':
        a = item.replace(' ', '')
        fout1.writelines(a)
fout1.close()
snippsat 661 Master Poster

Here i use startswith('s') to get it to work on first line.
Then or to ger it to replace whitspace in everey new line \n.

This is an efficient way because you dont read hole file into memory,it work line by line.
Off course on small file this dosent matter to much.

#Open file for write
fout1 = open('join.txt', 'w')

for item in open('my_file.txt'):
    if item.startswith('s') or '\n':
        a = item.replace(' ', '')
        fout1.writelines(a)
fout1.close()

'''
join.txt
ssmssmsmsms
sksksskkksppppplkl
ndndndndkdkdkdkdkppp
'''
snippsat 661 Master Poster

inputChoice = input("Choose an option: ") #Do not need int() as input defaults to int

tbone2sk this code is for python 3.x,so he need int(input()).
Garrett85 make a note that you use python 3.x,most pepole use python 2.x so there is no confusion.

Last but not least, what is prices[choice -1] & items[choice - 1]?

>>> prices = [1.50, 2.0, 1.80, 1.20]
>>> prices[1]
2.0
>>> choice = 2
>>> prices[choice]
1.8
>>> #To get the second element -1(count not from 0 as almost all programming language)
>>> prices[choice -1]
2.0
>>>
snippsat 661 Master Poster

python shell
File->new window
Write or paste in your code
To make it run-->run(F5)

Get a good editor is smart like pyscripter.
http://code.google.com/p/pyscripter/
Here you can run all code bye push the run button.

snippsat 661 Master Poster

You dont need a new except for every excption you whant to catch.
Could look something like this.

try:   
    file = t1.get()
    py_compile.compile(file)
except (IOError,UnicodeDecodeError,SyntaxError):
    #Give message
else:
    print "That went well!"
finally:
    print "Cleaning up."
snippsat 661 Master Poster

Python 3.x version after run through 2to3 module.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print('*'*35)    

#Sort by key
key_sort = sorted(list(my_Dict.items()), key=lambda v_k: (v_k[0],v_k[1]))
for info, stat in key_sort:
    print('%-10s  %10s' % (info, stat))
    
print('*'*35)

#Sort by value
value_sort = sorted(list(my_Dict.items()), key=lambda k_v: (k_v[1],k_v[0]))
for info, stat in value_sort:
    print('%-10s  %10s' % (info, stat))
snippsat 661 Master Poster

It`s better if you can use a for loop for key:value in a dicitionary.
Than just 6 print statement.

Here some code you can look at,with som sorted output that i see you asked about in an other post.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print '*'*35    

#Sort by key
key_sort = sorted(my_Dict.items(), key=lambda (v,k): (v,k))
for info, stat in key_sort:
    print '%-10s  %10s' % (info, stat)
    
print '*'*35

#Sort by value
value_sort = sorted(my_Dict.items(), key=lambda (k,v): (v,k))
for info, stat in value_sort:
    print '%-10s  %10s' % (info, stat)


##Out
{'age': '21',
 'average': '8.32',
 'board': 'Fish',
 'country': 'USA',
 'id': '101',
 'name': "johnny 'wave-boy' Jones"}
***********************************
age                 21
average           8.32
board             Fish
country            USA
id                 101
name        johnny 'wave-boy' Jones
***********************************
id                 101
age                 21
average           8.32
board             Fish
country            USA
name        johnny 'wave-boy' Jones
snippsat 661 Master Poster

input() is the same as eval(raw_input())

try replacing input with raw_input()

raw_input return a string.
So my version for python 2.6 will not work with raw_input.
Can off course use int(raw_input(' ') to get it to return an integer.
Or chage the code later int(guess)

It`s alwayse best to use raw_input for python 2.x,this work same as input() python 3.x.
Both my code example should work fine,so maybe som problem with python installation for NekoChan.

snippsat 661 Master Poster

The first code should work fine for python 2.6
Here is a test from IDLE.

IDLE 2.6.5    
>>> secret = 1337
>>> guess = 0
>>> count = 0
>>> while guess != secret:
	guess = input("Guess: ")
	if guess < secret:
		print "to small"
	elif guess > secret:
		print "to big"
	count += 1

	
Guess: 500
to small
Guess: 5000
to big
Guess: 1337
>>>
snippsat 661 Master Poster

Yes can be that he use python 3.
Then off course input()return a string.
input() in python 2 return an integer.
Here is a rewritten version for python 3

secret = 1337
guess = 0
count = 0
#Help the user give number range.
print ('Guess s number it`s between 0 <-> 2000 ')
while guess != secret:
    guess = int(input("Guess: "))
    if guess < secret:
        print ("to small")
    elif guess > secret:
        print ("to big")
    count += 1

print ('You guessed the number in %s try' % count)
snippsat 661 Master Poster

Use codetag and use english when you post in forums.
Try to run this script.
Maybe you have indentations problem when you type in IDLE.

secret = 1337
guess = 0
count = 0
#Help the user give number range.
print 'Guess s number it`s between 0 <-> 2000 '
while guess != secret:
    guess = input("Guess: ")
    if guess < secret:
        print "to small"
    elif guess > secret:
        print "to big"        
    count += 1

print 'You guessed the number in %s try' % count
snippsat 661 Master Poster

A more clearer an Pythonic way to print the last line and some better variable name.
This is done to make code more readably that always count as a plus.

s.replace('\n', '') you only need if you read in from a file.

s = """An Oligonucleotide is a short segment of RNA or DNA, typically with twenty or fewer bases. Although they can be formed by cleavage of longer segments,
they are now more commonly synthesized by polymerizing individual nucleotide
precursors. Automated synthesizers allow the synthesis of oligonucleotides up to 160
to 200 bases"""
                
word_split = s.split()
print word_split  #Test print.
# Look at the list and see if you happy with it
# 'DNA,' 'bases.' this is count as 2 word so ",." should not needed to be replaced.

print "Number of words =", len(word_split)
for letter, word in enumerate (word_split):   
    print '%d Number of letters in the word is: %s : %d'  % (letter + 1, word, len(word))
snippsat 661 Master Poster

Where is python used?

http://www.python.org/about/quotes/

YouTube is coded mostly in Python. Why? “Development speed critical”.
They use psyco, Python -> C compiler, and also C extensions, for performance critical work.
They use Lighttpd for serving the video itself, for a big improvement over Apache.

Most of the Spotify backend is written in Python, with smaller parts in C and Java,

Google has this filosofy
"Python where we can, C++ where we must"

Python dos not need to wrap code in class to make it work as in java.
This make it easy to test small part off the code.
Python vs java

Some basic off the python class you can look at.

class SimpleClass(object):
  '''Doc string info about class'''  
  # Class attributes as you see this is variables
  # They the belong to a class therefor the name 'attributes' 
  x = 5
  y = 10
  s = x + y
  
  def __init__(self, string):    
     '''
     This is the constructor in python you need only 1 constructor
     Self is the class glue,and it also transport data between metods
     When you make_objekt everything in this method get run because of __init__ 
     '''
     self.string = string
     print 'In the constructor'
     print 'Value from argument -->', string
     print ''     
      
  def SayHello(self, string):
    '''This is a function,but in a class it is called a method'''
    print 'Hi, ' + string + '.'
    
  def data_get(self):
    '''Recive data from __init__'''
    print 'Data from __init__ -->', self.string  #Try …
snippsat 661 Master Poster

A one liner i came upp with for fun.

print 'List has duplicate item %s' % [item for item in set(L) if L.count(item) > 1]
'''List has duplicate item ['oranges']'''
snippsat 661 Master Poster

Do you have a question?
If this is a school task try to code something yourself.

What you have now is pseudocode,that maybe has some info to this task that we dont know.

snippsat 661 Master Poster

For python 3 there is PyQt
Comes with Qt designer

Look at Ene Uran post about qt-designer.
http://www.daniweb.com/forums/thread191210-10.html

snippsat 661 Master Poster

time.sleep(10000000)is a vey long time and will give an error message.
OverflowError: sleep length is too large

time.sleep(5) #wait for 5sec
You can try this

import time
abc = [1,2,6,2,4,2,4,6,3,43,6]
print 'hey%s' % abc
time.sleep(5)
print 'What not again %s' % abc
snippsat 661 Master Poster
IDLE 2.6.5      
>>> abc = [1,2,6,2,4,2,4,6,3,43,6]
>>> print 'hey%l'%abc

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print 'hey%l'%abc
ValueError: incomplete format
>>> print 'hey %s' % abc
hey [1, 2, 6, 2, 4, 2, 4, 6, 3, 43, 6]
>>>
snippsat 661 Master Poster

Off course python doc has info about this.
This is very basic off any language.

You can look at this.

i = 55
print i
print(type(i))  

s = 'hello'
print s
print(type(s)) 

l = [1, 2, 3]
print l
print(type(l))  

print('string say %s i am an integer %d this is a list %s' % (s, i, l))

'''-->Out
55
<type 'int'>
hello
<type 'str'>
[1, 2, 3]
<type 'list'>
string say hello i am an integer 55 this is a list [1, 2, 3]
'''
snippsat 661 Master Poster

remember to use try to catch TypeError

Yes,we can take that later how to catch errors(Exception handling).
When you new is more important to get the code to run and understand the logic.
Then is a good exercice to try and catch all error a user input question can give.

snippsat 661 Master Poster

any one knows how to do that

Yes off course many off us now how to that,you should try something yourself.

Here is an explaination.
For first question use int(raw_input('how many questions: ') or python 3 int(input('...').
This will return an integer.
Then you make an empty list my_list = [ ].
So make for loop with range('..'),where you put variable from first question.
Then a new question inside the loop where you bind that question to a variable,that question will loop as many times as the first question variable return because you put it in a range function.
Then you append that question variable to the empty list my_list.append('...')
So outside the for loop you do sum(my_list)

snippsat 661 Master Poster

but what do they mean with this: directory[last,first] = number

Test it out

IDLE 2.6.5      
>>> directory = {}  #Empty  dictionary
>>> last = 'hansen'
>>> first = 'tom'
>>> number = 22558899
>>> directory[last,first] = number
>>> directory
{('hansen', 'tom'): 22558899}
>>> 
>>> dir(directory)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> #Here you see methods under dictionary
>>> directory.keys()
[('hansen', 'tom')]
>>> #So first last is a tuple key in the dictionary
>>> directory.values()
[22558899]
snippsat 661 Master Poster

Just to show an alterntive print line with string formatting.
Now you see it find car one time.
Try to change the code so it find both cases off car in the text.

text = '''I like to drive my car.
My car is black.'''    

search_word = 'car'
index = text.find(search_word)
if index == -1:
    print "Nothing found"
else:
    print "%s found at index %s" % (search_word, index)

'''-->Out
car found at index 19
'''
snippsat 661 Master Poster
snippsat 661 Master Poster

Same question.
http://www.daniweb.com/forums/thread285652.html
I give some direction in that post.

This must be a school assignments therefore you should try to code yourself.
You most had have some lecture about this,this is not an assignments for someone who just started with python.

snippsat 661 Master Poster

Some fun.

import re
print 'Word found was found %s times' % (len([re.findall(r'\bhi\b',open('my_file.txt').read())][0]))

Or a more readable version.

import re

Search_word = 'hi'
comp = r'\b%s\b' % Search_word
my_file = open('my_file.txt').read()
find_word = re.findall(comp, my_file)
print 'Word was found %s times' % len(find_word)
snippsat 661 Master Poster

Think this is a school assignments,and your try now is really a mess.
You should look more at how class in python work,read some tutorials/book or ask your teacher for help.

Create an Order class. The Order class should have a constructor which takes 2 parameters: a tracking number and a timestamp.

def __init__(self, tracker, timer, pay, ship, complete, cancel):
You have 6 parameters,for the constructor.
And you have to set variabels for the constructor.
self.tracker = tracker
self.timer = timer

So it should look like this.

def __init__(self, tracker, timer):
     '''This is the constructor we give it 2 arguments'''
     self.tracker = tracker
     self.timer = timer

Some code not finish off course,that can lead you in a better direction for solving this assignments.

import time

class Order(object):
    def __init__(self, tracker, time):
        '''This is the constructor we give it 2 arguments'''
        self.tracker = tracker
        self.timer= time
   
    #Implement 4 methods (pay, ship, complete, cancel)
    def pay(self,payment):
        '''This is a method that belong to Order class'''
        self.payment = payment
        self.payment_timer= self.timer        
    
    def ship(self,timestamp):        
        pass
    
    def complete(self):        
        pass
    
    def cancel(self):        
        pass   
   
    def __str__(self):
        '''Return a pleasant representation'''
        return "tracking_number %s payment %.2f payment_timer %s" % (self.tracker, self.payment,self.payment_timer)    

def timestamp():    
    lt = time.localtime(time.time())
    return "%02d.%02d.%02d.%02d.%02d" % (lt[0], lt[1], lt[2], lt[3], lt[4])
    
def main():   
    tracking_number = 44    
    #Example of making objects using Order class
    #We have to give 2 arguments to the constructor 
    object_order_1 = Order(tracking_number, timestamp())
    
    #Then we can test out the new object
    payment = …
snippsat 661 Master Poster

Youtube and spotify you may have heard off.

Youtube is written in python why? "because development speed is critical"

http://highscalability.com/youtube-architecture

Most of the Spotify backend is written in Python, with smaller parts in C and Java

http://www.spotify.com/int/about/jobs/software-engineer-backend/

http://www.python.org/about/quotes/

So why is most of the world's cool new software being written in C and now Java? Partially because people do not know about Python, which I am helping to change through advocacy. Partially it is because these languages are more efficient than Python. I am also helping to change this through support of compiler technologies.

http://www.prescod.net/python/why.html

A lot more software could be written in python,many schools,university has java C/C++ only as education therefor many contiune to use thoose languages in work life.
Some changes are coming like MIT that has switch to python for there software Computer Science lecture.
http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm

snippsat 661 Master Poster

Have you read at Pygame news? I cannot tell if they are going to abandon Pygame but they are heading on JS. If they are abandoning Python I would not bother learning it. I would look at other modules or Move to another language.

pygame rewritten for javascript - Apr 1, 2010

The date give you a hint.

snippsat 661 Master Poster

First you can start to dowload a picture from web.

2. Download found Images (urllib2?)

Yes can use urllib2.

I have been thinking off makeing a Image crawler for a while now and maybe with a gui frontend(wxpython)
Just havent getting startet yet.

Here some code you can look at,download a random picture i found on net and save it to disk.

from urllib2 import urlopen

def download_from_web(url,outfile):
    '''
    Give url adress to source you want to download
    Name of fileformat example <somthing.jpg>
    '''    
    try:
        webFile = urlopen(url)
        localFile = open(outfile, 'wb')
        localFile.write(webFile.read())
        webFile.close()
        localFile.close()
    except IOError, e:
        print "Download error"
        
def main():
    #Just a random picture
    download_from_web('http://www.opticianonline.net/blogs/big-optometry-blog/Optyl.jpg','myfile.jpg')        
        
if __name__ == "__main__":
    main()
snippsat 661 Master Poster

Fix your indentations(4 space)
Python will not work with wrong indentations.
Shall look like this.

def __init__(self, image, x, y):
    self.image= image
    self.xPos=x
    self.yPos=y
    self.dir=1

If you dont know this,read some basic lesson before you try pygame.
Like byte og python

snippsat 661 Master Poster

That cant be the hole line? print "\n".join(["%s %s" % .
Print is a function i python 3,therefor always print() .

Just to finish that line with something so it work

>>> print ("\n".join(["%s %s" % ('a','b')]))
a b
>>> 
# some test you can look at
>>> print '\n'
  File "<string>", line None
SyntaxError: invalid syntax (<interactive input>, line 1)
>>> print ('\n')


>>> t = ['my', 'car']
>>> print(''.join(t))
mycar
>>> print ('I like %s' % ''.join(t))
I like mycar
>>>