snippsat 661 Master Poster

You can call file/help or other standar name in a menu,whatever you want.
Here the standar way.

menubar = wx.MenuBar(wx.MB_DOCKABLE)
file = wx.Menu()
help = wx.Menu()
menubar.Append(file, '&File')
menubar.Append(help, '&Help')

So say that you want other name.

menubar = wx.MenuBar(wx.MB_DOCKABLE)
open_file = wx.Menu()
super_help = wx.Menu()
menubar.Append(open_file, '&open_File')
menubar.Append(super_help, '&super_Help')
snippsat 661 Master Poster

now i can't figure out what does find+1 means..

A clue most programming start indexing/counting at 0.

def find_genes(gene,sequence):
    my_list= []  #Dont use list as a varible name,it`s a python keyword

    count = sequence.count(gene)
    find = sequence.find(gene)
    my_list.append(find)

    while find > -1:
        find = sequence.find(gene,find+1)
        my_list.append(find)
        return count,my_list  #Move to remove -1

text = """\
My name is Fred Flintstone and I am a famous TV
star.I have as much authority as the Pope,I
just don't have as many people who believe it.
Fred
"""
gene = 'Fred'

count,index_word =  find_genes(gene,text)
print '%s occurred %s times,at index %s' % (gene,count,index_word)
snippsat 661 Master Poster

It work fine for me,it has no error so it should work for you to.
In your first code both __int__ statement was wrong should be __init__

import wx

class my_window(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self,parent,id,'My Window', size=(300,200))
    
        self.SetBackgroundColour('BLACK')

if __name__ == "__main__":
    app=wx.PySimpleApp()
    frame=my_window(parent=None,id=-1)
    frame.Show()
    app.MainLoop()
snippsat 661 Master Poster
import wx

class my_window(wx.Frame):
    def __init__(self, parent, id):  #error __int__
        wx.Frame.__init__(self,parent,id,'My Window', size=(300,200))

        #Panel for frame
        self.panel = wx.Panel(self)
        self.SetBackgroundColour('blue')

if __name__ == "__main__":
    app=wx.PySimpleApp()
    frame=my_window(parent=None,id=-1)
    frame.Show()
    app.MainLoop()
snippsat 661 Master Poster

Like this it can be done,did some changes in your code that generate a infinity loop.
Read stiky post about GUI in top on this forum.
http://zetcode.com/

import wx

class MyFrame(wx.Frame):
    '''info about class | doc_string'''
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)

        #---|Window color|---#
        self.SetBackgroundColour('light blue')

        #---|Panel for frame|---#
        self.panel = wx.Panel(self)

        #---|Button|---#
        self.button1 = wx.Button(self.panel, -1, "Click", (100,35))
        self.Bind(wx.EVT_BUTTON, self.EvtChoice,self.button1) #***

        #---|Static Text|---#
        self.text = wx.StaticText(self.panel, -1, '', pos=(100,70))

    #Your code this is called event handling
    def EvtChoice(self, event): #***
        '''print out 10 numbers'''
        printthis = 0
        my_list = []
        while True:
            printthis += 1
            my_list.append(printthis)
            make_string = [str(x) for x in my_list]
            self.text.SetLabel(' '.join(make_string))
            #print printthis   # You dont use print in GUI,it can be ok for troubleshooting
            if printthis == 10:
                return False

if __name__ == "__main__":
    app = wx.App()
    mytitle = 'My window'
    width = 300
    height = 200
    MyFrame(None, mytitle, (width, height)).Show()
    app.MainLoop()
snippsat 661 Master Poster

Should not be so hard to understand it`s a slice method that work on string.
your string[start:end]

>>> s = 'my car'
>>> s[0]
'm'
>>> #m is first,we cont from zero

>>> #So if we want to take out car,we count [start:end]
>>> start = 3
>>> end = 6
>>> s[start:end]
'car'
>>>
snippsat 661 Master Poster
'''
#part.txt
This is a test.
I want to take out this part,of the text
'''

f = open('part.txt')
#readlines() return a list,so string slice wont work [start:end]
print f.readlines()
#--> ['This is a test.\n', 'I want to take out this part,of the text']


f = open('part.txt')
#read() return a string and you can use string slice
print f.read()[35:44]
#--> this part

#Join() as you may now convert a list to string
''.join(['This is a test.\n', 'I want to take out this part,of the text'])[35:44]
#--> this part
snippsat 661 Master Poster

No,i dont get None at the end.

and
the
happy
summer
days
the
end
>>>

read_book(file_in) #ok
print read_book(file_in) #will return None,because you are calling a function that has no return statement

snippsat 661 Master Poster

Some advice,and no None as d5ed poinet out.

import string

def read_book(file_in=None):
    '''
    Read in file,strips whitespace-punctuation
    Returns them in lowercase
     '''
    f = open(file_in)  #r is default
    for l in f:        #Dont need readlines
        book_line = l.strip().translate(None, string.punctuation)
        for w in book_line.split(" "):
            if w != "":
                print w.lower()

def main():
    """main function"""
    file_in = 'alice.txt'
    read_book(file_in)  #The function you calling has print
    #return 0           #Not needed in python how has an excellent garbage collection

if __name__ == "__main__":
    main()
snippsat 661 Master Poster

This should help,and try to post some code next time.

>>> from __future__ import division
>>> my_list = [1,2,3,4]
>>> avg = sum(my_list)/len(my_list)
>>> avg
2.5
>>>
snippsat 661 Master Poster

python.org tell people to forget about python 2 and head into python 3.

No they do not.

For example, python 3 only ship with a tkinter gui module which does not have great reputation. If I am to use python 3, I have no choice but to use tkinter.

No,you have not PyQT and PyGTK has been portet to python 3,so plase uppdate yourself.
We had many thread about python 2 or 3 her on daniweb
To make it simple python is python,have both installed and learn what the diffrence are.
Then there is no problem to switch back and fourth.
One therad that was about this recently.
http://www.daniweb.com/forums/thread324004.html

snippsat 661 Master Poster

Here is a proxy test that worked for me.
Maybe it can help you.

import urllib2

proxy_handler = urllib2.ProxyHandler({'http':'184.73.131.27:3128'})
opener = urllib2.build_opener(proxy_handler)
f = opener.open('http://www.whatismyipaddress.com')
print f.read()
snippsat 661 Master Poster

PyQt is compitable with python 3,and of course build in Tkinter.
http://www.riverbankcomputing.co.uk/news
For beginner there is a massive amount of quality book/tutorials/forum help that are almost all inn pyhon 2.x.
Is not a smart ting to overlook all that info because you look only for for python 3 stuff.

snippsat 661 Master Poster
snippsat 661 Master Poster

Just have both installed as most of us have.
Wxpyhon is a excellent GUI toolkit use python 2.x if you need to use that.

This topic has been upp several times,python is python dont get hang up in python 2.x or 3.x.
If you are learning python 3.,you are learing python 2.x and visa versa.
Just get ourself uppdatet what the differences are.

snippsat 661 Master Poster

Nice one woooee.
Just need a fix of range[1, 6] to range(1, 6)

snippsat 661 Master Poster

Not your lucky day snippsat, double post and:

Yes,a misstype when a did some edting of forum code thx.
Did fix it now.

snippsat 661 Master Poster

You have to some reading about dictionary.
Some stuff you can look at.

>>> z = {'a': 1, 'a': 2, 'a': 3, 'b': 4, 'c': 5}
>>> z
{'a': 3, 'b': 4, 'c': 5}
>>> #Keys are unique within a dictionary while values may not be
>>> #That`s why only last value 3 is bind to key 'a'

>>> d = {'a' (1,2,3)
>>> d['a']
(1, 2, 3)
>>> #now key 'a' has value of 1,2,3
>>> d.keys()
['a']
>>> d.values()
[(1, 2, 3)]
 
>>>#some explation  about get.
>>>#dict.get(key, default=None)
>>>#For key key, returns value or default if key not in dictionary
>>> z.get('a')
3
>>> d.get('a')
(1, 2, 3)
>>> print d.get('b')
None
>>>
snippsat 661 Master Poster

A rule that can be good to remember.
Never delete something from or add something to the list you are iterating over.

The solution is:
Iterate over your original list, and put everything which passes your test into another list.

Some way of doing this.
Using List comprehensions.

>>> l = [1,2,3,4,5,6,7,8]
>>> odd_remove = [item for item in l if item %2 != 1]
>>> odd_remove
[2, 4, 6, 8]
>>>
l = [1,2,3,4,5,6,7,8]

even_list = []
for item in l:
    if item %2 != 1:
        even_list.append(item)

print even_list  #[2, 4, 6, 8]
l = [1,2,3,4,5,6,7,8]

for item in l[:]: #make a copy of list
	if item %2 != 0:
	    l.remove(item)

print l  #[2, 4, 6, 8]
snippsat 661 Master Poster

Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the ‘property’ built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in ‘property’.

http://tomayko.com/writings/getters-setters-fuxors

The link over is follow up from python is Not java.
http://dirtsimple.org/2004/12/python-is-not-java.html

snippsat 661 Master Poster

An example i make some code that calulate average.

#average.py
#saved in python dir
from __future__ import division

def average(average_list):
    if isinstance(average_list, (list, tuple)):
        return sum(average_list)/len(average_list)
    else:
        return 'Input can only be list or tuple'

So import it and test it out.
Save it in python sys.path or same folder as your other .py-file.

#Check out path
>>> import sys
>>> sys.path
>>> from average import average
>>> average
<function average at 0x04D2C430>
>>> average([1,2,3,4])
2.5
>>> average(88)
'Input can only be list or tuple'
>>> average('hi')
'Input can only be list or tuple'
>>>
snippsat 661 Master Poster

Use code tags.
A shorter way to average.

from __future__ import division

def getAverage(numList):
    return sum(numList)/len(numList)

print getAverage([1,2,3,4])
snippsat 661 Master Poster

Some pratice you can try out in IDLE.

>>> name = raw_input("Enter Name: ")
Enter Name: joe
>>> name
'joe'
>>> list(name)
['j', 'o', 'e']

>>> #This is called list comprehension
>>> [i for i in name]
['j', 'o', 'e']

>>> #Written as an ordenarry loop
>>> my_list = []
>>> for i in name:
	my_list.append(i)	
>>> my_list
['j', 'o', 'e']

#one with map()
>>> map(str, name)
['j', 'o', 'e']

>>> #convert to string
>>> ''.join(my_list)
'joe'

>>> n = (1+2+3+4+5+6)
>>> n
21

>>> l = list(str(n))
>>> l
['2', '1']

#list comprehension
>>> [i for i in l]
['2', '1']
>>> [int(i) for i in l]
[2, 1]
>>> sum([int(i) for i in l])
3
>>>
snippsat 661 Master Poster

ran it and I was so happy with it, but then... why on Earth does it tell me that "5" is higher than "24"? Or why does it tell me that "5" is higher than "45"?? Or why "5" is higher than "13"?

Because you are comparing string and not integer.
Python 3 has only input() and it return a string,but you can choose what datatype it shall return with int() float() .

Just an advice.
For beginner there is a massive amout of tutorials/books/forum help that are in python 2.x this is important stuff for learing python.
If you learn python 2.x you learn of course python 3.x,have both installed is a good chooice.
Most pepole still use python 2.x in wait for many 3 part moduls to be rewritten in python 3.

#python 3
>>> x = input('Give a value for \'a\': ')
>>> Give a value for 'a': 5
>>> type(x)
<class 'str'>

>>> x = int(input('Give a value for \'a\': '))
>>> >>> Give a value for 'a': 3
>>> type(x)
<class 'int'>

>>> #Or use float for decimal number
>>> x = float(input('Give a value for \'a\': '))
>>> Give a value for 'a': 5.3  
>>> type(x)
<class 'float'>

>>> #You can also convert later in code
>>>  if float(a) > float(b):
snippsat 661 Master Poster

Just to put in one line.
You can try to understand the code and spilt it more upp.
If it a school task you have to explain and understand the code.

>>> sum([float(item) for item in i.split(',') for i in open("numbers.dat")])
47.0
>>>
snippsat 661 Master Poster

Something you can look that may help you.

>>> s = '13, 15, 19'
>>> s = s.split(',')
>>> s
['13', ' 15', ' 19']
>>> [float(item) for item in s]
[13.0, 15.0, 19.0]
>>> sum([float(item) for item in s])
47.0
>>>
snippsat 661 Master Poster

Use parser BeautifulSoup is good.

from BeautifulSoup import BeautifulSoup

html = '''\
<a href="http://www.gumtree.sg/?ChangeLocation=Y" rel="nofollow">Singapore</a>,
<a href="http://www.gumtree.com.au/?ChangeLocation=Y" rel="nofollow">Australia</a>,
<a href="http://www.gumtree.co.nz/?ChangeLocation=Y" rel="nofollow">New Zealand</a>,
<a href="http://www.gumtree.com" rel="nofollow">England</a>, <a href="http://edinburgh.gumtree.com" rel="nofollow">Scotland</a>,
<a href="http://cardiff.gumtree.com" rel="nofollow">Wales</a>,
<a href="http://www.gumtree.ie" rel="nofollow">Ireland</a>, <a>
'''

soup = BeautifulSoup(html)
links = soup.findAll('a', href=True) # find <a> with a defined href attribute
for link in links:
    print link['href']
    
''' output-->
http://www.gumtree.sg/?ChangeLocation=Y
http://www.gumtree.com.au/?ChangeLocation=Y
http://www.gumtree.co.nz/?ChangeLocation=Y
http://www.gumtree.com
http://edinburgh.gumtree.com
http://cardiff.gumtree.com
http://www.gumtree.ie
'''
Gribouillis commented: very simple +4
snippsat 661 Master Poster

also i wud like to know about the differences between java and python

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

Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.

Python has a lot off power and are used in many areas
http://www.python.org/about/quotes/

snippsat 661 Master Poster
>>> Z = []
>>> X=['a']
>>> Y=['b','c','d','e','f']
>>> for i in Y:
...     Z.append(X[0] + i)
...     
>>> Z
['ab', 'ac', 'ad', 'ae', 'af']
>>>
snippsat 661 Master Poster

Try to some code something yourself next time,not just ask for a soultion.

b = 0
a = 5

while b < a:
    b = b + 1
    print b

#-----------
for i in range(1,6):
    print i
snippsat 661 Master Poster
snippsat 661 Master Poster

When it comes to parseing xml/html regular expression is not the right tool.
Use a parser python has several in standar libary or very good 3 party parser like beautifulsoup and lxml.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

snippsat 661 Master Poster

I have to compare 5 words so writing a seperate for each combination would take too long

I don see why you should use for loop like that for comparing 5 words.
Give an example of the words,and how you think the comparing output should look.

snippsat 661 Master Poster

Another way that i think is ok to read.

import os

filenames = os.listdir(os.curdir)
for filename in filenames:
    for ext in ['txt', 'htm', 'html']:
        if filename.lower().endswith(ext):
            print filename
snippsat 661 Master Poster

I did write about exception handling(try,except)in this post you an look at.
http://www.daniweb.com/forums/thread245633.html

snippsat 661 Master Poster

From looking at your code i have shorten it down.
You have to many repating statement,that is not so good in programming.
Have not read all rule off game,that you have to work on.

from random import randint

def rollDice():
    return [randint(1, 6) for r in range(6)]

def user_input():
    while True:
        response = raw_input("\nWould you like a roll?\n").lower()
        if response in ['y','yes','']:
            dice = rollDice()
            return dice
        else:
            print "That is not a valid response,try again"

if __name__ == '__main__':
    roll = user_input()
    print roll
    score = 0
    for i in roll:
        if i == 1:
            score+=100
        if i == 5:
            score+=50
    print 'Your total score for this round is %s' % score
snippsat 661 Master Poster

Can you post score.dat or a sample of the file.
Show what data from the file you will take out,and how the list should look.

snippsat 661 Master Poster

You have to read about regex,there is no way to explain it a short way.
http://docs.python.org/library/re.html

Just one more example a text where a take out price.
\$ match $
\d match any number.
. matches any character except a newline.

import re

text = '''\
Hi this is a string with a price $5.30.
Text has also a number we dont want $55.99
'''

test_match = re.findall(r'\$\d.\d+', text)
print test_match  #5.30
snippsat 661 Master Poster

Read this post by bobince why regex is a very bad idèe when it`s come to parse (x)html.
It`s one of the best answer on stackoverflow.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

For small website is it`s possibly to use only regex.
But the way is to regex in a combo with BeautifulSoup,lxml
I use this two parser,because the are best at parsing html.
HTMLParser will break if html is a little malformed,very few sites has perfect html.
Around only 5% on all websites on internet has 100% valid html.

Here i get price with just regex.

import urllib2
import re

url = urllib2.urlopen('http://beans.itcarlow.ie/prices.html').read()
print re.search(r'\$\d.+\d', url).group()  #$5.30
snippsat 661 Master Poster

Python has 2 very good 3 party parser BeautifulSoup and lxml.
This parser can handle html that is no good,this can be important.
An example with BeautifulSoup.
We want the price of beans from this site.
http://beans.itcarlow.ie/prices.html

from BeautifulSoup import BeautifulSoup
import urllib2

#Read in website
url = urllib2.urlopen('http://beans.itcarlow.ie/prices.html')
soup = BeautifulSoup(url)
print soup #website contents

tag = soup.findAll('strong') #Find strong tag
print tag                    #[<strong>$6.36</strong>]
print tag[0].string          #Print out info we want "$6.36"

Firebug is a good tool to navigate in source code of a website.
http://getfirebug.com/

snippsat 661 Master Poster

Your class look strange,dont see a point with __len__ and __str__ in that class.

test = zoeken()
#calling find method.
print test.find(****) #Takes 4 ****arguments or 0 because of default arguments.
Maybe is better you explain what you want to do?

print test(test2)
You only return test2 in __str__ so how do you think that should work.
Calling method in that class is test.something() not test(something)

snippsat 661 Master Poster

And it's not working, so how should i do shuffel thing?

import random

my_string = 'abcdefghijklmnopqrstuvxyzo'

my_list = []
for i in range(len(my_string)):
    if i == 10:
        my_list.append(my_string[:i])


r =  list(''.join(my_list))
print r #now we can shuffle
random.shuffle(r)
shuffle_string = ''.join(r)
print shuffle_string         #string
#--> ebdihfjgca
print shuffle_string.split() #make list
#--> ['ebdihfjgca']
snippsat 661 Master Poster

If you want to shuffle it`s need to more than 2 elements in list.
Look into spilt(),list(),to split upp upp a string or a list.

>>> a = 'abc'
>>> list(a)
['a', 'b', 'c']

>>> a = 'a b c'.split()
>>> a
['a', 'b', 'c']
>>> from random import shuffle
>>> help(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.

>>> #This list has 3 element
>>> l = ['a', 'b', 'c']
>>> shuffle(l)
>>> l
['b', 'a', 'c']
>>> my_list
['abcdefghij']
>>> #my_list has only 1 element an can not be shuffled
>>> print shuffle(my_list)
None
>>>
snippsat 661 Master Poster
>>> c = dict( key = 0 )
>>> c
{'key': 0}
>>> c['key'] = 49
>>> c
{'key': 49}
>>> my_list = []
>>> my_dict = {}
>>> a = 'a string'
>>> b = 78
>>> my_list.append(a)
>>> my_list.append(b)
>>> my_list
['a string', 78]
>>> my_list.append(c)
>>> my_list
['a string', 78, {'key': 49}]
>>>
snippsat 661 Master Poster

Dont use list as a variable name,it`s a python keyword

>>> list
<type 'list'>
>>> a = 'abc'
>>> list(a)
['a', 'b', 'c']

Loop over the len() of my_sting,stop at 10 and use slice.

my_string = 'abcdefghijklmnopqrstuvxyzo'

for i in range(len(my_string)):
    if i == 10:
        print my_string[:i]
        #--> abcdefghij

If you want to save 10 chars in a list.

my_string = 'abcdefghijklmnopqrstuvxyzo'

my_list = []
for i in range(len(my_string)):
    if i == 10:
        my_list.append(my_string[:i])
        
print my_list
#--> ['abcdefghij']
snippsat 661 Master Poster

Here something you can look at.

class testClass(object):
    def __init__(self):
        self.my_dict = {}
        
    def uppdate(self,key, value):
        self.my_dict[key] = value

    def remove(self,del_key):
        del self.my_dict[del_key]

    def show_data(self):
        print self.my_dict

if __name__ == '__main__':
    test = testClass()
    test.uppdate('a', 1)
    test.uppdate('b', 2)
    test.uppdate('c', 3)
    test.remove('c')
    test.show_data()  #{'a': 1, 'b': 2}

Something to think off is that a class uses dicitonary as a internal storage.
Example.

class Server(object): 
    '''python constructor'''
    def __init__(self, server_name, port):        
        self.server_name = server_name
        self.port = port

server_1 = Server('master_100', 1234)
server_2 = Server('blob_500', 9999)

#if we print the internal working of the class storage of variables
print server_1.__dict__
print server_2.__dict__
'''Out-->
{'port': 1234, 'server_name': 'master_100'}
{'port': 9999, 'server_name': 'blob_500'}
'''

#So it work like a dictionary if we call server_name(key)
#We are getting the value.
print server_1.server_name
#--> master_100
print server_2.port
#--> 9999
snippsat 661 Master Poster

Make it an integer with int()

>>> paid_value = '55'
>>> type(paid_value)
<type 'str'>
>>> paid_value = int(paid_value)
>>> type(paid_value)
<type 'int'>
>>> paid_value ** 5
3025
snippsat 661 Master Poster

In program 1 they are returned by an extra argument calles cls put in program to they are returned directly with the class name. Could someone please help me understand?

Yes that what a class method do,did you read my link in the other post.
Vector2.from_points(A, C) here you call a method without making a instance(object).
Normal without @classmethod you make it like this.

v = Vector2(10, 20)   #make instance
v.from_points(5, 5)   #and call method like this.

You see the difference?
http://pyref.infogami.com/classmethod
http://docs.python.org/library/functions.html?highlight=classmethod#classmethod

snippsat 661 Master Poster

but what the hell is rhs.x and .y?

rhs is a name author of this code have choose.
You can can use whatever name you want when it comes to method/function arguments.
__add__ in this class will have an other meaing that normal __add__.
AB + BC call Vector2 and method def __add__(self, rhs)

# rhs stands for power of
def foo(rhs):
    a = 5
    b = a ** rhs
    return b

print foo(5) #3125

Or.
# my_car stands for power of
def foo(my_car):
    a = 5
    b = a ** my_car
    return b

print foo(5) #3125

So you see that you can use stupid name that confuse.

snippsat 661 Master Poster

Key in a dictionary can not use list.
If you turn it around is ok,and set list as an value.

>>> codes = {}
>>> inpt = raw_input("<<<").split()
<<<my car
>>> inpt
['my', 'car']
>>> inpt2 = raw_input("?...")
?...black
>>> inpt2
'black'
>>> codes[inpt] = inpt2

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    codes[inpt] = inpt2
TypeError: unhashable type: 'list'
>>> codes[inpt2] = inpt
>>> codes
{'black': ['my', 'car']}
>>>