Reputation: 25
I am creating a small text game of which a person has to guess the name of the song correctly and with only two guesses, I have created a while loop so that I can use this two guess system; However, it is only looping a small area of the code and not what I want it to loop.
Below is the code being used (Of which includes the while loop)
#song guess entry
ans2 = input("Enter the name of the song: ")
#change all the capitalisation to lowercase
ans2 = ans2.lower()
time.sleep(0.5)
x = 0
#while loop to allow two attempts at the Question
while x != 2:
print("LOADING...")
time.sleep(1)
#correct or incorrect?
if ans2 == song:
if x == 1:
print("\nYou gained 1 point for guessing it the second time!")
score = score + 1
if x == 0:
print("You gained 3 points for guessing it first time!")
score = score + 3
time.sleep(0.5)
if ans2 != song:
print("\nIncorrect! No points gained")
x = x + 1
time.sleep(0.5)
When executing the program I ensured that the song I entered was actually correct multiple times. When this problem first happened it was displaying nothing after it asked for the user to enter the song name, I then put a print statement after the while loop starts just to try and visualise the problem.
#while loop to allow two attempts at the Question
while x != 2:
print("LOADING...") # where i added the print statement
time.sleep(1)
The result of executing the code is this:
Enter the name of the song: buffalo soldier
LOADING...
LOADING...
LOADING...
LOADING...
LOADING...
LOADING...
LOADING...
LOADING...
LOADING...
The 'LOADING...' does not stop.
Upvotes: 0
Views: 51
Reputation: 5720
You need to ask the question within the while:
#song guess entry
import time
x,score = 0,0
song = 'buffalo soldier'
#while loop to allow two attempts at the Question
while x != 2:
print("LOADING...")
ans2 = input("Enter the name of the song: ")
# change all the capitalisation to lowercase
ans2 = ans2.lower()
time.sleep(1)
#correct or incorrect?
if ans2 == song:
if x == 1:
print("\nYou gained 1 point for guessing it the second time!")
score = score + 1
if x == 0:
print("You gained 3 points for guessing it first time!")
score = score + 3
break
else:
print("\nIncorrect! No points gained")
x = x + 1
time.sleep(0.5)
Upvotes: 1
Reputation: 3495
You don't re-initiate your x
, so it is probably over 2 after the first run you made, and it's going 3 -> 4 -> 5 -> 6... infinity (as x != 2
is always True). You need to assign x = 0
just before the loop. In addition, if it was the wrong answer, you don't ask the user for a new one inside the loop. Add ans2 = input("Enter the name of the song: ")
to the code if the user was wrong inside the loop.
Upvotes: 0