我可以通过什么方法将具有不同值的分数添加到代码中?

时间:2019-05-21 12:13:12

标签: python

我需要在代码中添加分数,但我不知道该怎么做。我尝试了以前的代码的不同方式,但是它们在此程序中不起作用。关于我可以做什么的任何建议?

我需要打分,以便如果用户在第一次尝试中猜对了,他们将获得3分,如果在第二次尝试中获得了3分,那么他们将获得1分,但是如果他们弄错了,他们将一无所获。这是我的代码:

def choose_song(artist, songs, song_choosen):
    idx = 0
    guess_correct = False
    song = ''
    while idx < 2:
        guess = input('The artist is {} and the song is {}... Enter your guess {}: '.format(artist, song_choosen[:3], idx+1))
        #Iterate through all songs to check if the guess is right, if it is, break out of for loop
        for song in songs:
            if guess.lower().strip() == song.lower().strip():
                guess_correct = True
                song = guess
                break
        #If the user guessed correctly, we are done else try again
        if guess_correct:
            break
        else:
            idx+= 1
    #Show the final output accordingly
    if guess_correct:
        print('You guessed correctly. The song is indeed {} '.format(song))
    else:
        print('You guessed wrong. The song is {} '.format(song_choosen))
choose_song('Eminem', ['Rap God', 'skip'], 'Rap God')
choose_song('Marshmello', ['Project Dreams', 'skip'], 'Project Dreams')
choose_song('Unlike Pluto', ['Late Bloomer', 'skip'], 'Late Bloomer')

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

添加:

  • 第4行:score = 0
  • 第13行score = [3,1,0][idx]
  • 第23行更改print()命令

有关以下新代码中发生的情况的评论:

idx = 0
guess_correct = False
song = ''
score = 0 #Add Variable for score and set it = 0

while idx < 2:

    guess = input('The artist is {} and the song is {}... Enter your guess {}: '.format(artist, song_choosen[:3], idx+1))

    #Iterate through all songs to check if the guess is right, if it is, break out of for loop
    for song in songs:
        if guess.lower().strip() == song.lower().strip():
            guess_correct = True
            song = guess
            score = [3,1,0][idx] # Depending on your index (number of tries) give 3, 1 or 0 points
            break

    #If the user guessed correctly, we are done else try again
    if guess_correct:
        break
    else:
        idx+= 1

#Show the final output accordingly
if guess_correct:
    print('You guessed correctly. The song is indeed {}. You got {} Points '.format(song, score)) # Print points
else:
    print('You guessed wrong. The song is {}. You got no points '.format(song_choosen)) 


choose_song('Eminem', ['Rap God', 'skip'], 'Rap God')
choose_song('Marshmello', ['Project Dreams', 'skip'], 'Project Dreams')
choose_song('Unlike Pluto', ['Late Bloomer', 'skip'], 'Late Bloomer')