pythonif-statementwords

Same input 2 different results


I'm extremely new to programming, and I hope someone could help me. I'm trying to make a game where 2 players need to input words based on the last 2 letters of the word the other player placed into. I got that part to work, but I cannot get the part which decides the winner. It's the same 2 elif statements but they should print out different results.

Ex. P1: banana P2: narnia P1:ian P2:animal So basically when one of the players fails to accomplish the task of matching the last 2 letters they lose the game

 used_words=[]

 while True:
     player_one=raw_input("Player one \n")
     first= list(player_one)
     player_two=raw_input("Player two \n")
     second=list(player_two)

     if first[-2:] == second[:2] and first and second not in used_words:
         used_words.append(player_one)
         used_words.append(player_two)
         continue

     elif first[-2:] != second[:2]:
         print "Player one wins! \n"
         print "The word you had to match was: ", second
         break

     elif second[:2] != first[-2:]:
         print "Player two wins!"
         print "The word you had to match was: ", first
         break

    else:
         break

Solution

  • I think the problem is in your conditional if first[-2:] == second[:2] and first and second not in used_words: because and first basically is testing that first is not an empty string, so change it to if first[-2:] == second[:2] and first not in used_words and second not in used_words:. However, there are other change that should make in order to achiever what you want:

    player_one = raw_input("Player one \n")
    used_words = [player_one]
    
    while True:
        player_two = raw_input("Player two \n")        
    
        if used_words[-1][-2:] != player_two[:2] and player_two not in used_words:
             print "Player one wins! \n"
             print "The word you had to match was: ", player_one
             break
    
        used_words.append(player_two)
        player_one = raw_input("Player one \n")
    
        if used_words[-1][-2:] != player_one[:2] and player_one not in used_words:
             print "Player two wins! \n"
             print "The word you had to match was: ", player_two
             break