Re: [Tutor] Todays Learning Python Question From a Newbie ;)

2006-02-02 Thread Jon Moore
On 02/02/06, Alan Gauld [EMAIL PROTECTED] wrote:
Bob, Write a new computer_move() function for the tic-tac-toe game to plug the hole in the computers stratergy. See if you can create an opponent that is unbeatable!
 My main problem is that I can not see how the computers stratergy can be improved as at best I can only manage a tie with the computer!Does the computer ever go first?Yes if you let it!
Does the computer start with a random location?No, if you look at the code below, it has a predefined set of 'best moves'. 
If yes to the above then the computer can be beaten since the entirecourse of a Tic-Tac-Toe game (or OXO as we call it in the UK!)
depends upon the first move location.Thanks to André, there is a way to win every time if you take the first move (see below), so there MUST be a whole in the computers stratergy! Based on what we all know about the game, I would say that you can not make it so that the computer can win every time, but it should be possable to make it tie.
x: 0o: 4x: 7o: 2x: 6If no to the above then, provided the gameplay is OK, I don't know
what the author means either.Alan G.The code is as follows:# set global constantsX = XO = OEMPTY =  TIE = TIE
NUM_SQUARES = 9# set game instructionsdef display_instruct(): Display game instructions. print \  Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. 
 This will be a showdown between your human brain and my silicon processor.  You will make your move known by entering a number, 0 - 8. The number  will correspond to the board position as illustrated:
  0 | 1 | 2 - 3 | 4 | 5 - 6 | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n
 # set questiondef ask_yes_no(question): Ask a yes or no question. response = None while response not in (y, n):
 response = raw_input(question).lower() return response# set ask numberdef ask_number(question, low, high): Ask for a number within the range response = None
 while response not in range(low, high): response = int(raw_input(question)) return response# set piecesdef pieces(): Determine if player or computer goes first.
 go_first = ask_yes_no(Do you wish to go first? (y/n): ) if go_first == y: print \nThen take the first move. You will need it ;) human = X computer = O
 else: print \nYour bravery will be your undoingI will go first. computer = X human = O return computer, human# create new boarddef new_board():
 Create a new game board. board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board# display the boarddef display_board(board):
 Display the board on the screen print \n\t, board[0], |, board[1], |, board[2] print \t, - print \t, board[3], |, board[4], |, board[5]
 print \t, - print \t, board[6], |, board[7], |, board[8], \n# set legal movesdef legal_moves(board): Create list of legal moves.
 moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves# set winnerdef winner(board): Determine the game winner
 WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8),
 (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board:
 return TIE return None# set human movedef human_move(board, human): Get human move. legal = legal_moves(board) move = None while move not in legal:
 move = ask_number(Where will you move? (0-8): , 0, NUM_SQUARES) if move not in legal: print \nThat square is already occupied. Please choose another.\n print Fine...
 return move# set computer movedef computer_move(board, computer, human): Make computer move. # Make a copy of the board to work with since the function will be changing the list
 board = board[:] # The best positions to have, in order BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print I shall take a square number, # if computer can win, take that move
 for move in legal_moves(board): board[move] = computer if winner(board) == computer: print move return move # done checking this move, undo it board[move] = EMPTY
 #if human can win, block that move for move in legal_moves(board): board[move] = human if winner(board) == human: print move return move # done checking this move, undo it
 board[move] = EMPTY # since no one can win on next move, pick best open square for move in BEST_MOVES: if move in legal_moves(board): print move return move
# set next turndef next_turn(turn): Switch turns. if turn == X: return O else: return X# congratulate winnerdef congrat_winner(the_winner, computer, human):
 Congratulate the winner if the_winner != TIE: print the_winner, won!\n else: print Its a tie!\n if the_winner == computer:
 print As I predicted human, I am triumphant once more. \n \ Proof that computers are superior to humans in all regards. elif the_winner == human: print No! It cannot be! Somehow you tricked me human! \n \
 But never again...I will win next time! elif the_winner == TIE: print You 

Re: [Tutor] Todays Learning Python Question From a Newbie ;)

2006-02-02 Thread Jon Moore
All that does is reverse the hole!?!?x:2o:4x:7o:0x:80:5 O | | X -  | O | O -  | X | X On 02/02/06, 
Wolfram Kraus [EMAIL PROTECTED] wrote:
Jon Moore wrote:[...] Thanks toAndré, there is a way to win every time if you take the first move (see below), so there MUST be a whole in the computers stratergy! Based on what we all know about the game, I would say that you can not
 make it so that the computer can win every time, but it should be possable to make it tie. x: 0 o: 4 x: 7 o: 2^Make this 6,3,8 or 5 and it will be a tie
 x: 6 0 | 1 | 2 - 3 | 4 | 5 - 6 | 7 | 8
Wolfram___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Todays Learning Python Question From a Newbie ;)

2006-02-01 Thread Jon Moore
Hi,Ok its the last exercise in the chapter of the python book (Python for the absolute beginner) I am working my way through.I have been learning about functions using a tic-tac-toe game as an example and I understand it fairly clearly, however the author says the following:
Write a new computer_move() function for the tic-tac-toe game to plug the hole in the computers stratergy. See if you can create an opponent that is unbeatable!
My main problem is that I can not see how the computers stratergy can be improved as at best I can only manage a tie with the computer! If I could see past this, I could hopefully work out the code.
Copy of the function:def computer_move(board, computer, human): Make computer move.
 # make a copy to work with since function will be changing list
 board = board[:] # the best positions to have, in order BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
 print I shall take square number,
  # if computer can win, take that move for move in legal_moves(board):
 board[move] = computer if winner(board) == computer:
 print move return move
 # done checking this move, undo it board[move] = EMPTY
  # if human can win, block that move
 for move in legal_moves(board): board[move] = human if winner(board) == human:
 print move return move
 # done checkin this move, undo it board[move] = EMPTY
 # since no one can win on next move, pick best open square for move in BEST_MOVES:
 if move in legal_moves(board): print move
 return move-- Best Regards
Jon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-02-01 Thread Jon Moore
Thats fine, but what differance does it make?I can see no way that it improves the code.I assume later on when the function is called, it should look as follows:move = ask_number(Where will you move? (0-8): , 0, NUM_SQUARES, 1)
JonOn 01/02/06, Ed Singleton [EMAIL PROTECTED] wrote:
On 31/01/06, Jon Moore [EMAIL PROTECTED] wrote: Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1.
 The function looks like this: def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high):
 response =int(raw_input(question)) return responseTo be honest, this made sense to me.I assumed the author wants youto be able to do the following:ask_number(Give me an even number between 1 and 10, 1, 10, 2)
The solution would be:def ask_number(question, low, high, step=1):Ask for a number within the rangeresponse = Nonewhile response not in range(low, high, step):
response =int(raw_input(question))return responseBut I definitely agree that he said it very, very badly.Ed___Tutor maillist-
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- Best Regards
Jon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Newbie question re. Functions

2006-01-31 Thread Jon Moore
Hi,I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises.The challenge says:Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1.
The function looks like this:def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high):
 response = int(raw_input(question)) return responseThe author has not eluded to 'step values' in anyway that I can see in the proceeding chapters!HELP!-- Best Regards
Jon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-01-31 Thread Jon Moore
I guess I am not going mad then!I will skip this exercise and move on.ThanksJonOn 31/01/06, Alan Gauld 
[EMAIL PROTECTED] wrote:Hi Jon, Improve the function ask_number() so that the function can be called with
 a step value. Make the default value of step 1.If its any consolation that doesn't really mean much to me either.I understand the concept of step value - range() takes one forexample, check the docs.
But how a step value would be used in this kind of user-input scenarioI have no idea!def ask_number(question, low, high):Ask for a number within the range
response = Nonewhile response not in range(low, high):response =int(raw_input(question))return responseThe only possibility I can think of is that the step value is used tonarrow the acceptable range each time round the loop. But given
we don't necessarily tell the user what the range is that would beweird. We'd need to modify question as we go or something.On the assumption you aren't being marked on this I'd justmake up your own mind what it should do and do it! :-)
...and treat it as a good example of a bad statement ofrequirements!Alan G-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-01-31 Thread Jon Moore
I know. Its hard enough for someone like me as it is without things like this complicating it!I have another one for the group, but I will save it for another day ;)I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail.
JonOn 31/01/06, Bob Gailer [EMAIL PROTECTED] wrote:
Jon Moore wrote: Hi, I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises. The challenge says:
 Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this: def ask_number(question, low, high):
 Ask for a number within the range response = None while response not in range(low, high): response =int(raw_input(question)) return response
 The author has not eluded to 'step values' in anyway that I can see in the proceeding chapters!This lights my frustration fire. I wonder whether the author tested thebook?When I worked for a training company I was asked to test a new on-line
course on JCL. I demurred by saying But I don't know JCL.. The replywas that's exactly what we want!So a general recommendation to authors is to have a member of the targetaudience test the book. You Jon have done that but at some cost to you
and those of us on this list.-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-01-31 Thread Jon Moore
DannyMany thanks for that, I notice a few erratas that I am yet to come up against. This will save my sanity (well some of it)1JonOn 31/01/06, 
Danny Yoo [EMAIL PROTECTED] wrote:
On Tue, 31 Jan 2006, Jon Moore wrote: I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail.Hi Jon,I did find errata here:
http://www.muskalipman.com/ptr_detail.cfm?group=Programmingall=1isbn=1-59200-073-8(bottom of the page)
but as far as contact information, I haven't been able to find anything.I do agree the challenege exercise as you've put it seems somewhatnonsensical.*grin*
-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-01-31 Thread Jon Moore
AlanAre you the author of Learn to Program Using Python: A Tutorial for Hobbyists, Self-starters and All Who Want to Learn the Art of Computer Programming?
Is the book still available as a web site?JonOn 31/01/06, Alan Gauld [EMAIL PROTECTED]
 wrote: So a general recommendation to authors is to have a member of the target
 audience test the book. You Jon have done that but at some cost to you and those of us on this list.One advantage of doing my book as a web site first was that I had plentyof testers before committing to print (over 100k visitors). Mind you the
paperversion still had plenty of mistakes but mostly those were typos...Alan G.-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controling my loops and redundant code?!?

2006-01-27 Thread Jon Moore
PaulThe book is called 'Python Programming for the absolute beginner'. It is written by Michael Dawson and published by Premier Press.I have to say that as someone that has no experience in programming what so ever, I am hooked! I need to learn Python for a job I am starting next month and to say I felt a little worried at the idea is an understatement. Since going through the first few chapters of this book (and having the support of this group) I can not wait to learn more!
JonOn 26/01/06, Paul Kraus [EMAIL PROTECTED] wrote:
What book are you working through? That is a pretty interesting exercise.PaulOn Thursday 26 January 2006 12:52 pm, Bob Gailer wrote: At 08:44 AM 1/25/2006, Jon Moore wrote: Hi,
 I have written the program below as an exercise from a book I am working my way through. Objective from book: Write a character creator program for a role-playing-game. The player should be given a pool of 30 points to spend on four attributes: strength,
 health, wisdom and dexterity. The player should be able to spend points from the pool on any attribute and should be also be able to take points from an attribute and put them back in the pool.
 Although the program meets the aim of the exercise set out in the book , there are a couple of things I am not happy with! 1. I am sure I have written far more code than required. Where could I have
 made some shorcuts? 2. Should the user enter a value greater than what is available, the program kicks the user all the way back to the main menu. How could I tidy this up to just loop round to ask the user to try a new value?
 choice = None # Set max number of available points POINTS_POOL = 30 # store attribute values attributes = [[Strength, 0], [Health, 0], [Wisdom, 0], [Dexterity,
 0]] Some ideas to chew on as you develop skills and understanding of programming. Separate the essential data from the code. The essential data are attributes, associated points and max_points. So
 attributes = [Strength, Health, Wisdom, Dexterity] points = [0, 0, 0, 0] MAX_POINTS = 30 In this model the relationship between attributes and points is by
 position. Later you will study and use classes; then the points list will be replaced by a list of class instances, one per attribute. Develop code that operates on these lists to accomplish the various
 objectives. The code itself will never refer to any attribute by name! For example - to list the attributes with their points: for x in range(len(attributes)): print \t,attributes[x], points[x]
 To assign values. Note I separated getting input from converting it to integer so we can see if the user's entry is convertible.: available_points = MAX_POINTS - sum(points) print You have  + available_points +  available.
 for x in range(len(attributes)):cvalue = raw_input(How much would you like to assign to  + attributes[x] +  ?: )) if cvalue.isdigit(): value = int(cvalue)
 else: print Number expected [snip] -- Bob Gailer 510-978-4454--Paul Kraus=-=-=-=-=-=-=-=-=-=-=PEL Supply CompanyNetwork Administrator
216.267.5775 Voice216.267.6176 Faxwww.pelsupply.com=-=-=-=-=-=-=-=-=-=-=___Tutor maillist-
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-26 Thread Jon Moore
KentThanks! I have not come accross string formatting yet, but I can see how the for statement works.How would I modify this to just print either the values or keys?Jon
On 26/01/06, Kent Johnson [EMAIL PROTECTED] wrote:
Jon Moore wrote: Hi Is there anyway to print informtation from dictionaries better than this?: pairs = {Jon Moore: Tony Moore,Simon Nightingale: John Nightingale,
David Willett: Bernard Willet,John Jackson: Stuart Jackson,James Southey: Richard Southey,William Forsythe: Shaun Forsythe}
 print pairs.keys() ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', 'James Southey', 'William Forsythe'] Is there no way to make it a nice list as I want to print the keys and
 values next to each other in a list such as:Of course there is :-) for father, son in pairs.iteritems():... print '%-20s %s' % (father, son)...David WillettBernard Willet
Jon MooreTony MooreJohn Jackson Stuart JacksonSimon NightingaleJohn NightingaleJames SoutheyRichard SoutheyWilliam Forsythe Shaun Forsythepairs.iteritems() iterates over key, value pairs. The string formatting
operations are very handy for formatted output.http://docs.python.org/lib/typesseq-strings.htmlKent Jon MooreTony Moore
 Simon Nightingale John Nightingale David Willett Bernard Willet John Jackson Stuart Jackson James SoutheyRichard Southey William ForsytheShaun Forsythe
 For anyone who is wondering, it is to show father/son pairs. Next is to add grandfathers *eek*. -- Best Regards Jon Moore 
 ___ Tutor maillist-Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Adding items to dictionaries

2006-01-26 Thread Jon Moore
Hi,I have the following dictionary:pairs = {Jon Moore: [Tony Moore, Stanley Moore], Simon Nightingale: [John Nightingale, Alan Nightingale],
 David Willett: [Bernard Willet, Robert Willet], John Jackson: [John Jackson, Peter Jackson], James Southey: [Richard Southey, Paul Southey],
 Shaun Forsythe: [William Forsythe, Angus Forsythe], Daniel Geach: [Mike Geach, Andy Geach]}Where the names represent a son, father and grandfather.
I am trying to add a new term and related definitions to the dictionary, but my code does not seem to work: son = raw_input(Please enter the name of the Son: ) if son not in pairs:
 father = raw_input(Who is the Father?: ) grandfather = raw_input(What is the Grand Father?: ) pairs[son][0] = father pairs[son][1] = grandfather
 print \n, son, ,, father, and ,grandfather, have been added. else: print \nThat Son already exists!The error I get is:
Please enter the name of the Son: Steven BatesWho is the Father?: Alan BatesWhat is the Grand Father?: Master BatesTraceback (most recent call last): File C:\Documents and Settings\Administrator\Desktop\FOO\transfer\whos_your_daddy_and_grandaddy.py, line 65, in ?
 pairs[son][0] = fatherKeyError: 'Steven Bates' Where am I going wrong?-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items to dictionaries

2006-01-26 Thread Jon Moore
KentThanks again. I have a question (see below).On 26/01/06, Kent Johnson [EMAIL PROTECTED] wrote:
Jon Moore wrote: Hi, I have the following dictionary: pairs = {Jon Moore: [Tony Moore, Stanley Moore],
Simon Nightingale: [John Nightingale, Alan Nightingale],David Willett: [Bernard Willet, Robert Willet],John Jackson: [John Jackson, Peter Jackson],
James Southey: [Richard Southey, Paul Southey],Shaun Forsythe: [William Forsythe, Angus Forsythe],Daniel Geach: [Mike Geach, Andy Geach]}
 Where the names represent a son, father and grandfather. I am trying to add a new term and related definitions to the dictionary, but my code does not seem to work: son = raw_input(Please enter the name of the Son: )
 if son not in pairs: father = raw_input(Who is the Father?: ) grandfather = raw_input(What is the Grand Father?: ) pairs[son][0] = father
 pairs[son][1] = grandfather print \n, son, ,, father, and ,grandfather, have been added. else: print \nThat Son already exists!
 The error I get is: pairs[son][0] = father KeyError: 'Steven Bates' Where am I going wrong?The problem is, when you say pairs[son][0] = father
pairs[son] does not yet exist. This is on the left side of anassignment, but it is really an access to pair[son]. It is as if you hadwritten temp = pairs[son] temp[0] = fatherYou get a KeyError accessing pairs[son].
The solution is to create a new list for the (father, grandfather) pair,and assign that to pairs[son]:ancestors = [father, grandfather]pairs[son] = ancestorsYou might want to rethink how you are storing the data. (father,
grandfather) is actually a (son, father) pair so you might want to storethem as another entry in the dictionary. Also two sons could have thesame father and grandfather; with your scheme you will store the
(father, grandfather) pair twice. In general this kind of duplication ofdata is better avoided.Good point, but I have no idea how to do this! Could you show me? 
You might also want to Google 'python genealogy'.Kent___Tutor maillist-Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Controling my loops and redundant code?!?

2006-01-25 Thread Jon Moore
Hi,I have written the program below as an exercise from a book I am working my way through.Objective from book:Write a character creator program for a role-playing-game. The player should be given a pool of 30 points to spend on four attributes: strength, health, wisdom and dexterity. The player should be able to spend points from the pool on any attribute and should be also be able to take points from an attribute and put them back in the pool.
Although the program meets the aim of the exercise set out in the book , there are a couple of things I am not happy with!1. I am sure I have written far more code than required. Where could I have made some shorcuts?
2. Should the user enter a value greater than what is available, the program kicks the user all the way back to the main menu. How could I tidy this up to just loop round to ask the user to try a new value?
choice = None# Set max number of available pointsPOINTS_POOL = 30# store attribute valuesattributes = [[Strength, 0], [Health, 0], [Wisdom, 0], [Dexterity, 0]]
strength = attributes[0]health = attributes[1]wisdom = attributes[2]dexterity = attributes[3]available_points = 30used_points = 0attribute_value = while choice != 0:
 print \  - Character Creator - 0 - Exit 1 - Show Character Attributes 2 - Set Character Attributes
 3 - Reset Character Attributes  choice = raw_input(Choice: ) print # exit option if choice == 0: print Good bye.
 # show attributes option elif choice == 1: print Your attributes are as follows:\n print \t,strength[0], strength[1] print \t,health[0], health[1]
 print \t,wisdom[0], wisdom[1] print \t,dexterity[0], dexterity[1] print \nYou have,available_points,points available.  # edit attributes option
 elif choice == 2: # set strength attribute print \nYou have,strength[1] + available_points,points available. attribute_value = int(raw_input(How much would you like to assign to strength?: ))
 if attribute_value  (strength[1] + available_points): print Error - You do not have that many points available!\n print Please reset the character or assign a value equal\nto or lower than the avaialble points.
 continue strength[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # set health attribute
 print \nYou have,health[1] + available_points,points available. attribute_value = int(raw_input(How much would you like to assign to health?: )) if attribute_value  (health[1] + available_points):
 print Error - You do not have that many points available!\n print Please reset the character or assign a value equal\nto or lower than the avaialble points. continue
 health[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # set wisdom attribute print \nYou have,wisdom[1] + available_points,points available.
 attribute_value = int(raw_input(How much would you like to assign to wisdom?: )) if attribute_value  (wisdom[1] + available_points): print Error - You do not have that many points available!\n
 print Please reset the character or assign a value equal\nto or lower than the avaialble points. continue wisdom[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1]
 available_points = POINTS_POOL - used_points # set dexterity attribute print \nYou have,dexterity[1] + available_points,points available. attribute_value = int(raw_input(How much would you like to assign to dexterity?: ))
 if attribute_value  (dexterity[1] + available_points): print Error - You do not have that many points available!\n print Please reset the character or assign a value equal\nto or lower than the avaialble points.
 continue dexterity[1] = attribute_value used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points # print amount of unused points
 print \nYou have,available_points,unused points. # reset attributes option elif choice == 3: strength[1] = 0 health[1] = 0 wisdom[1] = 0
 dexterity[1] = 0 used_points = strength[1] + health[1] + wisdom[1] + dexterity[1] available_points = POINTS_POOL - used_points print Attributes have been reset.
  # some unknown choice else: print Sorry, but ,choice, is not a valid choice.-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controling my loops and redundant code?!?

2006-01-25 Thread Jon Moore
Alan

Many thanks, that is really useful.

I will go through this a bit at a time over the next few days to ensure I understand what I am doing!

I think functions come in the next chapter!

Jon
On 25/01/06, Alan Gauld [EMAIL PROTECTED] wrote:
Hi Jon, 1. I am sure I have written far more code than required. Where could I have made some shorcuts?
Probably but shortcuts are not necesasarily a good thingif they obscure readability...However one area that would clean it up a bit is if you were touse a dictionary rather than lists for the attributes(see below):
 # Set max number of available points POINTS_POOL = 30Thus duplicates available_points below. You only really need it once...although I see that you modify avail... Might be better to do it by
assigning this constant as the initial value of available_points:available_points = POINTS_POOL # store attribute values attributes = [[Strength, 0], [Health, 0],
[Wisdom, 0], [Dexterity,0]]Use a dictionary here instead:attributes = {'Strength': 0, 'Health':0, 'Wisdom':0, Dexterity:0}strength = attributes[0]
health = attributes[1]wisdom = attributes[2]dexterity = attributes[3]and you shouldn't need these nowavailable_points = 30used_points = 0attribute_value = 
choice = Nonewhile choice != 0: print  -  choice = raw_input(Choice: ) # show attributes option
elif choice == 1: print Your attributes are as follows:\nprint \t,strength[0], strength[1]print '\t Strength', attributes['Strength']
is easier to read I think. # edit attributes optionelif choice == 2:# set strength attribute print \nYou have,strength[1] + available_points,points
 available.print '\n You have', attributes['Strength'] + available_points,'points'Although I personally prefer to use string formatting:print '\n You have %d points', (attributes['Strength'] + available_points)
if attribute_value  (strength[1] + available_points):Since you do the sum twice I'd store the value up topavail_strength = attributes['Strength'] + available_pointsAnd use avail_strength in both the print and comparison.
strength[1] = attribute_valueused_points = strength[1] + health[1] + wisdom[1] + dexterity[1]You can use the sum() function here:used_points = sum(attributes.values())
Also since you are repeating almost exactly the samecode for each attribute you coiuld create a function thattakes the attribute name as a parameter.Have you come across functions yet? If not don't worry
this approach works it just means more typing andmultiple changes to fix things.Hope those points help a little.Alan GAuthor of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld-- Best RegardsJon Moore 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Guess Your Number Game

2006-01-17 Thread Jon Moore
HiI hope someone can help me!I am currently learning
Python using a book by Michael Dawson. In one of the exercises I have
to right a program that will guess a number chosen by the user.It
is partly working, however it does not seem to keep state of numbers
that should have already been ruled out as too high or low.
Any pointers would be very much appreciated!import random print Welcome to 'Guess Your Number'!print \nThink of a number between 1 and 100.print And I will try and guess it!\n
print Valid inputs are: higher, lower and correct.raw_input(\n\nPress enter once you have thought of a number.)# set the initial valuesguess = random.randrange(100) + 1

tries = 1# guessing loopresponse = while response != correct: print Is it ,guess, ?\n response = raw_input () if response == lower:
 guess = random.randrange(1, guess) elif response == higher: guess = random.randrange(guess, 100)# Error message for invalid inputs else: print Invalid entry!
 tries += 1print \nI guessed it! The number was, guessprint And it only took me, tries, tries!\nraw_input(\n\nPress the enter key to exit.)
-- Best RegardsJon-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor