R˙ffffe9veill˙ffffe9 wrote:
Hello,

I have just started doing the python tutorials and i
tried to modify one of the exercises, it has to to
with defining functions.


I wanted the user to be able to enter an option and
then get a print of the selected option. I also wanted
to have an exit for the user.

As it is, your code throws an exception for me (temp.py contains your code):

$ temp.py
Traceback (most recent call last):
  File "D:\Steve\temp.py", line 24, in ?
    menu()
NameError: name 'menu' is not defined

So, I dedented the "def menu" line, which solved the above NameError and gave me a new exception:

$ temp.py
 GOALS IN...
____________________
1.Pick up
2.Python Programming
3.Overall
4.Motivation
5.Exit
____________________
Traceback (most recent call last):
  File "D:\Steve\temp.py", line 27, in ?
    while choice != 5:
NameError: name 'choice' is not defined

So, at the beginning of the while loop, 'choice' is not yet defined. So let's define it:

choice = 1
while choice != 5:
    ...

$ temp.py
 GOALS IN...
____________________
1.Pick up
2.Python Programming
3.Overall
4.Motivation
5.Exit
____________________
Pick a number:2
To create a programme ...
Pick a number:1
To have a ...
Pick a number:5
Bye

Seems to be working now. Moral of the story here is that posting the exact text of the error you got is the best way to get an answer quickly -- the experienced Python programmers on this list can quickly tell you what the problem is if given enough information.

As a side note, I would probably write your code as:

print ' GOALS IN... '
print '____________________'
print '1.Pick up'
print '2.Python Programming'
print '3.Overall'
print '4.Motivation'
print '5.Exit'
print '____________________'

def choice_iter():
    while True:
        choice = int(raw_input('Pick a number: '))
        if choice == 5:
            break
        yield choice

def PU():
    print 'To have a ...'

def Python():
    print 'To create a programme ...'

def overall():
    print 'To make .....'

def motv():
    print 'I know you can do it!'

selections = [PU, Python, overall, motv]
for choice in choice_iter():
    selections[choice - 1]()
print 'Bye'

This cleans up the program logic in two ways:

(1) The iteration over user input is modularized into the choice_iter function. This separates the code reading input from the user from the code calling the specified functions.

(2) Rather than an set of if-else statements, I put the functions to be called into a list, and use the integer selected as an index to this list.

HTH!

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to