snippsat 661 Master Poster

If you want to open notepad.
You can use the os module.

import os
os.system('start notepad.exe')

#Open a webpage
os.system('start iexplore.exe http://www.google.com')
snippsat 661 Master Poster

Take copy or type correct.
You have type wrong here. b = ''.join(a) ---> b = ' '.join(a) Rember space. ' '

snippsat 661 Master Poster

You can do it like this.

>>> s = '491 43140113108107 11210'
>>> s
'491 43140113108107 11210'

>>> def splitCount(s, count):
    return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])] 

>>> a = splitCount(s, 3)
>>> a
['491', ' 43', '140', '113', '108', '107', ' 11', '210']
>>> b = ' '.join(a)
>>> b
'491  43 140 113 108 107  11 210'
snippsat 661 Master Poster

Not quite sure what You mean,but here are som min/max method that can help

>>> a = min([0,7],[100,25],[150,59],[300,189])
>>> a
[0, 7]
>>> b = min(a)
>>> b
0

>>> c = max([0,7],[100,25],[150,59],[300,189])
>>> c
[300, 189]
>>> d = max(c)
>>> d
300

#same with max
>>> list_of = ([0,7],[100,25],[150,59],[300,189])
>>> for item in list_of:
	min(item)
	
0
25
59
189

>>> list_of = ([0,7],[100,25],[150,59],[300,189])
>>> def flatten(list_of):
	for item in list_of:
		for element in item:
			yield element
			
>>> a = list(flatten(list_of))
>>> a
[0, 7, 100, 25, 150, 59, 300, 189]
>>> print min(a), max(a)
0 300
>>>
snippsat 661 Master Poster

Not much help to give you without solving it.
Look a little on this.

>>> km = raw_input('How many km? ')
How many km? 100
>>> km
'100'
>>> #As you see km is now a string
>>> type(km)
<type 'str'>
>>> #make intreger
>>> int(km)
100
>>> #100 * ??? what mystery number give miles?

For python 2.x use always raw_input(and convert to what you need)
Python 3.x has only input same as raw_input(it return a string too)

snippsat 661 Master Poster
snippsat 661 Master Poster

I been using komodo ide for some years now.
Been happy with it,works fine for wxpython/pygame not that you need own ide for that.
http://www.activestate.com/komodo/

Two very good free editors is.
http://code.google.com/p/pyscripter/
http://code.google.com/p/ulipad/

snippsat 661 Master Poster

Why do I have to specify 'self' while defining the function? I usually don't do it if the function isn't in a class, then why if it is in a class

In a class a function is called a method.
An example.

class SimpleClass(object): 
      
  def SayHello(self, string):
    '''
    * This is a function,but in a class it is called a method
    * Self is the class glue,and it also transport data between metods
    * Think of self as a carrier
    '''
    print 'Hi,' + string + ' nice to see you'
    
make_object = SimpleClass()  #Class instance
make_object.SayHello('Tom')  #Call method,we give one argument(self dont count)

'''
output-->
Hi,Tom nice to see you
'''

global a
a=1

class myThread(threading.Thread):
def run(self):
print(a)
a+=1global a
a=1

class myThread(threading.Thread):
def run(self):
print(a)
a+=1

a = 1 is in the global namespace(scope)
Then global a is doing nothing.

Maybe is better to take away threading and try to understand how classes work first?

snippsat 661 Master Poster

Dont think you can call print,have you done that before?

In Python a callable is an object which type has a __call__ method:

def test():
    print 'hi'

>>> dir(test)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

>>> callable(test)
True

>>> a = 5
>>> dir(a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> callable(a)
False
>>>
snippsat 661 Master Poster

But the problem in bumsfeld's method is that if the number I enter is huuge, then the simplified one itself be two or three characters length..so then how do I go about it?

This will work for adding integer together.

while True:
    total = sum([int(x) for x in raw_input('Enter integer')])
    if total <= 9:
        print 'Less than 10'
        break
    else:
        print total

Python has a build in function "eval"
Eval evaluates a Python expression and returns the
resulting value.

>>> eval(raw_input("Enter an arithmetic expression: "))
>>> Enter an arithmetic expression: 8/2*25-258+5896
>>> 5738
while True:
    total = eval(raw_input("Enter an expression: "))
    if total <= 9:
        print 'Less than 10'
        break
    else:
        print total
snippsat 661 Master Poster

That`s a other problem,now u are returing x.
And x is in your code is alway returing 0.

Copy my code in post #2
Run it,and u get a NameError
Take away # before global.
And now is "p" calulatet correct outside the function.

Then u start to work on "x" and why it always return 0.

snippsat 661 Master Poster

No, it doesn't show any error.

yes it dos.
To make it simple.

def test():
    # global a
    a = 5

test()
print a

This gives a NameError.
Are you using any python ide editor?

snippsat 661 Master Poster
def reduce():
    # global p
    s = raw_input("Enter a number: ")
    x = int(s)
    p = 0
    for i in s:
        p += x % 10
        x = x / 10
    return p, x   
    
reduce()
print p

Why are we getting a NameError now?
Take away # and use the not so popular global.

Read a little about local and global scope in python.

snippsat 661 Master Poster

mean also downgrading the python version just to use a different toolkit, only to be regraded later when wx works with v3 and then i reupgrade.

There is now upp and downgrade in python.
Most off us you 2.x,that dosent mean that we dont test python 3.x out.
Have off course both 2.x and 3.x installed.

There are to much info and 3 part modules one need to only use 3.x
And most books are for 2.x

When learing 2.x you do off couse learn 3.x,they changes arent that big.

You can use 2to3 module for covert code from 2.x to 3.x
That`s work fine,but not needed more for test to see the difference.

One day all will use 3.x,but why hurry?

If one only use 3.x will this not give any advances in the future?
No not at all,because all info about learing this great language is in 2.x
This is info man for sure need.
They changes are way to small to trow that info away.

snippsat 661 Master Poster

That ought to work!

Not work maybe typeError.
'a' iterarte throught the list,then you have to compare 'a ' == 'pear' Now you compare l with 'pear'

>>> l=['apple','orange','mango','pear','strawberry']
>>> l == 'pear'
False
>>>
l = ['apple','orange','mango','pear','strawberry']
for a in l:
    if(a == 'pear'):
        l.remove(a)       

print l
snippsat 661 Master Poster

if __name__ == '__main__':

It`s a very commen ting to use in pyhon.
You can take it away make no diffrence.
it's in use when you save your program an want to import it.
http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm

Just to make it very clear what it`s dos.
Save my kode as menu.py (menuloop program)

Now copy this file an run it.

import menu  # menu.py

def test(input_name):
    print 'Hi!' ,input_name
    while True:
        a = raw_input('What to play a game? ')
        if a == 'yes':
            menu.menuloop()  # Call my menuloop program          
        else:
            exit()    

test('Roy')

Now it run correct first it run my new code and when a call menuloop() it run that after.

Take away __name__ == '__main__': Run the same.
Now menuloop() start before my new code.
Now you understand what if __name__ == '__main__': dos.

snippsat 661 Master Poster

I am not sure I fully understand, I know if I misstype things it will error

If someone misstyping,there are 2 options.
You write in code that handlig excepitons.
Or you try to write code that dont need excepiton handling.
Like i did in my example.
http://docs.python.org/tutorial/errors.html

Sure you can get this to work,but i have to say your code is somewhat messy.
But try to write a game like this you are learing many thing.

snippsat 661 Master Poster

Still some errors.

Game are looping on one menu.
Give global error on gold.
If you type wrong an exception is trown(NameError)
Try to avoid to use global so much.

Saw you gave opp classes.
That ok,but you can better with your loop-functions design than it is now.

Just a tips on how to design a menu-system with function and loop.

Try to type wrong,you get a warning and get back to menu.
You dont need to put in code to handle exeptions.

def test1():
    '''Info about function'''    
    print 'My code'        
    raw_input("\nTrykk enter for meny")
     
def test2():
    '''Info about function'''    
    print 'My code'  
    raw_input("\nTrykk enter for meny")
    
def menuloop():
    '''Info about function''' 
    while True:               
        print 'Welcome to my menu\n'
        print '(1) Choice 1'
        print '(2) Choice 2' 
        print '(q) Quit' 
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            test1()
        elif choice == '2': 
            test2() 
        elif choice == 'q': 
            exit() 
        else: 
            print 'Not a correct choice:', choice    

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

You can try this.
Test script from Ene Uran.

# use Tkinter's file dialog window to get
# a file name with full path, you can also use
# this to get filenames for a console program
# askopenfilename() gives one selected filename

# with Python25 use ...
#import Tkinter as tk
#from tkFileDialog import askopenfilename

# with Python30 use ...
import tkinter as tk
from tkinter.filedialog import askopenfilename

root = tk.Tk()
# show askopenfilename dialog without the Tkinter window
root.withdraw()

# default is all file types
file_name = askopenfilename()

print(file_name)
snippsat 661 Master Poster

Try this.

>>> import tkinter as tk
>>> print(tk.filedialog.__doc__)
File selection dialog classes.
Classes:

- FileDialog
- LoadFileDialog
- SaveFileDialog

This module also presents tk common file dialogues, it provides interfaces
to the native file dialogues available in Tk 4.2 and newer, and the
directory dialogue available in Tk 8.3 and newer.
These interfaces were written by Fredrik Lundh, May 1997.

# Give you a list of method under tk
>>>dir(tk)
snippsat 661 Master Poster

Can you make a new post with same question sab786.
If you have som code or how output list look,post that.

It`s not good forum behavior in any forum to hijack thread with new question.

snippsat 661 Master Poster

When take out data from a dictionary order is not important.
But here is a soultion.

>>> a_dict = {'2':12354, '1':12355432, '4':35342, '3':858743}
>>> sorted(a_dict.items(), key=lambda (v,k): (v,k))
[('1', 12355432), ('2', 12354), ('3', 858743), ('4', 35342)]
>>>
snippsat 661 Master Poster

You can pass value in as argument.

new = raw_input('Enter name: ')

class Test(object):
    def __init__(self,value):
        self.value = value

x = Test(new)
print x.value

'''
output-->
Enter name: hi
hi
'''
snippsat 661 Master Poster

Here is a class you can look,with some basic function of a class.
Paulthom12345 has a good eksample how a class can inheritance from other class.

Just little fix to Paulthom12345 code.
Shape.__init__(name)
change to
Shape.__init__( self, name )

class SimpleClass(object):
  '''Doc string info about class'''
  
  # Class attributes as you see this is variables
  # They the belong to a class therefor name 'attributes' 
  x = 5
  y = 10
  s = x + y
  
  def __init__(self, string):    
     '''
     * Self is the class glue,and also transport data between methods
     * When you make_object 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 without self          
   

# Run one and one line understand whats happens    
make_object = SimpleClass('I am an argument')  # Class instance
#make_object_new = SimpleClass("argument from new object")  # New class instance 

#make_object.SayHello('This is Python and i like it')
#make_object_new.SayHello('Object_new like python to')

#make_object.data_get()

#print make_object.x
#print make_object.s
#print make_object_new.y

#print make_object.__doc__
#print help(SimpleClass)
snippsat 661 Master Poster

Works fine for me to.
Testet 2.5.4 and 2.6.2 wxPython 2.8.

snippsat 661 Master Poster

Here i make a copy of the list,then iterating over it.
It is not a good ideƩ to delete/add somthing from a list you are iterating over.
The solution is to make a copy or new list.

mylist = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']

for item in mylist[:]:
	if item[0] == 'a':
            mylist.remove(item)
print mylist

'''
output--->
['bunnies', 'fruit']
'''

This maybe easyer to read.

lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
    
new_lst = []
for item in lst:
        if item[0] != 'a':
            new_lst.append(item)
print new_lst

'''
output--->
['bunnies', 'fruit']
'''

Or maybe a more elegant solution with a function

def list_remove(item):   
        if item[0] == 'a':
            return False
        return True
    
lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
lst1 = [item for item in lst if list_remove(item)]
print lst1

'''
output--->
['bunnies', 'fruit']
'''
snippsat 661 Master Poster
import math

>>> intensity = 1*(10**12)
>>> intensity
1000000000000L

>>> y = math.sqrt( intensity / (1.327*(10**13)) )
>>> y
0.27451402562301408
snippsat 661 Master Poster

TypeError: argument 1 must be a string or read-only buffer, not list

readlines()--> return a list.
Convert list to sting.

>>> my_file = open('test1.txt', 'r')
>>> x = my_file.readlines()
>>> x
['1e+12']
>>> type(x)         # use this to find out what datatype you are dealing with
<type 'list'>
>>> y = ''.join(x)  # list to string
>>> type(y)
<type 'str'>
>>> y
'1e+12'
>>> finish = y.replace('e+',  '*(10**') + ')'
>>> finish
'1*(10**12)'

Or use a for loop.

my_file = open('test1.txt', 'r')
x = my_file.readlines()

for item in x:
    item
    
finish = item.replace('e+',  '*(10**') + ')'
print finish

'''
My output--->
1*(10**12)
'''
snippsat 661 Master Poster

Se if this help.

>>> a = '1e+12'
>>> a
'1e+12'

>>> b = a.replace('e+',  '*(10**') + ')'
>>> b
'1*(10**12)'
snippsat 661 Master Poster

Somthing like this.
readlines() return a list,so we just use join().
Something with a for loop should also be possibly.
See if this solve it.

>>> my_file = open('test.txt', 'r')
>>> x = my_file.readlines()
>>> x
['AATTCCGGTTT\n', 'CCTTAACCCCC']
>>> y = ''.join(x)
>>> y
'AATTCCGGTTT\nCCTTAACCCCC'
>>> finish = y.replace('\n', '')
>>> finish
'AATTCCGGTTTCCTTAACCCCC'
>>>
snippsat 661 Master Poster

Hi see if this help you.

>>> str_input = '''AATTCCGGTTT
CCTTAACCCCC'''
>>> str_input
'AATTCCGGTTT\nCCTTAACCCCC'
>>> x = str_input.replace ('\n', '')
>>> x
'AATTCCGGTTTCCTTAACCCCC'
>>>