snippsat 661 Master Poster

A little messy this.
Import <moudule> always first not inside code.
You call main() 3 times,call main() one time.
if comp_choice != userchoice: type error.
And the big mistake vegaseat pointet out.

It won't work!

Yes that`s for sure true.

The logic could be better,user only win if 3-3 4-4....
Maybe hightest dice number should win.
So the script without function,with a different print statement.

import random

user_choice = input('Type a number, 1 to 6.\n\n')
comp_choice = random.randint(1,6)

if comp_choice != user_choice:
    print 'Computer got %d user had %d | Computer won' % (comp_choice,user_choice)   
else:
    print 'Computer got %d user had %d | User won' % (comp_choice,user_choice)

Now think off again how to use function for this code.
Here just to give you and idèe off one way to set it upp.

def get_user_choice():
   print 'your code'
   pass

def check_if_true():    
    pass

def main():
    '''Main menu and info ''' 
    while True:               
        print 'Welcome to my menu\n'
        print '(1) Throw a dice against computer'
        print '(2) Nothin yet'
        print '(q) Quit' 
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            get_user_choice()           
        elif choice == '2': 
            pass 
        elif choice == 'q': 
            exit() 
        else: 
            print 'Not a correct choice:', choice 

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

What are you doing fummy,can you not read?
2 times har Murtan ask you to put your code in code tags.

So that indentations is correct.
Is that so hard?
http://www.daniweb.com/forums/announcement114-3.html

snippsat 661 Master Poster

Is it not better to make one function like this to add 2 number.

def add_number():
    n = raw_input('Enter number to add format (2+2)')
    num1, num2 = n.split('+')
    my_sum = int(num1) + int(num2)
    print my_sum

add_number()
snippsat 661 Master Poster

Look at this here two way to work with function.
Maybe you get some idèe on how to solve your +*-/ with function and a menu.
One function i just return and do calulation in main.
They other function all calulation and exception handling is done in fuction.

Try to get comfortable with use off function.
Then look at classes and a more OOP apropose to solve problem. except: is the easy way here a catch many errors.
You can catch error you need.
Try option 1 the one without exception handling and type a letter.
Now you get a NameError
To catch that except NameError: Just a litte on how to handle error.

def radius_1(r):
    '''Here we just return and do calulation in main'''
    pi = 3.14
    return pi * r * r

def radius_2():
    '''
    Here we do calulation in fuction,with exception handling
    Try to breake it with wrong input,you see that not so easy
    '''    
    while True:
        try:
            r = input ('enter radius: ')
            pi = 3.14
            radius_sum = pi * r * r
            if r >=0:
              print 'The radius is %.2f' % (radius_sum)
              break  #We break out off loop when answer is correct and back to menu
            else:
                print 'Invalid radius'
        except:
            print 'Wrong input'    

def main():
    '''Main menu and info ''' 
    while True:               
        print 'Welcome to my menu\n'
        print '(1) Calculate radius example_1'
        print '(2) Calculate radius example_2' 
        print '(q) Quit' 
        choice = raw_input('Enter your …
snippsat 661 Master Poster

why does it look odd?

Two classes with 1 attributt(variable) in each,is not a normal OO design.
Your program work,but for me this is not a good way to code.

Some problem.
Menu should come first so user now what this is about.
You have no exception handling,so if you type a letter program crash.

snippsat 661 Master Poster

Tkinter is the build in gui(Graphical user interface) of python.
There are many other good gui toolkit like wxpython - PyQt -PyGTK.

Tkinter is just a way of translating Tk commands into python. (please correct me if I'm wrong).

No Tkinter or any other gui toolkit is to display our python code in a graphical way.

if I draw a window with a simple button in linux, it will look just like any other button in the operating system

Yes pretty much,gui toolkit come with many ways to customize look off button and any other widgets.

I like wxpython and it has a cool demo where you can se all widgets live and test them out.
look like this.

snippsat 661 Master Poster

Yeah, IDEs like notepad++ lack the auto-indent feature

Try pyscripter has a lot off useful feature and off course auto-indent.
http://code.google.com/p/pyscripter/

snippsat 661 Master Poster

can i get a simpler example like with 3 functions and a simple task/concept

The example is simple and you shoul try to understand it.
Break it down and ask question.

def get_data():
    """get the data from the user, from a file, or hard coded"""
    mydata = [1, 2, 3, 4]
    # return requested data to caller
    return mydata

print get_data()
'''my output-->
[1, 2, 3, 4]
'''

So this is how the first function work.
It take no argument and it has a standar list that get returned out off function.

Then we can look at the next function.

def process_data(data=None):
    """this is also the main function of the program"""
    # if no data is passed, get it with this function call
    if not data:
        #data = get_data()   #here come data from get_data() function.
        data = [1, 2, 3, 4]  #this is the same
    minimum_data = min(data)   #find minium value of a list
    maximum_data = max(data)   #find maxium value of a list
    # pass the 2 needed data paramters/arguments to this function
    #show_result(minimum_data, maximum_data)
    return( "result: min=%s  max=%s" % (minimum_data, maximum_data) )

l = [2,5,5,8]

#with no argument passed to function
print process_data()
'''my output-->
result: min=1  max=4
'''

#here we pass l as an argument
print process_data(l)
'''
my output-->
result: min=2  max=8
'''

Here i have made it so this function work alone,we simualte that data comes from first fuction.
And insted off useing show_result() we return data out off this …

snippsat 661 Master Poster

Can the above code be simplified and change to graphic.py not TK

Maybe,but i wont speend any tïme at all on an outdatet module like graphics.py.
It was just made as an intro to graphic,you much forget this module if you want to make something ourself.

Look at code by masterofpuppets,it not hard at all to understand tkinter.

snippsat 661 Master Poster

You should not speend much time on outdate mouduls like graphics.py.
Think it was written in 2005 by John M. Zelle as and easy intro to graphics for beginner.

The only way to do this is to learn a gui toolkit like Tkinter-wxpython-pyqt.
I like wxpython and use that to almost all i do with gui.

snippsat 661 Master Poster

It's not supposed to show the same value, I only printed 90 as an example next to the last code, and it did this.

Do you think we can se your code based on output print screen?
If you want help you post your code or the part you think cause the problem.

snippsat 661 Master Poster

You can use what ide editor you want, whish gui toolkit you use dos have little impact.

Pyscipter is good.
http://code.google.com/p/pyscripter/

I use komodo ide,and pyscripter for python 3.x
http://www.activestate.com/komodo/

Pydev plugin should work fine,have not testet it.

snippsat 661 Master Poster

Dictionary values are accessed by their key. To allow for high speed key searches, the keys are in a hash order. So a dictionary sorted alphabetically by it's keys would make no sense and would defeat the whole dictionary idea.

Here are some way doh.

>>> d = { "a":4, "c":3, "b":12 }
>>> sorted(d.items(), key=lambda (v,k): (v,k))
[('a', 4), ('b', 12), ('c', 3)]
>>> sorted(d.items(), lambda x, y: cmp(x[1], y[1]))
[('c', 3), ('a', 4), ('b', 12)]
snippsat 661 Master Poster

1 more question. How do I start the default web browser to a specific URL in python?

>>> import webbrowser
>>> dir(webbrowser)
['BackgroundBrowser', 'BaseBrowser', 'Elinks', 'Error', 'Galeon', 'GenericBrowser', 'Grail', 'Konqueror', 'Mozilla', 'Netscape', 'Opera', 'UnixBrowser', 'WindowsDefault', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_browsers', '_iscommand', '_isexecutable', '_synthesize', '_tryorder', 'browser', 'get', 'iexplore', 'main', 'open', 'open_new', 'open_new_tab', 'os', 'register', 'register_X_browsers', 'shlex', 'stat', 'subprocess', 'sys', 'time']
>>> help(webbrowser.open)
Help on function open in module webbrowser:

open(url, new=0, autoraise=1)

>>> webbrowser.open("http://www.google.com/")
True
>>>

You second question in last post is really a mess,the same with that code example.
I really dont know what you what you mean here.

Just a guess.

count = 4
number = [1,2,3,count]
print number[3]  #4

#number [count] = 2  #this is plain wrong you cant assagin variabels this way
snippsat 661 Master Poster

Kind off help whit some clear messages.

>>> we_dot_do_homework_if_no_effort_is_shown = 2
>>> 1 % we_dot_do_homework_if_no_effort_is_shown
1
>>> 2 % we_dot_do_homework_if_no_effort_is_shown
0
>>> 3 % we_dot_do_homework_if_no_effort_is_shown
1
>>> 4 % we_dot_do_homework_if_no_effort_is_shown
0
>>> stupid = 3
>>> show_effort = 4
>>> if stupid % we_dot_do_homework_if_no_effort_is_shown == 1:
	print'Odd'
else:
	print 'even'

	
Odd
>>> if show_effort % we_dot_do_homework_if_no_effort_is_shown == 1:
	print'Odd'
else:
	print 'even'

	
even
>>>
snippsat 661 Master Poster

I just want the output to be 50, I try changing the the code but t doesn't work

Vegaseat has pretty much given you the answer.
You dont say that code dos not work and nothing more.
Then is not possibly to help you,post your code and then you say it will not work or try to explain what you need help to.

def my_sum(first,last):
    mylist = []
    for x in range(first, last+1):
        mylist.append(x * x)
    return sum(mylist)
        
print my_sum(3,5)
'''
my output-->
50
'''
snippsat 661 Master Poster

What I was expecting was that L = [ 0, 2, 1 ]

If you what this result is better to iterate over the list and append the result to a new list.

L = [ 0 , 2, 1 , -1 , -1 , -1, -1 ]

new_list = []
for item in L:
    if item >= 0:
        new_list.append(item)        
print new_list
''' my output-->
[0, 2, 1]
'''

#Or more fancyer with list comprehension
lst = [item for item in L if item >= 0]
print lst
''' my output-->
[0, 2, 1]
'''
snippsat 661 Master Poster

Tkinter has change import name in python 3.
Put this first then tkinter import correct for python 2.x and 3.x

try:
    # for Python2
    import Tkinter as tk   
except ImportError:
    # for Python3
    import tkinter as tk
snippsat 661 Master Poster

Here is class example have i tryed to explain som basic thing about the making of a class and how thing work.

class SimpleClass(object):
  '''
  Doc string info about class  
  * SimpleClass inherits the most basic container class object (just a place holder)
  * this is the newer class writing convention, adding (object) is "still" optional  
  '''  
  # 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):    
     '''
     Self is the class glue,it`s a carrier off data between metods.
     The variable s is assigned a value in the class, but outside of the methods.
     You can access s in a method using self.s #****    
     When you make_objekt everything in this method get executed because of __init__
     __init__ acts as Constructor when you make_object everything under __init__ method get executed
     You dont need to call like next method SayHello
     '''
     self.string = string
     print 'In the constructor'
     print 'Value from argument -->', string
     print 'This is my lucky number %s' % self.s #*****
     print ''     
      
  def SayHello(self, string):
    '''This look like 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 without self(remember carrier of data)      
   

# Run 1 and 1 line try to understand whats happens    
make_object = SimpleClass('hello')  #Class instance(pay attention that __init__ method …
snippsat 661 Master Poster

You can do it like this.

def getValidNum(min, max):
    print ('Enter a value between %d and %d | 0 to quit' % (min, max))
    while True:
        try:
            num = input('>')
            if int(num) in range(int(min), int(max)):
                print (num)  #test print
                #return num
            elif num == '0':
                exit()
            else:
                print('Only values between %d and %d' % (min, max))
                print("Try again.")
        except ValueError:
            print('Numbers only,try again')

getValidNum(2, 8)
snippsat 661 Master Poster
snippsat 661 Master Poster

New style class python 2.2--> you should use

class(object):

Old style pre python 2.2

class:

So object is a build in,let`s test it.

IDLE 2.6.2      
>>> object
<type 'object'>
>>>

For more deeper explanation.
http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

snippsat 661 Master Poster

You know that this code is for python 3.x?

For python 2.x

n = input('Enter an interger >= 0: ')
fact = 1
for i in range(2,n+1):
        fact = fact*i
print n, 'factorial is', fact
print 'The factorial off %d is %d' % (n, fact)  #Or like this is better

Python 3.x has only input(that return a string)
That why it`s used int(input())

I take opp this for in your post #3 you use print i <-- this will not work for python 3
Print has become a function in python 3,and only this will work print(i)
That why i think you use python 2.x

snippsat 661 Master Poster

but it doesn't seem to be working... it still gives 11.50 when i input 10...

Yes as it should do,is should not be so hard to understand.
<= 10 means that less than 10 or equal to 10 it will add 1.50.
Then off course if you input is 10 it will add 1.50 and print 11.50.
< 10 all values under 10 it will add 1.50

snippsat 661 Master Poster
>>> suits = ['diamonds', 'clubs', 'hearts', 'spades']
>>> rank = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
>>> # This is what we need to make a hole deck
>>> # Now we loop trough (rank and suits) and append the result.
>>> deck = []  # Empty deck
>>> for n in numbers:
	for s in suits:
		card = '%s of %s' % (n, s)
		deck.append(card)
		
>>> deck  # Will print the whole deck

>>> # Make it look better
>>> from pprint import pprint
>>> # Now let us print 10 card
>>> pprint(deck[:10])
['1 of diamonds',
 '1 of clubs',
 '1 of hearts',
 '1 of spades',
 '2 of diamonds',
 '2 of clubs',
 '2 of hearts',
 '2 of spades',
 '3 of diamonds',
 '3 of clubs']
>>> # The for loop can be written in 1 line like this
>>> deck = ['%s of %s' % (n, s) for n in numbers for s in suits]
>>> # A little python sugar with list comprehension

Now you can to shuffle the deck,use random module.
Deck is a list now,so to take out 1 card should be easy,look at pop() method.
To se all method for list do this dir(deck)

snippsat 661 Master Poster

It`s not the best example of python class masterofpuppets.
You put in lot effort to help wish is fine.

Hope this makes it a bit clearer....I haven't actually worked a lot with classes in Python but I guess it is not that much different to Java. So I am sorry if I didn't explain something properly... still learning as well

Python is not java,it`s a lot better:cool:
http://dirtsimple.org/2004/12/python-is-not-java.html
Just to point it out that you could have dropped all that getters method.

Form article.

don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

Look at this and then think of how you code could have been shorter and better.
http://tomayko.com/writings/getters-setters-fuxors

jlm699 commented: Great articles. I like the authors' points of view on Python. Inspiring! +3
snippsat 661 Master Poster

Yes,i should have think of that you need floating point number to get correct sum.
%.2f(give you 2 decimal float number)

is %.2f pounds" % (order + x)
snippsat 661 Master Poster

total price... is 8pounds or £8 and not just 8..

order = input("Please enter the price of the order: ")
x = 1.50
if order < 10:
    print "the total price including the delivery charge is %d pounds" % (order + x)
else:
    print "The toal price including delivery charges is %d pounds" % (order)
snippsat 661 Master Poster
>>> #Is rounds greater than player_point or cpu_point
>>> #It will print Victory
>>> #Test
>>> rounds = 5
>>> player_point = 4
>>> cpu_point = 3
>>> while rounds > player_point or cpu_point:
	print 'Victory'
	break
else:
	print 'Lose'

	
Victory
>>> #So if we change player_point to 8
>>> player_point = 8
>>> while rounds > player_point or cpu_point:
	print 'Victory'
	break
else:
	print 'Lose'

	
Victory
>>> #It still print Victory because of "or"
>>> #If we change to "and" then Lose
>>> while rounds > player_point and cpu_point:
	print 'Victory'
	break
else:
	print 'Lose'

	
Lose
>>> player_point = 4
>>> while rounds > player_point and cpu_point:
	print 'Victory'
	break
else:
	print 'Lose'

	
Victory
>>> #Last one Victory beacause now both player_point and cpu_point are less than rounds

Edit a little to late i see:icon_wink:

snippsat 661 Master Poster

Yes good.
Or shorter.

a = [raw_input('>')for x in range(5)]
snippsat 661 Master Poster

A for loop is easier for this.

for i in range(4):
    for item in ['a,b,c,d']:
        item = raw_input("something: ")
		
something: 7
something: 8
something: 9
something: 2
>>> item
'2'

>>> #If you whant to store all values put them into a list
>>> l = []
for i in range(4):
    for item in ['a,b,c,d']:
        item = raw_input("something: ")
        l.append(item)

		
something: 8
something: 9
something: 6
something: test
>>> l
['8', '9', '6', 'test']
>>>
snippsat 661 Master Poster

Next time if you post here try to post some code.
That will show that you but some effort in to it.

With homework we will not just post finish code.

Here is one soultion,as extra i put number odd/even number in a list.
Try to understand what going on,ask question if you not sure an we break it down.

import random

count_odd = 0
count_even = 0
odd_list = []
even_list = []
for i in range(0,100):
	rand_n = random.randint(0,100)
        if rand_n % 2 == 1:
            count_odd += 1
            odd_list.append(rand_n)
        else:
            count_even += 1
            even_list.append(rand_n)

print 'Out off 100 random number %d was odd\nHere are the numbers->\n' % (count_odd)
print odd_list
print
# Here we do a check that it`s 100 number
print 'Out off %d random number %d was even\nHere are the numbers->\n' % (count_even + count_odd, count_even)
print even_list

'''my output->
Out off 100 random number 44 was odd
Here are the numbers->

[53, 67, 27, 37, 97, 75, 89, 87, 65, 81, 31, 85, 85, 33, 13, 13, 27, 5, 75, 37, 73, 39, 53, 71, 53, 27, 23, 1, 13, 19, 29, 9, 13, 45, 19, 31, 63, 27, 33, 43, 51, 61, 35, 35]

Out off 100 random number 56 was even
Here are the numbers->

[2, 2, 16, 16, 34, 14, 70, 22, 30, 2, 74, 90, 28, 36, 100, 74, 48, 8, 40, 64, 54, 94, 54, 56, 16, 4, 94, 66, 18, 12, 36, 100, 8, 18, 54, 16, 72, 16, 20, 60, 28, 6, 38, 10, 62, 88, 98, 90, 54, 26, 50, 38, 66, 76, 42, 12]
'''
snippsat 661 Master Poster

One more,now start to think how to put this together.

>>> count = 0
>>> a = 55
>>> if a % 2 == 1:
	count += 1
	print 'odd', count

else:
	print 'even'

	
odd 1
>>>
snippsat 661 Master Poster

You should try to post some code yourself.

Can give you some tips.

>>> for i in range(0,7):
	a = random.randint(0,100)
	print a
	
79
21
69
60
28
68
0
>>>
>>> 
>>> 1 % 2
1
>>> 2 % 2
0
>>> 3 % 2
1
>>> 4 % 2
0
>>>
snippsat 661 Master Poster

But how could we test if the given string is pallindrome or not. I need a syntax that returns true if the string is pallindrome otherwise false.

>>> def is_palindrome(s): 
...     return s.lower() == s[::-1].lower()
... 
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True
mn_kthompson commented: Very elegant solution to palindrome problem +2
snippsat 661 Master Poster

Lets break it down.

IDLE 2.6.2      
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in a:
	print i
	
Mary
had
a
little
lamb

>>> for item in a:
	print item
	
Mary
had
a
little
lamb

>>> #So it can be anything you whant(i,item,element.....)
>>> #The for loop iterates over elemen in a

>>> i = 'Mary'
>>> i
'Mary'
>>> i = 'had'
>>> i
'had'
>>> i = 'a'
>>> i
'a'

>>> #So the for loop assigning each element in a to i
>>> for i in range(5):
	print i
	
0
1
2
3
4
>>> len(a)
5
>>> #So the last part that you have combine this 2
>>>
snippsat 661 Master Poster

How did you make those images?

Du you mean the Attached Thumbnails?
Thats just screenshot capture with free program jing.
http://www.jingproject.com/

snippsat 661 Master Poster

like the dir( x ) - really useful

Doc string and help is ok to know about to.

>>> l = []
>>> type(l)
<type 'list'>
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> #Now let get help for method in list class
>>> l.pop.__doc__
'L.pop([index]) -> item -- remove and return item at index (default last).\nRaises IndexError if list is empty or index is out of range.'

>>> #Better to use print because of new line(\n)
>>> print l.pop.__doc__
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.

>>> print l.insert.__doc__
L.insert(index, object) -- insert object before index
>>> #With help
>>> help(l.insert)
Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index

>>> help(l.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

>>>
snippsat 661 Master Poster

Think maybe you are confused about calling a function and calling a method.

def my_func(name, greeting = 'Hello'):
    print '%s, %s' % (greeting, name)    

#Call a function
my_func('tom')  #output <Hello tom>

#-----------------------------------#
class myClass(object):    
    # Inside a class this is called a method
    def my_method(self,name,greeting = 'Hello'):
        print '%s, %s' % (greeting, name)        

a = myClass()  #Class instance

# Call a method
a.my_method('tom')  #output <Hello tom>

So do this.

>>> x = 'a string'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> # Now we se method for string
>>> # And calling a method x.<name of method>
>>> x.upper()
'A STRING'
>>> x.split(' ')
['a', 'string']
>>>
snippsat 661 Master Poster

i just added little spacing here and there to see more easy what im doing.

Always use 4 space for indent.
Read PEP 8.
http://www.python.org/dev/peps/pep-0008/

Tutorial look like it come from sthurlow
http://www.sthurlow.com/python/lesson05/

And some strange code confusing for beginner.

add(raw_input("Add this: "),raw_input("to this: "))

This call function add with 2 argument.

So a more simpler way to understand this.

>>> def add(a,b):    
    print a, '+', b, '=', int(a) + int(b)

>>> a = raw_input("Add this: ")
Add this: 5
>>> b = raw_input("to this: ")
to this: 9
>>> 
>>> # now let us call add() function in a more normal way
>>> add(a, b)
5 + 9 = 14
>>>
snippsat 661 Master Poster

PyQt support python 3.x
http://www.riverbankcomputing.co.uk/software/pyqt/intro

This post has many PyQt example.
http://www.daniweb.com/forums/thread191210.html
There are also example of new function for Tkinter.

Tkinter version that comes with the Python 3.1 installation includes expansion module ttk.
Look at Vegaseat example in link over.

Just as a notice there no problem to have both python 2.x and python 3.x installed.
I use wxpython so i stay with python 2.x for now.
Have off course python 3.x installed to.

snippsat 661 Master Poster

Or if you stay with raw_input,you can convert to integer later in the function.

def add(a,b):    
    print a, '+', b, '=', int(a) + int(b)
    #print '%s + %s = %d ' % (a, b, int(a)+int(b))  # Try this line to

choice = menu() So now choice take take the variable that get returned for menu() function.
So if user choice 1,what will choice be integer or string?

Choose your option: 1

>>>choice = menu()
>>> choice
'1'

Yes it return a string.

Will this line work correct then? if choice == 1:

>>> '1' == 1
False
>>> 1 == 1
True
>>>

So now you now what to change in that line.

how to connect Notepad++ with python.exe but i like notepad++ more than Python GUI)

Use a edtior that that you can just run your code on the fly.
Just paste inn code and push run button.
Pyscripter is god.
http://code.google.com/p/pyscripter/

And use code tag when you post code.

snippsat 661 Master Poster

Look like cx-freeze has come out with a version for python 3.
http://cx-freeze.sourceforge.net/

Or just use python 2.x and python 3., there is no point just to use python 3.x for now.

I will not stay for python 2.x til most of the 3 party modules i use a lot is rewritten for python 2.x eksp:wxpython, p2exe.

I have python 2.5.4 - 2.6 and 3.1 installed,no problem switching between them.

snippsat 661 Master Poster

Hi here are som changes.
Done some work on this,i was thinking making somthing simelar as this for fun.
So helping you a little is no problem,set my self as co-developer in about box if you dont mind.

Here are changes.

----------| Change log |---------

* Change on size and design | New headerpicture

* Take away maximize window (wx.MINIMIZE_BOX)

* Ico for Frame and about box

* New about box style

* Picture buttons

* Bigger message Box and multiline enable(wx.TE_MULTILINE)

* Exception handling on mail sent with new StaticText message

* Better documentation of code

----------| idèe for future development |--------

* Email attachment(file)

* Contact list load

* Save default login

http://www.esnips.com/doc/c2e05e06-508b-4dbd-a678-110819cb05ed/py-mailer

import smtplib
import time
import os
import wx
from wx.lib.wordwrap import wordwrap

window = wx.App()
class pymailer(wx.Frame):
    '''
    Program to send gmail message    
    '''    
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,"Py-mailer",size=(330,520),
                        style = wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX)        
        #----| Window color |---#
        self.SetBackgroundColour("#d8d8bf")       
        
        #---| Add a panel so it looks the correct on all platforms |---#  
        self.panel = wx.Panel(self, wx.ID_ANY)
        
        #---| Ico for window |---#  
        ico = wx.Icon('email1.ico', wx.BITMAP_TYPE_ICO)
        self.SetIcon(ico)
        
        #----| Gmail server |---#
        self.info = {}
        self.s = smtplib.SMTP("smtp.gmail.com",587)
        self.s.ehlo()
        self.s.starttls()
        self.s.ehlo()       
        
        #---| Menu bar |---# 
        menubar=wx.MenuBar()
        filem=wx.Menu()
        filem.Append(201,"Quit")
        self.Bind(wx.EVT_MENU,self.Quit,id=201)
        viewm = wx.Menu()
        viewm.Append(202,"About")
        self.Bind(wx.EVT_MENU,self.About,id=202)
        menubar.Append(filem,"File")
        menubar.Append(viewm,"Help")
        self.SetMenuBar(menubar)        
        
         #---| Picture Buttons |---# 
        self.send = wx.BitmapButton(self.panel,107,wx.Bitmap("py_email1.png"),
                                       pos = (7,430), size = (65,26))
        self.Bind(wx.EVT_BUTTON,self.Send,id = 107)        
        self.login = wx.BitmapButton(self.panel,103,wx.Bitmap("py_email2.png"),
                                       pos …
snippsat 661 Master Poster
>>> import urllib.request, re
>>> from html.parser import HTMLParser
>>> main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000).decode('gb2312')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000).decode('gb2312')
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 1-2: illegal multibyte sequence

It will return none because of error with decode('gb2312')
So the Chinese data encoded GB2312 format give som problem.
Search google python decode('gb2312')

>>> main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000)
>>> main_page
<now it work>

If this give you what you need i am not sure.

snippsat 661 Master Poster

You can set size so the text get overwrite.
And som color look better.

try:
    self.s.login(self.user,self.passw)
    wx.StaticText(self.panel,-1,"Logged in...",pos=(10,200),size = (150,20)).SetForegroundColour('blue')         
except:
    wx.StaticText(self.panel,-1,"Failed",pos=(10,200),size = (150,20)).SetForegroundColour('red')

For me i have to have this put in this lines or it dont work for me.

self.s.ehlo()
self.s.starttls()
self.s.ehlo()

And your design need some work,can give som tips later if you want that.

snippsat 661 Master Poster

And a shorter version that uses the reverse string metod in a smart way.

>>> def is_palindrome(s): 
...     return s.lower() == s[::-1].lower()
... 
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True
snippsat 661 Master Poster
snippsat 661 Master Poster

This is really starting to annoy me

I did this just to show an alternative way of thinking,because you ask about OO.

It is not to put your code down.
One the best way to learn is to get input from other.

So you shoul not be annoyed but rather look at it as a good way to learn.

If someone told me that writing a function for +-*/ rather than use eval() is a good thing for safe code.
I would not argue about that.
Because eval() can be used in a bad way.

>>> eval("__import__('os').remove('file')")
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    eval("__import__('os').remove('file')")
  File "<string>", line 1, in <module>
WindowsError: [Error 2] Systemet finner ikke angitt fil: 'file'

So it get an error that it dont find the file.
If correct path it had removed that file from my system.

The prevent this add __builtins__

print eval("__import__('os').remove('file')", {"__builtins__": {}})
snippsat 661 Master Poster

This code had been better without a class,and this is not the OOP way of thinking.
One function for Addition/Division....... can be shorten by eval()

>>> a = eval('5+8886/45*4554545')
>>> a
899370824.3333334

Here an example with class.

import math
class Calculator(object):
    '''Doc_string info about class'''
    def calculate(self, expression):
        self.value = eval(expression)

    def square(self, sqrt1):
        '''This look like a function,but inside a class is called a method'''
        self.b = math.sqrt(sqrt1)
        
    def __str__(self):
        return self.value
        return self.b

#here a make the method of class short
#and i do user_input and printing outside of the class(you can of course make a menu but not in the class)
a = Calculator()
print('Calculate +-*/ and Square Root')
b = input('values')
a.calculate(b)
print('The sum of %s is %d' % (b, a.value))

c = int(input('Enter Square Root value'))
a.square(c)
print('The square Root of %d is %d' % (c, a.b))

''' my output-->
Calculate +-*/ and Square Root
The sum of 45+78*4545/56 is 6375
The square Root of 25 is 5
'''