This is an exercise from the Non-programmers tutorial for Python
by Josh Cogliati.
The exercise is:
Write a program that has a user guess your name, but they only get 3
chances to do so until the program quits.
Here is my script:
--------------------------
count = 0
name = raw_input("Guess my name. ")
while name != 'Ben' and count < 3:
count = count + 1
if name != 'Ben' and count < 3:
name = raw_input('Guess again. ')
elif name == 'Ben' and count < 3:
print "You're right!"
else:
print 'No more tries.'
----------------------------------
Everything works except the line: print "You're right!"
Could someone tell me what is wrong and give me a better alternative to
what I came up with.
Thank you
Ben 14 1156
Ben wrote: This is an exercise from the Non-programmers tutorial for Python by Josh Cogliati.
The exercise is:
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
Here is my script:
--------------------------
count = 0 name = raw_input("Guess my name. ")
while name != 'Ben' and count < 3: count = count + 1
if name != 'Ben' and count < 3: name = raw_input('Guess again. ') elif name == 'Ben' and count < 3: print "You're right!" else: print 'No more tries.'
----------------------------------
Everything works except the line: print "You're right!"
Could someone tell me what is wrong
The code within the while loop (i.e., everything indented) is executed only if
the while condition is true, i.e., name != Ben and count < 3
So name == 'Ben': will always be false and "You're right!" will never get printed
and give me a better alternative to what I came up with.
Just a hint: you may find a cleaner solution if you separate the tests for name
from the test for count.
Thank you
Ben
HTH
Michael
On 31 Mar 2005 20:03:00 -0800, "Ben" <be*********@gmail.com> wrote: Could someone tell me what is wrong and give me a better alternative to what I came up with.
Seperate you raw input statements from your test. Your elsif is
skipping over it.
Try using only one raw imput statement right after your while
statement.
Ron
Ben wrote: This is an exercise from the Non-programmers tutorial for Python by Josh Cogliati.
The exercise is:
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
Here is my script:
--------------------------
count = 0 name = raw_input("Guess my name. ")
while name != 'Ben' and count < 3:
Everything inside this loop will only occur if the name doesn't equal
'Ben' and the count is less than 3.
count = count + 1
You increase the count by one, which allows your code to catch the case
where count = 2 and now equals 3.
if name != 'Ben' and count < 3: name = raw_input('Guess again. ') elif name == 'Ben' and count < 3: print "You're right!" else: print 'No more tries.'
Which is why you get this print message, because count is now equal to 3. ----------------------------------
Everything works except the line: print "You're right!"
But at no point does the program get an opportunity to print "No more
tries.' because there is no point inside this loop where name == 'Ben'.
Could someone tell me what is wrong and give me a better alternative to what I came up with.
Thank you
Ben
Also, you're duplicating a lot of your case testing. You check to see if
the name is 'Ben' at the start, and then inside the loop, and the same
for the counts.
I tried to write out a logical method of approaching this problem, but
in truth this particular use-case isn't that simple is it?
Here's my contribution anycase:
count = 0
# Get first input
name = raw_input("Guess my name: ")
# Give the sucker two extra goes
while count < 2:
# Check the value of name
if name == 'Ben':
print "You're right!"
break
else:
name = raw_input("Try again: ")
# Of course, we haven't checked the sucker's last guess
# so we have to do that now.
if count == 2:
if name == 'Ben':
print "You're right!"
else:
print "No more tries for you!!!"
Hope this helps.
Joal
Oh goddammmnitttt. I seem to be doing this a lot today. Look below for
the extra addition to the code I posted.
Joal Heagney wrote: Here's my contribution anycase:
count = 0 # Get first input name = raw_input("Guess my name: ") # Give the sucker two extra goes while count < 2: # Check the value of name if name == 'Ben': print "You're right!" break else: name = raw_input("Try again: ")
# Here's the bit I missed out.
count += 1 # Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print "You're right!" else: print "No more tries for you!!!"
Hope this helps. Joal
GRRRRRRRR.
Joal
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <jo**@bigpond.net.au> wrote: Oh goddammmnitttt. I seem to be doing this a lot today. Look below for the extra addition to the code I posted.
Joal Heagney wrote: Here's my contribution anycase:
count = 0 # Get first input name = raw_input("Guess my name: ") # Give the sucker two extra goes while count < 2: # Check the value of name if name == 'Ben': print "You're right!" break else: name = raw_input("Try again: ")
# Here's the bit I missed out. count += 1 # Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print "You're right!" else: print "No more tries for you!!!"
Hope this helps. Joal
GRRRRRRRR.
Need something more straightforward, e.g., a wrapped one-liner: def guess(n=3): print ("You're right!", 'No more tries for you!!!')[n-1 in
... (x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben']
... if not t or iter([]).next())]
... guess()
Guess my name: Jack
Guess my name: Bob
Guess my name: Ben
You're right! guess()
Guess my name: Jack
Guess my name: Ben
You're right! guess()
Guess my name: Kermit
Guess my name: Ms Piggy
Guess my name: Ernie
No more tries for you!!! guess(1)
Guess my name: Einstein
No more tries for you!!! guess()
Guess my name: Ben
You're right!
Regards,
Bengt Richter
Bengt Richter wrote: On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <jo**@bigpond.net.au> wrote:
Oh goddammmnitttt. I seem to be doing this a lot today. Look below for the extra addition to the code I posted.
Joal Heagney wrote:
Here's my contribution anycase:
count = 0 # Get first input name = raw_input("Guess my name: ") # Give the sucker two extra goes while count < 2: # Check the value of name if name == 'Ben': print "You're right!" break else: name = raw_input("Try again: ")
# Here's the bit I missed out. count += 1
# Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print "You're right!" else: print "No more tries for you!!!"
Hope this helps. Joal
GRRRRRRRR.
Need something more straightforward, e.g., a wrapped one-liner:
>>> def guess(n=3): print ("You're right!", 'No more tries for you!!!')[n-1 in
... (x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ... if not t or iter([]).next())]
Okay, now in my opinion, that's just too complex to give to a newbie as
a suggested implementation. :)
Joal
Joal Heagney wrote: Bengt Richter wrote:
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <jo**@bigpond.net.au> wrote:
Oh goddammmnitttt. I seem to be doing this a lot today. Look below for the extra addition to the code I posted.
Joal Heagney wrote:
Here's my contribution anycase:
count = 0 # Get first input name = raw_input("Guess my name: ") # Give the sucker two extra goes while count < 2: # Check the value of name if name == 'Ben': print "You're right!" break else: name = raw_input("Try again: ")
# Here's the bit I missed out. count += 1
# Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print "You're right!" else: print "No more tries for you!!!"
Hope this helps. Joal
GRRRRRRRR.
Need something more straightforward, e.g., a wrapped one-liner:
>>> def guess(n=3): print ("You're right!", 'No more tries for you!!!')[n-1 in ... (x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ... if not t or iter([]).next())]
Okay, now in my opinion, that's just too complex to give to a newbie as a suggested implementation. :)
Joal
I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance']
for p in pr:
name = raw_input(p+": ")
if name == "Ben":
print "You're right!"
break
else:
print "Loser: no more tries for you"
regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Thanks for your help.
It is much appreciated.
Joal was right. It is a bit beyond me. But I appreciate your response.
Steve Holden wrote: Joal Heagney wrote:
Bengt Richter wrote:
On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney <jo**@bigpond.net.au> wrote:
Oh goddammmnitttt. I seem to be doing this a lot today. Look below for the extra addition to the code I posted.
Joal Heagney wrote:
> Here's my contribution anycase: > > count = 0 > # Get first input > name = raw_input("Guess my name: ") > # Give the sucker two extra goes > while count < 2: > # Check the value of name > if name == 'Ben': > print "You're right!" > break > else: > name = raw_input("Try again: ") # Here's the bit I missed out. count += 1
> # Of course, we haven't checked the sucker's last guess > # so we have to do that now. > if count == 2: > if name == 'Ben': > print "You're right!" > else: > print "No more tries for you!!!" > > > Hope this helps. > Joal GRRRRRRRR. Need something more straightforward, e.g., a wrapped one-liner:
>>> def guess(n=3): print ("You're right!", 'No more tries for you!!!')[n-1 in ... (x for x in xrange(n) for t in [raw_input('Guess my name: ')=='Ben'] ... if not t or iter([]).next())] Okay, now in my opinion, that's just too complex to give to a newbie as a suggested implementation. :)
Joal
I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance'] for p in pr: name = raw_input(p+": ") if name == "Ben": print "You're right!" break else: print "Loser: no more tries for you"
regards Steve
THIS is why I like python! There's always a simple, easy to understand
way to do something. If it looks complex, then there must me something
wrong.
Joal
Joal Heagney wrote: Steve Holden wrote: I suppose this would be far too easy to understand, then:
pr =['Guess my name', 'Wrong, try again', 'Last chance'] for p in pr: name = raw_input(p+": ") if name == "Ben": print "You're right!" break else: print "Loser: no more tries for you"
regards Steve
THIS is why I like python! There's always a simple, easy to understand way to do something. If it looks complex, then there must me something wrong.
Joal
And now that I've looked at the documentation of the for loop, I
understand it as well! :)
The following explaination is for Ben, so he knows what's going on.
From the documentation, with a little rewriting.
"The for statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for target_list "in" expression_list:
<do this first>
else:
<now do this last>
The expression list is evaluated once and should yield a sequence(such
as a string, tuple, list or iterator object).
Each item in the sequence is assigned to the target_list variable in
turn. Then the "do this first" instructions are then executed once for
each item in the sequence.
When the items are exhausted (which is immediately when the sequence is
empty), the "now do this last" instructions in the else statement, if
present, are executed, and the loop terminates.
A break statement executed in the first section terminates the WHOLE
loop without executing the else clause. A continue statement executed in
the first stage skips the rest of these instructions for that loop and
continues with the next item, or with the else clause if there was no
next item."
So copying Steve's example: pr =['Guess my name', 'Wrong, try again', 'Last chance'] for p in pr: name = raw_input(p+": ") if name == "Ben": print "You're right!" break else: print "Loser: no more tries for you"
This allows us to execute the else clause if the name is guessed
incorrectly three times.
However, if the name is guessed correctly, then the break statement
pulls us completely out of the loop without executing the else clause.
My original example attempted to do this by splitting the loop up into a
series of different cases because I was unaware of this additional
behaviour with the for loop expression. Steve's method = much better.
Joal
On 31 Mar 2005 20:03:00 -0800, "Ben" <be*********@gmail.com> declaimed
the following in comp.lang.python: This is an exercise from the Non-programmers tutorial for Python by Josh Cogliati.
The exercise is:
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
Here is my script:
<snip>
Could someone tell me what is wrong and give me a better alternative to what I came up with.
Thank you
Well, it's been two days since your post, and the other
suggestions should have given you enough to make a working version, so I
shouldn't be violating the "we don't do homework" ethic by too much with
this...
-=-===-=-=-=-=-=-
myName = "Ben"
numTries = 3
print "Guess my name (you get three tries)"
for t in range(numTries):
guess = raw_input("Your Guess> ")
if guess.upper() == myName.upper():
print "You guessed my name in %s tries" % (t + 1)
break
else:
print "%s is not my name" % guess
else:
print "Sorry, you lose"
-=-=-=-=-=-=-=-=-=-
G:\My Documents>python t.py
Guess my name (you get three tries)
Your Guess> Able
Able is not my name
Your Guess> Cain
Cain is not my name
Your Guess> Serpent
Serpent is not my name
Sorry, you lose
G:\My Documents>python t.py
Guess my name (you get three tries)
Your Guess> Who
Who is not my name
Your Guess> is
is is not my name
Your Guess> ben
You guessed my name in 3 tries
G:\My Documents>
-- ================================================== ============ < wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < wu******@dm.net | Bestiaria Support Staff < ================================================== ============ < Home Page: <http://www.dm.net/~wulfraed/> < Overflow Page: <http://wlfraed.home.netcom.com/> < This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: rdsteph |
last post by:
I am having a lot of fun using the pyGoogle module (
http://pygoogle.sourceforge.net/ ) that uses the Google API. It is
about as easy to use as I can imagine, and it is a lot nicer than using
my...
|
by: G. |
last post by:
Hi all,
During my degree, BEng (Hons) Electronics and Communications Engineering, we
did C programming every year, but I never kept it up, as I had no interest
and didn't see the point. But now...
|
by: Rohit |
last post by:
I need some ideas on how to write a program that could
-- Read an MS Access database and grab information say Vehicle year,
vehicle make
-- Make a call to a website and enter the information...
|
by: user |
last post by:
Hi all,
At the outset, I regret having to post this slightly OT post here.
However, I strongly feel that people in this group would be the best to
advise me on my predicament.
I am working as...
|
by: Jesse B. |
last post by:
I've been learning how to program with C, and I can't find any info about
GUI programming with C. I'm almost done with O'reilly's Practical
programming with C, and would like to mess around with...
|
by: Ed_P |
last post by:
Hello
I just wanted to get the opinions of those of you who have experience developing C# applications and programming in general. I currently am learning the basics of programming (choosing C#...
|
by: tjones |
last post by:
Hi, I am guessing this is *THE* nntp newsgroup for C#?
I was hoping someone could point me in the right direction. Id like to find
employment in the IT industry as a programmer again. My...
|
by: Kevin Spencer |
last post by:
Is it just me, or am I really observing a trend away from analysis and
probem-solving amongst programmers? Let me be more specific:
It seems that every day, in greater numbers, people are coming...
|
by: arnuld |
last post by:
hello all,
1st of all, i searched last 12 years archives of comp.lang.c++
because i have some problems. i got some help but not satisfied as i
did not get solution specific to my problem. In the...
|
by: Dexter |
last post by:
My site is home to series of quizzes ranging from Accounting,
Business, Math to programming languages. These are multiple choice
type questions and you get a score card at end.
For C language, ...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |