[英]How do I conditionally prematurely end a while loop?
nextround=True
#Reading from a file to a list for Songs
SongNamesList = []
myfile = open("Songnames.txt", "r")
endOfFile = False
while endOfFile == False:
temp = myfile.readline()
temp = temp.strip()
if not temp:
endOfFile = True
else:
SongNamesList.append(temp)
myfile.close()
#Reading from a file to a list for Artists
ArtistsList = []
myfile1 = open("Artists.txt", "r")
endOfFile = False
while endOfFile== False:
temp = myfile1.readline()
temp = temp.strip()
if not temp:
endOfFile = True
else:
ArtistsList.append(temp)
myfile1.close()
cont = True
#sets score to 0 at the start of the game
totalscore = 0
#Sets up continue variable to allow the user to stop the game if they want
while cont == True:
#Sets up guess count number to cut out after 3
guesscount = 0
#Generates random artist and song
randomindex = random.randint(0,len(ArtistsList)-1)
Artist = [randomindex]
a=(ArtistsList[randomindex])
#print(a)
b=(SongNamesList[randomindex])
#print(b)
answercount=0
#Works out if answer is correct problem
while answercount <=2:
print(a[0:1])
print(b[0:1])
guess1 = input("What is the Artist name?")
guess2=input("What is the Song name?")
if guess1==a and guess2==b:
print("Correct!")
guesscount=guesscount+1
print(guesscount)
else:
print("Incorrect! Please input another answer:")
guesscount=guesscount+1
print(guesscount)
#Works out the number of points given in turn for the guess count
if guesscount==1:
totalscore=totalscore+3
print(totalscore)
guesscount=0
print("Your Score Is:",(totalscore))
elif guesscount==2:
totalscore=totalscore+1
guesscount=0
cont=True
print("Your Score Is:", totalscore)
print(totalscore)
elif guesscount==3:
print(None)
elif guesscount>=4:
print("The Song was",b)
print("The Artist was",a)
print("Your Score Is:", totalscore)
print(totalscore)
else:
cont=False
print("You have failed to Guess,your total score was:", totalscore)
print("The Song was",b)
print("The Artist was",a)
這是該問題的所有相關代碼。 我知道問題在於分數的變量以及需要添加多少分。 該代碼適用於音樂游戲,玩家必須僅從兩者的一個字母中猜測音樂標題和藝術家姓名,藝術家和歌曲都在已寫入的文件中。
如前所述,問題在於每次猜測會增加多少分,所以如果首先猜測歌曲和藝術家,他們會得到 3 分,依此類推,但是即使猜對了,它也會重復 3 次,這就是我的地方搞砸了,因為我只為決定分數的猜測計數和決定是否繼續游戲的猜測計數創建了一個變量。
我怎么會go這個呢? 理想情況下盡可能少地更改當前代碼?
作為最小的更改修復,您可以在正確猜測答案以逃避 while 循環后break
:
if guess1==a and guess2==b:
print("Correct!")
guesscount=guesscount+1
print(guesscount)
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.