snippsat 661 Master Poster

If you look at this post,i give some example.
http://www.daniweb.com/forums/thread245633.html

snippsat 661 Master Poster

See if this help you.

def colourPicker():
    print "pick four different colours from; red, green, blue, yellow, orange, pink, brown"
    colourList = ["red", "green", "blue", "yellow", "orange", "pink", "brown"]
    chosenColours = []
    count = 0
    while True:            
        colourPicked = raw_input("pick a colour: ")
        if colourPicked in colourList:
            chosenColours.append(colourPicked)
            if len(chosenColours) == 4:  #If length of list is 4 do next line
                break  #For test we use break this is what you will do "return chosenColours" 
            else:
                count +=1
                print 'Color %d is picked and it is %s ' % (count,chosenColours)           
        else:
            print 'Not in list'       
    print chosenColours    

colourPicker()
'''-->output
pick four different colours from; red, green, blue, yellow, orange, pink, brown
pick a colour: ghgh
Not in list
pick a colour: red
Color 1 is picked and it is ['red'] 
pick a colour: green
Color 2 is picked and it is ['red', 'green'] 
pick a colour: pink
Color 3 is picked and it is ['red', 'green', 'pink'] 
pick a colour: brown
['red', 'green', 'pink', 'brown']
'''
snippsat 661 Master Poster

str(raw_input('Enter int: '))

No raw_input return a string,so no need for str .
Input return a integer this is for python 2.x
Or for python 2.x you can use int(raw_input('return integer')) input python 3.x return a string.
Same as raw_input python 2.x
Python 3.x has only input ,not input and raw_input as python 2,x

So therefor is normal to use int(input('enter integer')) to get it to return a integer in python 3.x.

That`s why i did think ffs82defxp used python 3.x
But i get unsure when i did not see this line that only work for python 2.x print range_list for python 3.x off course this print (range_list) So ffs82defxp will clear this upp.

snippsat 661 Master Poster

Are you using python 2.x or python 3.x?
Mine code is for python 3.x,because i did think you used python 3.x.

This line look like you use python 3.x
integer = int(input('Enter an integer here -- > '))

But here here look like you use python 2.x
print range_list

snippsat 661 Master Poster

Dont use set as variable

>>> set
<class 'set'>
>>> print (set.__doc__)
set(iterable) --> set object

Build an unordered collection of unique elements.
>>>

As you see it`s a python build in.

#python 3.x
def range_display(integer):
    my_set = []
    for num in range(0, integer):
        my_set.append(num)  #Dont make a variable inside for loop,you shall just append to my_set
    print (my_set)          #Move this to display result only one time

integer = int(input('Enter an integer here -- > '))  #input 10

range_display(integer)
'''
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
snippsat 661 Master Poster

Anyone have experience highlighting these issues to the right channel?

wxpython-users@googlegroups.com
http://groups.google.com/group/wxpython-users

snippsat 661 Master Poster

You have made a function that dont get passed(and argument) and it dont return anything as your description say.

First the easy way with a build in(sum)

def sum_lst(my_list):
    return sum(my_list)

num = [1,2,3]  
print sum_lst(num)  #6

Here function is passes a list(num) and return the sum.
And i think this is homework,so you may have to use a while loop.

def sum_elements(my_list):
    total = 0
    index = 0
    while index < len(my_list):
        total += my_list[index]
        index += 1
    return total
 
num = [1,2,3]
print sum_elements(num)  #6

Next time use code tag and look more at how argument and return in a function works.

snippsat 661 Master Poster

Change the class little,and show some way to handle data.

import csv

class Reader(object):
    def __init__(self):
        self.names = []
        self.idigit = []
        self.fileReader_list = []       
        self.fileReader = csv.reader(open("survey_result.csv", "rb"))
        self.fileReader_list.extend(self.fileReader)       
        
    def my_sort(self):
        for column in self.fileReader_list:
            self.names.append(column[0])
            self.idigit.append(column[1])       

x = Reader()
x.my_sort()
print 'Name | Number'
print x.names
print x.idigit
print
print 'String'
#make string
s_names = ','.join(x.names)
print s_names
print
print 'Sorted names'
#Sort list
print sorted(x.names)
print
#Make dictionary
my_dict = dict(zip(x.names, x.idigit))
print 'Dictionary'
print my_dict
print
print 'Dictionary test'
#Test dictionary
name = raw_input('Your name to get value: ')
if name in my_dict:
    print 'The value is:%s' % (my_dict[name])

''' my output-->
Name | Number
['Ch', 'Oudfd', 'Sdfdfu', 'Adfn', 'Wodfdf', 'Chdfdng', 'Badfd']
[' Sbb 6748', ' Sufdfdfy 8473', ' Radfdf 5667', ' Mudfmmdfd 4290', ' Yeddfdfon 8066', ' Widfdfn 3325', ' Sadfdf 4742']

String
Ch,Oudfd,Sdfdfu,Adfn,Wodfdf,Chdfdng,Badfd

Sorted names
['Adfn', 'Badfd', 'Ch', 'Chdfdng', 'Oudfd', 'Sdfdfu', 'Wodfdf']

Dictionary
{'Ch': ' Sbb 6748', 'Oudfd': ' Sufdfdfy 8473', 'Chdfdng': ' Widfdfn 3325', 'Adfn': ' Mudfmmdfd 4290', 'Wodfdf': ' Yeddfdfon 8066', 'Sdfdfu': ' Radfdf 5667', 'Badfd': ' Sadfdf 4742'}

Dictionary test
Your name to get value: Ch
The value is: Sbb 6748
'''
snippsat 661 Master Poster

Sure you gone have big problems.
Global variables is a really bad thing,and you have used it a lot.

def la():
    clear()
    global cash, dealers, hp, gang

def foo_sell():
    global cash, dealers

Now cash,dealer is in global namespace.

global cash  #this is global namespace so no need to use global here.
cash = 500
global dealers
dealers = 2

Now do understand why this is a big mess?
This happen many times in your code an make global namespace a big mess off variables.
An important point with function is to keep data local to that function.
Not all variables get thrown out in global namespace.

I am not sure if someone can help you,without rewrite a lot off code.
You shold try to make normal function that takes argument and return data and remove all global.

snippsat 661 Master Poster

This will not work for nested lists.
Example

No problem,kidding this one was not so easy.
Search and think,did find a soultion.

def unshared_copy(inList):
    if isinstance(inList, list):
        return list( map(unshared_copy, inList) )
    return inList

inlist = [1, 2, [3, 4, 5]]
copy_list = unshared_copy(inlist)

print inlist
print copy_list
print
print id(inlist)
print id(copy_list)
print inlist == copy_list
print
inlist[1] = 99
print inlist
print copy_list
print
inlist[2][1] = 33
print inlist
print copy_list
'''
[1, 2, [3, 4, 5]]
[1, 2, [3, 4, 5]]

15060344
15060464
True

[1, 99, [3, 4, 5]]
[1, 2, [3, 4, 5]]

[1, 99, [3, 33, 5]]
[1, 2, [3, 4, 5]]
'''

Have you looked at or tried if deepcopy works for you irh9?
http://www.doughellmann.com/PyMOTW/copy/index.html

snippsat 661 Master Poster

http://docs.python.org/library/exceptions.html
http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm
Use python shell as postet on top.

>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
>>>
snippsat 661 Master Poster

What Is an Exception?

Python uses exception objects.
When it encounters an error, it raises an exception.
If such an exception object is not handled (or caught), the program
terminates with a so-called traceback (an error message)

>>> b

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    b
NameError: name 'b' is not defined
>>>
import exceptions
>>> dir(exceptions)
<list method in exception class>

So let try it out. Version 1

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y 
'''
Enter the first number: 10
Enter the second number: 5
2
'''

Work just fine. Version 2

x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
'''
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
  File "E:\1py\Div\dffddd.py", line 3, in <module>
    print x/y
ZeroDivisionError: integer division or modulo by zero
'''

Here we got an problem,user did divided 10/0.
So what to do now?
We have to catch that exceptions.
You do this with the try/except statement. Version 3

try:
    x = input('Enter the first number: ')
    y = input('Enter the second number: ')
    print x/y
except ZeroDivisionError:
    print "Dont divid by zero!"
'''
Enter the first number: 10
Enter the second number: 0
Dont divid by zero!
'''

Look we used ZeroDivisionError from error message,and now we dont get …

snippsat 661 Master Poster

Two module comes in mind.

Python Win32 Extensions.
http://python.net/crew/skippy/win32/Downloads.html
Tim Golden's excellent WMI.
http://tgolden.sc.sabren.com/python/wmi/index.html

WMI has an excellent way of looking at many hardware settings,
but has limited support for changing many of them.

Try pypi to see if someone has make somthing for this.
http://pypi.python.org/pypi

Maybe better to find a network soultion(something like you have now)
So low level as disabling hardware devices can be a problem,but very few thing are impossible.

snippsat 661 Master Poster

Have make a better menu system.
Put all comment in doc string.

Look at exception handling for your function.
Try type a letter.

def getPints(pints):
    '''The getPints(pints) function:'''
    counter = 0
    while counter < 7:
        pints[counter] = input ("Enter pints collected: ")
        counter = counter + 1
    return pints

def getTotal(pints, pintsTotal):
    '''The getTotal(pints, pintsTotal) function:'''
    counter = 0
    while counter < 7:
        pintsTotal = pintsTotal + pints[counter]
        counter = counter + 1
    return pintsTotal

def getAvg(pintsTotal, pintsAvg):
    '''The getAvg(pintsTotal, pintsAvg) function:'''
    pintsAvg = pintsTotal / 7
    return pintsAvg

def getHigh(pints, pintsHigh):
    '''The getHigh(pints, pintsHigh) function:'''
    pintsHigh = pints[0]
    counter = 1
    while counter < 7:
        if pints[counter] > pintsHigh:
            pintsHigh = pints[counter]
            counter = counter + 1
        return pintsHigh

def getLow(pints, pintsLow):
    '''The getLow(pints, pintsLow) function:'''
    pintsLow = pints[0]
    counter = 1
    while counter < 7:
        if pints[counter] < pintsLow:
            pintsLow = pints[counter]
            counter = counter + 1
        return pintsLow

def dispInfo(pintsTotal, pintsAvg, pintsHigh, pintsLow):
    '''Function to display the information:'''
    print "The total number of pints donated was: ", pintsTotal
    print "The highest number of pints donated was: ", pintsHigh
    print "The lowest number of pints donated was: ", pintsLow
    print "The average # of pints donated was %.2f " % (pintsAvg) #display float with 2 decimal
    return

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

3 days ago you post almost the same question,then i did breake it down.
Did you ever read that?
And this work correctly.
http://www.daniweb.com/forums/thread244170.html

snippsat 661 Master Poster

You have to study and learn the basic of function,now it`s no god.
Run this the first function and understand what is dos.
Here i make sure that number are between 1-6.

import random  #import shall alway be first

def get_user_choice():   
    while True:
        try:          
            user_choice = int(raw_input('Type a number, 1 to 6: '))
            if user_choice <=6 and user_choice >= 1:
                print user_choice   #test print                
                #return user_choice #we return and this exit this function when number is between 1-6
                break  #we break out off loop.                         
            else:
                print 'Numbers most be between 1 and 6'       
        except ValueError:
            print 'Only numbers'    

get_user_choice()

Now with return.
Think of how this work,now this function is returning user_choice.
Then this function has done it`s work

Then you catch that variable in your next function.
To do more work with variable user_choice
def check_if_true( user_choice ):

def get_user_choice():   
    while True:
        try:          
            user_choice = int(raw_input('Type a number, 1 to 6: '))
            if user_choice <=6 and user_choice >= 1:                              
                return user_choice #we return and this exit this function when number is between 1-6
            else:
                print 'Nubmer most be between 1 and 6'       
        except ValueError:
            print 'Only numbers'
snippsat 661 Master Poster

I'm really surprised and disappointed to see that no body has replied even after two days of posting the question... Does daniweb forum slowly losing it's fervour and it's uniqueness???

Maybe because this is a jobb for goolge.

http://diotavelli.net/PyQtWiki
And on this site.
http://www.daniweb.com/forums/thread191210.html

snippsat 661 Master Poster

Most people will not want to download .zip files, it is better if you copy and paste your code between the CODE-tags.

The zip is just the Homework Assignment.
Not a line off code.
I you dont try and show some effort now one will or should help you Nazere.

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

Here i try to break the first class to make it clearer.

Is it the __str__ method using the rank & suit attributes from the __init__ constructor?

Yes __str__ use rank and suite from __init__.
Return a human-readable string.

class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "J", "Q", "K"]
    
    SUITS = ["c", "d", "h", "s"]
    
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        
    def __str__(self):
        '''Returns pleasant string representation of the object'''
        self.rep = self.rank + self.suit
        return self.rep

#First we have to give to argument to __init__
#self as you may know dos not count as an argument(self is the class glue and transport data between methods)
card1 = Card(rank = "A", suit = "c")  #Class instance

print card1.RANKS  #class attributes we can call like this
print "Printing a Card Object"
print card1  #__str__ method at work,dont need to use card.<something>
print card1.rank  #here we access rank
#look i have put self before rep(self.rep)
#Then we can call rep like this to
print card1.rep

'''my oytput-->
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
Printing a Card Object
Ac
A
Ac
'''
snippsat 661 Master Poster
class Critter(object):
    """A virtual pet"""
    
    def __init__(self, name, hunger = 0, boredom = 0):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

crit = Critter('killer')
print crit.name
'''
killer
'''

#Let look at what the class store
print crit.__dict__
'''
{'name': 'killer', 'boredom': 0, 'hunger': 0}
'''
#We only have to pass one argument(name) the two other are default value set to 0
#We can acess default value the same way as name
print crit.boredom
'''
0
'''
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

Animals is always fun to make with oop design in mind.
Here you se __call___ used like this cow('gras')
This fill the the empty list(stomach)

class Animal(object):
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        self.stomach = []        
        
    def __call__(self,food):
        self.stomach.append(food)
    
    def poop(self):
        if len(self.stomach) > 0:
            return self.stomach.pop(0)
        
    def __str__(self):        
        return 'A animal named %s' % (self.name)       
        
cow = Animal('king', 4)  #We make a cow
dog = Animal('flopp', 4) #We can make many animals
print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
print cow  #here __str__ metod work

#We give food to cow
cow('gras')
print cow.stomach

#We give food to dog
dog('bone')
dog('beef')
print dog.stomach

#What comes inn most come out
print cow.poop()
print cow.stomach  #Empty stomach

'''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''
snippsat 661 Master Poster

A more normal way to use __int__ (constructor) in a python class.
And just some point that a class is storeing variables in a dictionary.

from math import sqrt

class ageName(object):
    '''class to represent a person'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
worker1 = ageName('jon', 40)
worker2 = ageName('lise', 22)

#Now if we print this you see that variabls are stored in a dictionary
print worker1.__dict__
print worker2.__dict__
'''
{'age': 40, 'name': 'jon'}
{'age': 22, 'name': 'lise'}
'''

#when we call (key)worker1.name we are getting the (value)
print worker1.name
'''
jon
'''
print sqrt(worker2.age)
'''
4.69041575982
'''
snippsat 661 Master Poster

I have are hard time understand why instructors use outdatet module like graphics.

It has to be much better to learn student basic Tkinter(graphical user interface) or another GUI toolkit.
That is useful othert than education purpose.

And getting help with graphics is hard,because very few has the graphics module.

snippsat 661 Master Poster
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

thx for the help but what does this operation do?"global"?

Global should not be used at all,it`s no good at all.
Learn to code without it.

Here one way to do what you want.

import random 
  
def main(max_guess):     
    num = random.randrange(1, 100) 
    tries = 0 
    guess = "" 
    while guess != num: 
        guess = int(raw_input("Take a guess: ")) 
        if guess > num: 
            print "Too high." 
        elif guess < num: 
            print "Too low." 
        tries += 1 
        if tries >= max_guess: 
            print "Sorry, you took too many guesses. Game Over" 
            exit() 
    print "Congratulations! you did it in %d tries" % (tries)
    again = raw_input("To play again press Enter. Type anything else to quit.") 
    if again == "": 
        main(7) 
    else: 
        exit() 
#We pass in max gusses as an argument  
main(7)
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

Have you tryed som yourself,and mayby post some code.
Can take a little about this but next time dont expext to get help if you dont but some effort in to this.

>>> lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
>>> dir(lst)
['__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']
>>> help(lst.remove)
Help on built-in function remove:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.

>>> lst.remove('apples')
>>> lst
['bunnies', 'animals', 'fruit', 'amsterdam']
>>> #To remove item in a list by index use del
>>> lst.index('fruit')
2
>>> del lst[2]
>>> lst
['bunnies', 'animals', 'amsterdam']
>>>

One commen way to remove items for a list is to iterate over list and remove stuff.
This also made opp for some commen mistake.
Let look at this.

lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
for item in lst:
	if item[0] == 'a':
            lst.remove(item)
print lst
'''my ouyput-->
['bunnies', 'animals', 'fruit']
'''

This is wrong it dont remove 'animals' that has 'a' as item[0]
This is because index get wrong, if you not first make a copy of that list.

>>> lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
>>> new_list = lst[:]
>>> new_list
['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']

Then we …

snippsat 661 Master Poster

The reason why I need GOTO is because the user is going to finish calculating their equations rather quickly and the program will need to loop back into it's original state (the menu screen).

There is no goto int python and thank god for that.
In python you use loop/ function calls or and OOP design with classes to get where you whant in your code
This depend of how you design your program.

Think is better to show you and example than start edit you code.
Run this and you see it always loop back to menu.
Also shown you some ways to handle input error by user.
Use else and loop back one way and read about exception handling in python.
Try to understand what going on in this code,ask question if you not sure.

def add():
    '''Multiplication off numbers'''
    while True:
        try:
            my_add = input('Enter three  number to add use + : ')
            n1, n2, n3 = my_add.split('+')
            my_sum = (float(n1) + float(n2) + float(n2) )
            print('The sum is:', my_sum)
            break
        except ValueError:
            print ('Numbers only and use 2+2+2 format ')

def multicalulate():
    ''' just to show eval method'''
    my_exp = input('Enter and expression ')
    print ('The sum of expression is ', eval(my_exp))

def somthing():
    '''You can add many function and control it in main'''
    pass

def main():
    '''Main menu and info '''
    while True:
        print ('Welcome to my menu\n')
        print ('(1) Multiplication ')
        print ('(2) multicalulate')
        print ('(q) …
snippsat 661 Master Poster

There are several problems.

if number == '1' : #use '1'because input in python 3 return a string.

Then you come to this meny.

print ('1. Operating expense')
print ('2. Payroll expense')
print ('3. Charity Support')
print ('4. Cancel')
number = input ('Enter the Expense you want to add.')

And if choice 1 here,it will off course bring you back to start meny.
because off no if number == '1': do somthing

You use number several time as a variable,dont you think it will be overwritten?
number = input ('Enter the Expense you want to remove.')
number_Expense = (better)

Your first desgin look better.

if user_inp == '1':
    addExpense()

Then make calulation in addExpense() and return value you need.
Then in a main() function but it all together.

snippsat 661 Master Poster

As Mathhax0r take upp your code is really not god at all it`s a big mess.
I think helping you now is difficult because of your code design.

Never use global variabels like this, or at all.
The are ugly an as code grow the will give a lot of problems.

Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
When you use global like this you are pollutioning the global namespace

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

I just need help with how i could give an error message to the user if they enter a string instead of a integer...

You can use a dictionary like this.
Now user can only input 123 to get past meny, anything else give error message and loop back.
Yes more easy for user to just type a number than write rock,paper........everytime.

import random

choices = {'1': 'rock', '2': 'paper', '3': 'scissors'}
choice_comp = ['rock', 'paper', 'scissors']

while True:
    choice = input("please enter your choice | 1:rock 2:paper 3:scissor")
    if choice in choices:
        print (choices[choice])  #test print
        print (type(choice))     #se what input returns,you can make it a integer later if you need that
        break                    #and break out of the while loop
    else:
        print("Invalid choice '{0}'.".format(choice))
        print('Possible values are 1-2-3')


comp = random.choice(choice_comp)  #comp
human = choices[choice]            #human

print ("Comp: %s\nHuman: %s" % (comp, human)) #test print

#now figuere out how to define winner