[Tutor] War: The Card Game
I am working on the card game of war challenge where each player is given a single card and the highest value wins. I keep getting a Type Error since for the moment since the values of the cards cannot be compared due to their types. I am thinking of creating a Card_Value class that will give each rank and suit a certain value. If there is also a more elegant way of handling some of the code in the main section that will be welcome. http://old.nabble.com/file/p31961149/war.py war.py -- View this message in context: http://old.nabble.com/War%3A-The-Card-Game-tp31961149p31961149.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Card Game
Vincent Balmori vincentbalm...@yahoo.com wrote I keep getting a Type Error since for the moment since the values of the cards cannot be compared due to their types. Please send the complete error text sincethat will tell us where to look etc. I am thinking of creating a Card_Value class that will give each rank and suit a certain value. If there is also a more elegant way of handling some of the code in the main section that will be welcome. You can get cards to compare themselves by adding a few more magic methods. Then you can do stuff like if card1 card2: # elif card2 card1: # else: The methods you need to create are __gt__(), __lt__(), __eq__(), __le__(), __ge__() for ,,==,=,= operations. BTW, In your code you have a comparison using = instead of ==. That will fail. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trivia
Just some programming philosophy. On Fri, Jun 24, 2011 at 3:58 AM, Vincent Balmori vincentbalm...@yahoo.comwrote: Your whole approach is very fragile in this respect, it only takes one small mistake in the data to wreck your program,. Somethjing like a config file format would be much more robust (and readable) the config reader module would make sure you got what you expected back. Can you please explain more on what you mean by this? Alan Gauld wrote: Vincent Balmori vincentbalm...@yahoo.com wrote It's working fine now with the scoring, but now at the end of the program for some reason I get this error message: /Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py, line 27, in next_block point = int(next_line(the_file)) ValueError: invalid literal for int() with base 10: '' Thats because after the last question you try to read another block and don't check anywhere whether you actually read anything. Your next_block code just assumes there will always be valid data there, but at the end of the file there won't be. You get away with category being blank because replace() doesn't complain. But int() does. Your whole approach is very fragile in this respect, it only takes one small mistake in the data to wreck your program,. Somethjing like a config file format would be much more robust (and readable) the config reader module would make sure you got what you expected back. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- View this message in context: http://old.nabble.com/Trivia-tp31917610p31917979.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators
It would be cool if their where decorators that modified decorators. I know its possible, but I can't think of a use. On Thu, Jun 23, 2011 at 11:05 PM, Steven D'Aprano st...@pearwood.infowrote: Robert wrote: Is there a good tutorial out there somewhere about decorators? Google doesn't bring up much. Define good :) I'm interested in what you think about this article: http://www.artima.com/weblogs/**viewpost.jsp?thread=240808http://www.artima.com/weblogs/viewpost.jsp?thread=240808 Personally, I think it's filled with jargon that will be alien to most Python coders, but otherwise interesting. Here's my cheap introduction to decorators... Before you understand decorators, you have to understand two things about Python: (1) Functions are first class objects; (2) and therefore you can write factory functions. Everything else is just a bonus. What I mean by first class is best explained by giving an example of the opposite, second class objects. In some languages, functions are special, and by special I mean they are more restricted. You cannot (easily, or at all) pass a function as an argument to another function, or give it a new name. This makes a lot of code hard to write. For instance, you might want to create a Grapher application, that lets the user draw the graph of some function. The basic algorithm would be something like this: def grapher(function, low, high, step): for x in range(low, high, step): y = function(x) draw_pixel(x, y) # draw a pixel on the graph, somehow... This is easy in Python, but very hard in languages where functions are second class. Because they are second class, you cannot pass them as arguments: grapher(math.sin, 0, 100, 1) is not allowed in some languages, but is allowed in Python. One consequence of this is the idea of factory functions is allowed. You can write a function which builds new functions, and returns them: def factory(x): ... def inner(arg): ... return arg + x ... return inner # return the function object itself ... plusone = factory(1) plustwo = factory(2) plusone(23) 24 Decorators are a special type of factory function. They take as their argument a function, and then modify, wrap, or replace the function to perform special processing. Because the decorator itself is a function, anything you can do in Python, you can do in a decorator. The only limitation is that it must take a single argument, expected to be a function. (Or a class, in newer versions of Python.) Everything else is up to you! Decorator syntax is the special syntax you often see: @decorator def spam(): pass is syntactic sugar for the longer version: def spam(): pass spam = decorator(spam) What are decorators good for? The most common use is to *wrap* the function so as to eliminate boilerplate code. Suppose you have a bunch of functions that look like this: def func(arg): if isinstance(arg, int) and arg 0: arg = min(arg, 1000) do stuff else: raise ValueError('bad argument') def func2(arg): if isinstance(arg, int) and arg 0: arg = min(arg, 1000) do different stuff else: raise ValueError('bad argument') def func3(arg): if isinstance(arg, int) and arg 0: arg = min(arg, 1000) do something else else: raise ValueError('bad argument') All of the functions go through the same boilerplate at the beginning and end, testing for a valid argument, raising an error if not, adjusting the argument value... Only the do stuff parts are different. This is a lot of duplicated code. We can reduce the duplication, making it easier to maintain and test, by moving all the common code into one place: def test_argument(func): def inner(arg): if not (isinstance(arg, int) and arg 0): raise ValueError('bad argument') arg = min(arg, 1000) return func(arg) return inner @test_argument def func(arg): do stuff @test_argument def func2(arg): do different stuff @test_argument def func3(arg): do something else again The common code (the boilerplate) is now inside the decorator. The decorator takes a function as an argument, wraps it with an inner function that calls the common boilerplate code, tests the argument, raises an error if needed, and returns the result of calling the unique do stuff part. -- Steven __**_ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Blackjack Betting
I have been working on another challenge that involves improving the Blackjack program so the players can wager an amount. If a player loses they will be removed from the game. I keep getting the error: “NameError: global name 'bet' is not defined.” I know I came across this error before in a previous thread, but I am confused on how to solve this, since I am also trying to juggle it with inherited methods at the same time. Here is the old and new file for the blackjack program for comparison: http://old.nabble.com/file/p31966195/blackjack.py blackjack.py http://old.nabble.com/file/p31966195/blackjackbetting.py blackjackbetting.py -- View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Copying Files
I was using glob and shutil to copy logs from one location to another successfully, however, I have run into a snag when trying to copy a directory. Not sure how to fix this. Current Code is as follows: for file in glob.glob(/drbd1/monitorcenter/Apps/WEB-INF/*): #This line is holding up the script due to copying a directory and not a single file shutil.copy(file, path_2_b_2) Any ideas? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Conceptual Question About Use of Python for Employee Training Program
What's step 4? On Sat, Jun 25, 2011 at 10:08 AM, Mac Ryan quasipe...@gmail.com wrote: On Sat, 25 Jun 2011 06:18:14 -0700 (PDT) Adam Carr adamlc...@yahoo.com wrote: Good Morning: I am very new to Python but I am enjoying the learning process. I have a question about the application of Python to a problem at the industrial business where I work. My two main questions are: 1. Can Python be used to achieve the goals of the possible project? 2. Where are the best places to look (books, blogs, websites, etc.) for programming examples or modules that would help me begin to assemble and test some code? We currently have a Windows-PC based safety training program that was put together in MS Access around 2001 snip Thanks in advance for taking the time to read my long note. I appreciate any help or direction that can be offered. Hi Adam, from the way you describe your problem, to me the obvious answer would be web application. This way you will be able to: 1. Make sure all employees will use the latest up-to-date training material and software version. 2. Have a central DB able to track employees' activity (this opens up the possibility for extra functionalities like sending a gentle reminder e-mail to those who are not taking tests frequently enough, statistics on what topics employees struggle most with, etc...) 3. Be platform independent. 5. Save time on developing the GUI (which - done properly - is a very time consuming part of desktop projects). That said, python is a great tool for web apps too. I personally looked a bit into Django (www.djangoproject.com), which is one of the python web frameworks and I was impressed by the speed you can prototype a fully working application. As for presenting the training material, for iteration #1 I would simply make them available as a download link. But in following iteration of the project I would also integrate them with the web (so as to make the entire application truly portable. I once used S5 for a project. Here you can see a presentation of it that is - coherentely - done with the standard presented: http://meyerweb.com/eric/tools/s5/s5-intro.html#slide1 However an alternative I did not experiment with is XOXO, which I read has python code examples available (see http://microformats.org/wiki/xoxo-sample-code-python) HTH, Mac. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python GUI
dude, what are all those story comments, did you just edit the mad lib program from Python for Absolute Beginners? On Wed, Jun 29, 2011 at 12:28 AM, David Merrick merrick...@gmail.comwrote: # Guess My Number GUI # Create a story based on user input from tkinter import * import random class Application(Frame): GUI application that creates a story based on user input. def __init__(self, master): Initialize Frame. super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): Create widgets to get story information and to display story. # create instruction label Label(self, text = Welcome to 'Guess My Number'!\n\nI'm thinking of a number between 1 and 100.\nTry to guess it in as few attempts as possible. ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label for body parts radio buttons Label(self, text = Take a guess: ).grid(row = 6, column = 0, sticky = W) self.numberEnt = Entry(self) self.numberEnt.grid(row = 6, column = 1, sticky = W) # create a submit button Button(self, text = Click to see if you got it, command = self.testNumber ).grid(row = 7, column = 0, sticky = W) self.numberTxt = Text(self, width = 75, height = 10, wrap = WORD) self.numberTxt.grid(row = 8, column = 0, columnspan = 4) def testNumber(self): Fill text box with new story based on user input. # get values from the GUI # create the story guess = int(self.numberEnt.get()) tries = 1 while guess != the_number: if guess the_number: number += Lower... else: number += Higher... guess = int(self.numberEnt.get()) tries += 1 # display the text self.numberTxt.delete(0.0, END) self.numberTxt.insert(0.0, number) number += You guessed it! The number was + the_number number += And it only took you + tries + tries!\n self.numberTxt.delete(0.0, END) self.numberTxt.insert(0.0, number) # main number = the_number = random.randint(1, 100) root = Tk() root.title(Mad Lib) app = Application(root) root.mainloop() *Output* Traceback (most recent call last): File I:\Python\programs\guess_my_ numberChapter10.py, line 60, in module number += You guessed it! The number was + the_number NameError: name 'number' is not defined Any ides??? Is my code going to work apart from this problem? -- Dave Merrick merrick...@gmail.com Ph 03 3423 121 Cell 027 3089 169 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipping files and Mysql
/myfiles/my_db/ needs to be a string that right there is trying to divide nothing by the variable called myfiles, divided by my_db, divide by nothing On Mon, Jun 27, 2011 at 3:45 PM, gagnr...@verizon.net wrote: I am trying to write a script that will dump a mysql db and then zip the file. I do know about mysqldb, but I was wondering if there is anything native to the libraries that will allow me to do this without using a seperate piece. Then after I gather the DBs, I need to zip them. I wrote the following, but wanted to know if I am heading in the correct direction. zipfile.zipfile(/myfiles/my_db/, w, zip_stored) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Card Game
I would go with __cmp__ which covers them all. 1 for greater, 0 for equal, -1 for less than. On Thu, Jun 30, 2011 at 5:35 AM, Alan Gauld alan.ga...@btinternet.comwrote: Vincent Balmori vincentbalm...@yahoo.com wrote I keep getting a Type Error since for the moment since the values of the cards cannot be compared due to their types. Please send the complete error text sincethat will tell us where to look etc. I am thinking of creating a Card_Value class that will give each rank and suit a certain value. If there is also a more elegant way of handling some of the code in the main section that will be welcome. You can get cards to compare themselves by adding a few more magic methods. Then you can do stuff like if card1 card2: # elif card2 card1: # else: The methods you need to create are __gt__(), __lt__(), __eq__(), __le__(), __ge__() for ,,==,=,= operations. BTW, In your code you have a comparison using = instead of ==. That will fail. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ __**_ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Blackjack Betting
I keep getting the error: “NameError: global name 'bet' is not defined.” I know I came across this error before in a previous thread, but I am confused on how to solve this, since I am also trying to juggle it with inherited methods at the same time. Telling us this without the stack trace is pretty unhelpful. The Python exceptions include a very good stack trace (with line numbers +- 1 line) and a decent description. This error means that wherever this error was raised was a reference to the name bet and it had no reference to any bet at that point. The reasons could be that you forgot to assign a value to the name first, maybe it was a typo, in a preceding function, forgot the reference to self, etc, etc. I took a *quick* look at the code and found this (I did not check for other problems or if this error happens in more than one place): class BJ_Player(BJ_Hand, Bet): A Blackjack Player. def is_hitting(self): response = games.ask_yes_no(\n + self.name + , do you want a hit? (Y/N): ) return response == y def bust(self): print(self.name, busts.) self.lose() def lose(self): print(self.name, loses.) betting = Bet() bet.stash -= bet.wager def win(self): print(self.name, wins.) bet = Bet() bet.stash += bet.wager def push(self): print(self.name, pushes.) There are a couple things wrong with this class. First, you never define an __init__ which might be technically okay but is unlikely to be what you want for any user defined class (especially one with multiple inheritance). Since there is no __init__ defined, it will call the first parent class BJ_Hand.__init__ but not the second parent class Bet.__init__ (if it has one). Next for BJ_Player.lose(), bet is never defined and thus neither is bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you ran lint/pylint on this module it would have told you the error without even having to run it. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -Original Message- From: tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of Vincent Balmori Sent: Thursday, June 30, 2011 1:49 PM To: tutor@python.org Subject: [Tutor] Blackjack Betting I have been working on another challenge that involves improving the Blackjack program so the players can wager an amount. If a player loses they will be removed from the game. I keep getting the error: “NameError: global name 'bet' is not defined.” I know I came across this error before in a previous thread, but I am confused on how to solve this, since I am also trying to juggle it with inherited methods at the same time. Here is the old and new file for the blackjack program for comparison: http://old.nabble.com/file/p31966195/blackjack.py blackjack.py http://old.nabble.com/file/p31966195/blackjackbetting.py blackjackbetting.py -- View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities.
Re: [Tutor] Copying Files
-Original Message- From: tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of gagnr...@verizon.net Sent: Thursday, June 30, 2011 1:03 PM To: tutor@python.org Subject: [Tutor] Copying Files I was using glob and shutil to copy logs from one location to another successfully, however, I have run into a snag when trying to copy a directory. Not sure how to fix this. Current Code is as follows: for file in glob.glob(/drbd1/monitorcenter/Apps/WEB-INF/*): #This line is holding up the script due to copying a directory and not a single file shutil.copy(file, path_2_b_2) Any ideas? Why not try shutil.copytree instead? Shutil.copytree('/drbd1/monitorcenter/Apps/WEB-INF', path_2_b_2 ) http://docs.python.org/library/shutil.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Card Game
I may be wrong but I thought __cmp__ was deprecated. In fact I thought it was one oof the things removed in Python v3 But I may have just imagined it! :-) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From: Christopher King g.nius...@gmail.com To: Alan Gauld alan.ga...@btinternet.com Cc: tutor@python.org Sent: Thursday, 30 June, 2011 20:43:29 Subject: Re: [Tutor] The Card Game I would go with __cmp__ which covers them all. 1 for greater, 0 for equal, -1 for less than. On Thu, Jun 30, 2011 at 5:35 AM, Alan Gauld alan.ga...@btinternet.com wrote: Vincent Balmori vincentbalm...@yahoo.com wrote I keep getting a Type Error since for the moment since the values of the cards cannot be compared due to their types. Please send the complete error text sincethat will tell us where to look etc. I am thinking of creating a Card_Value class that will give each rank and suit a certain value. If there is also a more elegant way of handling some of the code in the main section that will be welcome. You can get cards to compare themselves by adding a few more magic methods. Then you can do stuff like if card1 card2: # elif card2 card1: # else: The methods you need to create are __gt__(), __lt__(), __eq__(), __le__(), __ge__() for ,,==,=,= operations. BTW, In your code you have a comparison using = instead of ==. That will fail. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Card Game
Christopher King wrote: I would go with __cmp__ which covers them all. 1 for greater, 0 for equal, -1 for less than. So-called rich comparisons using __lt__, __gt__, etc. have been preferred since Python 2.1. The major advantage of them is that they can be used for more complicated data types, e.g. with sets where means superset and means subset: a = set([1, 2, 3, 4]) b = set([2, 3, 4, 5]) a b # a is not a subset of b False a b # neither is it a superset False a == b # and they're not equal either False a b # but they do overlap: set([2, 3, 4]) In Python 2.x, __cmp__ is only used as a fall-back if the rich comparisons aren't defined. In Python 3.x, __cmp__ is gone: even if you define it, it won't be used. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor