Re: [Tutor] Objects C++ vs Python
That clears it up to an extent. On Thu, Jun 9, 2011 at 11:31 AM, Steve Willoughby wrote: > The value 5 is an integer-class object. But now what is "Integer-class"? Isn't integer a data type? I mean there is no concept of "classes" in C, and yet in C, we can write int x = 5; Will "5", then be called an integer class object? What exactly is a class now? I thought is a collection of variables and (or) associated functions. Am I missing something here? -- Regards, Ashwini ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects C++ vs Python
On 08-Jun-11 22:38, Ashwini Oruganti wrote: I'm trying to learn Python, and know C++. I have a slight confusion regarding the meaning of "object" in python. Here's what I've concluded so far: When we say "object" in C++, it means an instance of a class. e.g. This is true in both Python and C++. int x;// x is NOT an object, it is a *variable* You're confusing variables and the things they hold. x here is a variable which contains an "int" type value. Another variable might hold a pointer to an object. while in python, from what i've understood so far, >>> x=5 implies that there's a memory allocation (called object) that holds the value 3, and "x" is the variable (or name) that is used to refer to it. Maybe this will be more clear: The value 5 is an integer-class object. Full stop. Don't even go down the road of thinking of "memory allocation" (yet). It's an object floating around in Python's runtime somewhere. x is a name you gave to that object for now, so you can refer to it somehow. The big difference is that variable names in Python are really just names for objects (something like pointers/references in C++ but a lot easier to work with), while in C++ they refer to specific memory locations, which must be the right size for what you store into them. Since Python is just naming objects, there is no such problem. That has nothing to do with what an "object" means. So does the term *Object * change its meaning when we shift the context from C++ to python?? This is a little confusing, can someone clear it up?? Not really. I think your confusion was about variables. -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Objects C++ vs Python
I'm trying to learn Python, and know C++. I have a slight confusion regarding the meaning of "object" in python. Here's what I've concluded so far: When we say "object" in C++, it means an instance of a class. e.g. class x{...}; x ob1; // here ob1 is an object. but, for; int x;// x is NOT an object, it is a *variable* while in python, from what i've understood so far, >>> x=5 implies that there's a memory allocation (called object) that holds the value 3, and "x" is the variable (or name) that is used to refer to it. Further, in python, *everything *is an object, while in C++, only*instances of a class * are called objects. So does the term *Object * change its meaning when we shift the context from C++ to python?? This is a little confusing, can someone clear it up?? -- Regards, Ashwini ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lxml.html
nitin chandra wrote to me off-list. I've taken the liberty of returning the conversation to the mailing list. Hi, ERROR [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback (most recent call last): What is all this extraneous date/error/ip address nonsense in the traceback? Where does it come from? This error statement comes from Apache Error Logs. Python / WSGI / apache. In future, please strip that extraneous noise before posting, thank you. TypeError: cannot concatenate 'str' and 'NoneType' objects I am extracting form field name / value from an html, but then it gives the above error and does not display the value of the variable 'name' entered in the respective form. What is the value of the variable 'name'? Value entered in the form is 'admin' I didn't ask what the value entered in the form is. Where does the form go? Where are you looking? Are you sure you're looking in the right place? You're looking at a file /home/dev/wsgi-scripts/index.py and trying to extract XML from that file. What's inside that file? Hint: read the error message that you get when you try to concatenate a string with the None object: "spam" + None Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'NoneType' objects Did this gives the same error... now the question is how do i NOT face the same error.? By making sure that the variable name actually contains a name. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Q
On Wed, Jun 8, 2011 at 3:25 PM, Vincent Balmori wrote: > In the "Loop of Game" section of my code for some reason it gives me five > more chances than I wanted it to. When I put two as the chance limit, it > allowed seven. Also, the program will always say "yes" to any letter I > enter, even if it's wrong. Let's take a look. I'll comment on a few parts that aren't the cause of your problems. > WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") > # pick one word randomly from the sequence > word = random.choice(WORDS) > # create a variable to use later to see if the guess is correct > correct = word I'm unclear on the purpose of this step. You never again use word, so why have correct and not just use word? > LETTERS = None > if correct == "python": > LETTERS = "python" LETTERS always ends up == correct (and thus == word). Why not just use correct (or word)? > chances = 0 > while chances < 5: > guess = input("Does the word have a: ") > for letter in correct: You are looping over every letter in correct. Why? Don't you just want to loop over my 5 chances? > if letter.lower() in LETTERS: Here's your other issue. What is letter? Based on your for loop, it's one of the letters in correct. What test do you actual intend to do here? Say it in english and the python code should be fairly obvious. > print("\nYes") > chances += 1 > guess = input("\nDoes the word have a: ") > else: > print("\nNo") > chances += 1 > guess = input("\nDoes the word have a: ") Just as a tip you've got a lot of repetition here. If you move the "chances" line and "guess" line outside of the if/else, your program will be shorter and cleaner. > print("\nYour chances are up!") You want this to occur when your chances are up, right? So why is it _inside_ the while loop? Your basic approach is fine, you just have some extra stuff going on unnecessarily and I'm guessing it's confused you as to your logic. Give it another shot and let us know how it goes. -- Brett Ritter / SwiftOne swift...@swiftone.org ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question with 's'.format()
wrote 'first={0}, last={1}, middle={2}'.format(*parts) "first=S, last=M, middle=['P', 'A']" why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: The * tells Python to unpack parts and treat the contents as individual values. format is looking for 3 values. Without the * it sees one, a tuple and complains about insufficient values. If it did try to do the format you would wind up with something like: "first=(S,M,['P', 'A']) last=None, middle=None" Python can't tell automatiocally whether you want the tuple treated as a single value and youu just forgot the other two or if you want the tuple unpacked. The * says unpack this value. 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] Copying a mutable
"Válas Péter" wrote > really care if the two names are bound to same object, or just to > two > objects that happen to have the same value. Being one of the purposes of Python to be a simple educational language, I want to make this simple to a beginner who does care. :-) That's good. But the fundamental precursor to explaining it is to explain the concept of an object. Because everything in Python is an object. If you don;t explain the concept of an object the beginner will never understand the different behaviours. There is nothing unusual in this, other object oriented languages require the same fundamental comprehension of objects. (eg Smalltalk - alsdo a language developed to teach beginners - indeed children - about programming.) My question is: how would you explain the different behaviour of a list and a tuple for a beginner? By explaining what immutability means and that some objects are mutable (the objects are changed in place) and others are not (new objects of the same type but with different values are created) - and that's just how it is... Every language has some core concepts that need to be addressed early in the learning experience. (Like the idea of maxint in C and Pascal say...) Python's data model and concept of mutability is one such concept. This is another point the beginner may be confused: multiple assignments. Frankly I never use those with beginners. They are syntactic sugar and never needed. If a beginner comes across them somewhere then I explain them. But they are an idiom best picked up by osmosis IMHO. As far as I understand, assignment means giving a value to a variable which is the expression used by classical languages and in math where the terms originated. variables (such as Pascal or Basic). Python has no variables, Python does have variables but the implementation model is different to languages like C and Pascal where they map to memory locations. But compared to Lisp and Smalltalk (both heavily used as teaching languages) Python is semantically very similar. since even the simpliest data is an object, but we still say assignment, Exactly, provided we have explained the concept of objects and that everything is an object, then assignment is simply the associating of a name with an object - a very simple and consistent concept for a true beginner. It's the folks who come with a load of mental baggage from other, memory mapped, languages that have the problems because they are trying to force Python's model onto their preconceived notions of variables. If you come from a clean slate with no previous knowledge Python's model is simple and consistent. In this sense, if I say, "assignment" is a subset of "binding", No because binding has a specific meaning in relation to classes and object instances. Assignment in Python is a form of name association not binding. 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] String formatting question with 's'.format()
I see now, that example helps. Basically I use one asterisk to extract a list or a tuple and double asterisks for a dictionary, but I have to provide keys in case of a dictionary, like here: >>> template = '{motto}, {pork} and {food}' >>> a = dict(motto='spam', pork='ham', food='eggs') >>> template.format(**a) 'spam, ham and eggs' Thanks for clearing things up. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question with 's'.format()
From: tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of eize...@gmail.com Sent: Wednesday, June 08, 2011 3:11 PM To: tutor@python.org Subject: [Tutor] String formatting question with 's'.format() I'm working through the 'Learn Python' book by Mark Lutz, in this example: >>> somelist = list('SPAM') >>> parts = somelist[0], somelist[-1], somelist[1:3] >>> 'first={0}, last={1}, middle={2}'.format(*parts) "first=S, last=M, middle=['P', 'A']" why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File "", line 1, in 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? When you use {0} and {1} and {2} it looks for 3 variables being passed into it format. Passing *parts tells Python that parts is NOT an argument but instead a list of arguments. *parts is equivalent to 3 variables where: Variable 1 = 'S' Variable 2 = 'M' Variable 3 = ['P', 'A'] The error you see when using parts instead of *parts is basically saying it is looking for 2 more arguments to be passed into the function so that it can replace it. Compare: >>> 'first={0}'.format(parts) "first=('S', 'M', ['P', 'A'])" >>> 'first={0}'.format(*parts) 'first=S' 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
[Tutor] String formatting question with 's'.format()
I'm working through the 'Learn Python' book by Mark Lutz, in this example: somelist = list('SPAM') parts = somelist[0], somelist[-1], somelist[1:3] 'first={0}, last={1}, middle={2}'.format(*parts) "first=S, last=M, middle=['P', 'A']" why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File "", line 1, in 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Q
For the Absolute Beginner 3rd Edition book, I am having trouble with another question, which says "create a game where the computer picks a random word and the player must guess that word. The computer tells the player how many letters are in the word. Then the player gets 5 chances to ask if a letter is in the word. The computer can only respond with 'yes' or 'no'. The player must then guess the word." In the "Loop of Game" section of my code for some reason it gives me five more chances than I wanted it to. When I put two as the chance limit, it allowed seven. Also, the program will always say "yes" to any letter I enter, even if it's wrong. #Word Guess import random Aquino # create a sequence of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # Getting the letter count and selection lcount = len(correct) LETTERS = None if correct == "python": LETTERS = "python" elif correct == "jumble": LETTERS = "jumble" elif correct == "easy": LETTERS = "easy" elif correct == "difficult": LETTERS = "difficult" elif correct == "answer": LETTERS = "answer" elif correct == "xylophone": LETTERS = "xylophone" #Start Game print("\n\n This word has", lcount,"letters in it.") #Loop of Game chances = 0 while chances < 5: guess = input("Does the word have a: ") for letter in correct: if letter.lower() in LETTERS: print("\nYes") chances += 1 guess = input("\nDoes the word have a: ") else: print("\nNo") chances += 1 guess = input("\nDoes the word have a: ") print("\nYour chances are up!") theguess = input("What is your guess?: ") if theguess == correct: print("\n\nYou did it!") input("\n\nPress the Enter key to exit.") else: print("\n\nSorry the word is:", correct) print(("Try again!")) input("\n\nPress the Enter key to exit.")___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lxml.html
On Wed, Jun 8, 2011 at 11:49 AM, Jerry Hill wrote: > On Wed, Jun 8, 2011 at 11:20 AM, nitin chandra > wrote: > > Hello Every One, > > > > doc = > lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() > > Is index.py really an XML document? If so, it's named pretty oddly... > > -- > Jerry > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Can you display the source code of your html file you are trying to process? -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lxml.html
On Wed, Jun 8, 2011 at 11:20 AM, nitin chandra wrote: > Hello Every One, > > doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() Is index.py really an XML document? If so, it's named pretty oddly... -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lxml.html
nitin chandra wrote: Hello Every One, doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() name = doc.forms[0].fields['name'] html = 'name is ' html += name ERROR [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback (most recent call last): What is all this extraneous date/error/ip address nonsense in the traceback? Where does it come from? TypeError: cannot concatenate 'str' and 'NoneType' objects I am extracting form field name / value from an html, but then it gives the above error and does not display the value of the variable 'name' entered in the respective form. What is the value of the variable 'name'? Hint: read the error message that you get when you try to concatenate a string with the None object: >>> "spam" + None Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'NoneType' objects -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] lxml.html
Hello Every One, doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() name = doc.forms[0].fields['name'] html = 'name is ' html += name ERROR [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback (most recent call last): [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] File "/home/dev/wsgi-scripts/response.py", line 33, in application [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] return handler.do(environ, start_response) [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] File "/home/dev/wsgi-scripts/response.py", line 15, in do [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] html += name [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] TypeError: cannot concatenate 'str' and 'NoneType' objects I am extracting form field name / value from an html, but then it gives the above error and does not display the value of the variable 'name' entered in the respective form. Thank Nitin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copying a mutable
2011/6/8 Válas Péter > As far as I understand, assignment means giving a value to a variable which > is the expression used by classical languages that have variables (such as > Pascal or Basic). Python has no variables, since even the simpliest data is > an object, but we still say assignment, because it is comfortable. > I'd submit that conceptually Python has variables, but the way it implements it is simply slightly different from some other languages. So conceptually talking about assignment is quite appropriate even if as an implementation detail it's slightly different to some other languages (due to being object oriented and due to design choices made in the langugae.) I'd further submit that from a conceptual point of view assignments mostly work as expected, for example consider this exchange: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = [1,2,3] >>> b = [1,2,3] >>> a == b True >>> id(a) 14423144 >>> id(b) 14425384 >>> a = (1,2,3) >>> b = (1,2,3) >>> id(a) 10877368 >>> id(b) 14312952 >>> a is b False >>> a == b True >>> Note, the lists are 2 seperate objects, but contain the same values. From a newbies point of view they look to be the same. Now, from an *identity* (id) point of view they're actually not the same, however usually that's a detail that you can ignore, and furthermore you'll normally use an equality check to see if they're "the same", so when a newbie that checks them for equality (using ==) he/she will get the expected result, e.g. that they're equal (despite not being the same object). In other words, the fact that they're different objects are actually irrelevant in this case. The same goes for the tuple as shown. In some sense, this is atually no different from a normal pascal/C variable, where e.g. one int will have a seperate identity (address in memory heap or on the stack) from another int, and when comparing them it would be implicitly understood that the machine would be reading the value from the one address and comparing it to the value at the other address and returning the result of the value comparison. The identities (pointers/memory addresses) are then conceptually irrelevant. So, I submit that the implications and effects of some types being mutable and others being immutable and the fact that they're implemented via objects need not lead to confusion or complication to basic notions of assignment in Python. Conceptually you have variables, and you can assign values to them. Everything else is details. HTH, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copying a mutable
I think this is easily seen by a for loop: for something in range(20): print something In the above "something" is a variable, in this case an int(which is immutable). However, "something" is changed every time it goes through the loop. It's the equivalent of: x = 0 x = 1 x = 2 and so on Just because an int is immutable, doesn't mean that you can't change the "variable" that refers to it. Hope that helps -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copying a mutable
Válas Péter wrote: Being one of the purposes of Python to be a simple educational language, I want to make this simple to a beginner who does care. :-) Here is a piece of code, Python 3.1.2, a small game with a list and a tuple: li=[3,4] id(li) 13711200 la=li id(la) 13711200 You can make it simpler by ignoring id() and using the `is` operator instead. `is` is equivalent to this function: def my_is(a, b): return id(a) == id(b) Of course you don't need to use that, instead do this: >>> a = [1, 2, 3] >>> b = a >>> a is b True My question is: how would you explain the different behaviour of a list and a tuple for a beginner? Lists are mutable, which means you can change them in-place. The *= command changes the list in place: >>> a = [1, 2] >>> b = a >>> b *= 2 >>> a is b True >>> b [1, 2, 1, 2] Since you have changed the list object itself, both a and b see the same change. Naturally, since a and b are nothing but two different names for the same object. But tuples are immutable, which means you *cannot* change then in-place. Since *= cannot change the tuple in-place, it has to create a new tuple and assign it to the name on the left hand side: >>> c = (1, 2) >>> d = c >>> c is d True >>> d *= 2 >>> d (1, 2, 1, 2) c remains a name for the first tuple, and d is now a name for the new, expanded tuple: >>> c (1, 2) >>> c is d False [...] Just to precisely understand English words, because this is a foreign language for me. As far as I understand, assignment means giving a value to a variable which is the expression used by classical languages that have variables (such as Pascal or Basic). Python has no variables, since even the simpliest data is an object, but we still say assignment, because it is comfortable. In this sense, if I say, "assignment" is a subset of "binding", is it correct? I don't think so. They are definitely related, though, assignment in the Pascal or C sense is *like* name binding in the Python or Java sense, but they are not strictly subset/superset of each other. If one was a subset of the other, then you could write down every fact about name binding: Name binding is: 1. blah blah blah... 2. ... 3. ... 999. ... and then every fact about assignment: Assignment is: 1. blah blah blah... 2. ... 3. ... 777. ... and every fact about assignment would also be a fact about name binding. But that's not the case. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Beginners
Dave Angel wrote: On 01/-10/-28163 02:59 PM, Vincent Balmori wrote: Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint'". Right now I am having trouble with giving the 'hint' variable a value despite the conditions. Everything else is working fine. Don't try to use color to give us any information, since this is a text newsgroup. I wouldn't know you had tried if Valas hadn't mentioned yellow. Not to mention that about one in 12 males (and 1 in 200 females) are colour blind and have difficulty distinguishing colours, and a surprisingly large number of completely blind people manage to read and write emails by use of screen readers and speech-to-text programs. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Beginners
On 01/-10/-28163 02:59 PM, Vincent Balmori wrote: Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint'". Right now I am having trouble with giving the 'hint' variable a value despite the conditions. Everything else is working fine. Don't try to use color to give us any information, since this is a text newsgroup. I wouldn't know you had tried if Valas hadn't mentioned yellow. # Word Jumble # # The computer picks a random word and then "jumbles" it # The player has to guess the original word import random # create a sequence of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word Since the words and hints are so closely tied, you should just make one list/tuple with both of them, so that once you have chosen a word, you've already got the hint. WORDS = (("python","It's a snake"), ("jumble", Shake Those Words"), ... then word, hint = random.choice(WORDS) # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] There's a random function that does this in one go. Look through the module and see if you can find it. # hints for each word hint = None if word == "python": hint = ("It's a snake!!") elif word == "jumble": hint = ("Shake Those Words!") elif word == "easy": hint = ("Not Hard!") elif word == "difficult": hint = ("Not Easy!") elif word == "answer": hint = ("I ask a question you have an...") elif word == "xylophone": hint = ("Metal bars with two drum sticks") Don't need this part any more. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Beginners
Vincent Balmori wrote: Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint'". Right now I am having trouble with giving the 'hint' variable a value despite the conditions. Everything else is working fine. Try adding an "else" clause to your "if word == ... hint = ..." block. else: print "word = '%s'" % word I think you might be surprised by the value of word. A bit more advice for you: # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] That's a rather complicated way to shuffle word. Here's a better way: >>> import random >>> word = 'python' >>> jumble = list(word) >>> random.shuffle(jumble) >>> jumble = ''.join(jumble) >>> jumble 'ytohpn' -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if statement
Matthew Brunt wrote: i'm very new to python (currently going through a python for beginners book at work to pass the time), and i'm having trouble with an if statement exercise. basically, i'm creating a very simple password program that displays "Access Granted" if the if statement is true. the problem i'm having is that no matter what i set the password to, it seems like it's ignoring the if statement (and failing to print "Access Granted"). the code is copied below. i'm pretty sure it's my own programming ignorance, but i would greatly appreciate any feedback. More important than the exact solution to the problem is to learn how to solve this sort of problem: password = input("Enter your password: ") if password == "a": print("Access Granted") If this is not doing what you expect, you should see what password actually is: print(password) It might also help to print the repr() of password, in case there are any unexpected spaces or other characters: print(repr(password)) Of course, if you're getting an error instead, then you should read the error message, and look at the full traceback, and see what it says. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Beginners
Since you have jumbled the word in the same variable, you have a very small chance (1:len(word)! which is 1:120 for a five-letter word) to have any of the given words in the variable "word" whan your program reaches the yellow part. You shold try to use "correct" instead of "word" in the yellow if. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Beginners
Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint'". Right now I am having trouble with giving the 'hint' variable a value despite the conditions. Everything else is working fine. # Word Jumble # # The computer picks a random word and then "jumbles" it # The player has to guess the original word import random # create a sequence of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # hints for each word hint = None if word == "python": hint = ("It's a snake!!") elif word == "jumble": hint = ("Shake Those Words!") elif word == "easy": hint = ("Not Hard!") elif word == "difficult": hint = ("Not Easy!") elif word == "answer": hint = ("I ask a question you have an...") elif word == "xylophone": hint = ("Metal bars with two drum sticks") # start the game print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """ ) print("The jumble is:", jumble) print("\nFor a hint, type in 'yes'. If not, type in 'no'.") helpcount = 0 help = input("Do you need a hint?: ") if help == "yes": print(hint) helpcount += 1 guess = input("\nYour guess: ") elif help == "no": guess = input("\nYour guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") guess = input("Your guess: ") if guess == correct: print("That's it! You guessed it!") if helpcount == 0: print("And you didn't even need a hint! You're awesome!\n") print("Thanks for playing.") input("\n\nPress the enter key to exit.")___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor