2

I have to create a game in python, where I have to code a game called 'word chain' where the last letter of a word has to be the same as the first letter of another word.

The user should input 2 words and it should say if the words are valid or not. If they are valid the code should play the game again.

I am quite new to programming.

I have tried to code the game, but whenever the words are valid it says so but when they're not it still says they're valid and the loop plays again even when it should stop.

a = True
while a:
    one = input('Word 1: ')
    two = input('Word 2: ')

    if two[-1] != one[0]: 
        print('Valid') #print result
    else:
        print('Nope! The other player won.') #print result
        a = False
        break
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
James
  • 55
  • 7

3 Answers3

4

1- your if-condition seems flipped. You want if two[-1] == one[0]: because it is valid if the last letter of word2 is the same as first of word1. Also you need to be clear on which one needs to match. last of 1 with first of 2 or last of 2 with first of 1 or either.

2- with input() you'll get trailing characters, so you'll need to trim them to compare strings.

3- you shouldn't need break if you are already looping on the variable that you are setting to False. This won't impact the rest of the functionality but pointing it out.

perennial_noob
  • 459
  • 3
  • 14
1

You need to compare the first character of the second input (two[0]) against the last character of the first input (one[-1]):

while True:
    one = input('Word 1: ').strip()
    two = input('Word 2: ').strip()

    if two[0] == one[-1]: 
        print('Valid')
    else:
        print('Nope! The other player won.')
        break

should do the trick:

Word 1: valid 
Word 2: david
Valid
Word 1: valid
Word 2: david
Valid
Word 1: notvalid
Word 2: notvalid
Nope! The other player won.
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
0

You need to replace if two[-1] != one[0]: with if one[-1] == two[0]:

Word 1: cat
Word 2: tiger
Valid
Word 1: cat
Word 2: dog
Nope! The other player won.
>>> 
Faquarl
  • 335
  • 3
  • 11