如何有条件地过早地结束while循环?

时间:2020-10-26 12:05:41

标签: python variables

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次,这是我搞砸了,因为我只创建了一个变量来估计点数和决定是否继续游戏的猜测数。

我将如何处理?理想情况下,只需更改尽可能少的当前代码?

1 个答案:

答案 0 :(得分:0)

作为最小的更改修复程序,您可以在正确猜出答案后可以放入break,以逃避while循环:

  if guess1==a and guess2==b:
    print("Correct!")
    guesscount=guesscount+1
    print(guesscount)
    break