Reputation: 129
I am having some trouble with loops. It's for on of my projects: "Write a program that prompts the user to guess your given name. The program should continue to ask until the user guesses the name correctly. When the correct guess is made, issue a congratulatory message to the user. The user is told he/she has only ten guesses. The loop should exit when the user correctly guesses the name or has made ten wrong guesses?
The issue is that when I am in the while loop, if I type in "Name" , it still would register that I was incorrect.
Here's what I currently have:
count = 0
print "Hello. I have a name inside my head. Please guess what name it is."
text = raw_input ("What is your answer? ")
while (text != "Name"):
count = count + 1
attempt = 10 - count
if count >= 10:
print "That is the maximum amount of attempts allowed. Sorry!"
stopper = raw_input ("Thanks for playing!")
if count < 10:
print "Sorry, that is not the answer. You have", attempt, "more attempts."
newText = raw_input ("What is your next guess? ")
if (text == "Name"):
print "Amazing. You got it correct!"
Upvotes: 1
Views: 82
Reputation: 1562
You need to make a few changes to your code:
(1) Replace new_text
with text
so that text
's value gets updated in each iteration.
(2) Break out of the while
loop once the user has reached the max number of tries.
(3) There's no point in asking the user to input text when the count has reached the max, so instead of getting raw_input
, just print "Thanks for playing!"
.
Here's the updated code that works:
count = 0
print "Hello. I have a name inside my head. Please guess what name it is."
text = raw_input ("What is your answer? ")
while (text != "Name" and count < 10):
count = count + 1
attempt = 10 - count
if count >= 10:
print "That is the maximum amount of attempts allowed. Sorry!"
print "Thanks for playing!"
if count < 10:
print "Sorry, that is not the answer. You have", attempt, "more attempts."
text = raw_input ("What is your next guess? ")
if (text == "Name"):
print "Amazing. You got it correct!"
Upvotes: 1
Reputation: 56
that's because you're iterating and testing on variable text which is set outside of the while loop, means it'll catch only the first input of the user and that's the only success case. Here you go:
count = 0
print("Hello. I have a name inside my head. Please guess what name it is.")
text = input("What is your answer? ")
while (count<12):
count = count + 1
attempt = 10 - count
if (text == 'Name'):
print("Amazing. You got it correct!")
count = 12
if count >= 10:
print("That is the maximum amount of attempts allowed. Sorry!")
stopper = input ("Thanks for playing!")
if count < 10:
print ("Sorry, that is not the answer. You have", attempt, "more attempts.")
text = input ("What is your next guess? ")
Upvotes: 2