这个字符串相等比较有什么问题?(Python)

2024-04-20 02:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是为一个简单的刽子手类型的游戏,其中用户应该猜测一个随机单词从一个字母列表或猜测整个单词。当用户猜到整个单词时的比较不会执行。我将其中一个可能的随机词硬编码到下面的代码中作为示例:

guess = "----"
letterCount = 8
letter = ""

x = 0
while letterCount > 0:
    temp1 = "word"
    letter = input("Guess a letter in the word or attempt to guess the whole word: ")
    if (len(letter) > 1):
        print ("this is the test word: word, this is letter:" + letter)
        if letter == "word":
            print ("You win!!!")
            letterCount = 0
    else:
        x = temp1.find(letter)
        while x != -1:
            x = temp1.find(letter)
            temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
            guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
        print (("Your guess is now: " + guess))
    letterCount = letterCount - 1
    x = 0

如果我猜“单词”,它告诉我我猜单词,它指出我猜单词我应该,但If语句应该告诉我我不会执行。我是否正确地比较了这些字符串,还是问题出在其他方面?你知道吗


Tags: the代码用户ifisfindthis单词
1条回答
网友
1楼 · 发布于 2024-04-20 02:23:31
>>> while letterCount > 0:
...     temp1 = "word"
...     letter = input("Guess a letter in the word or attempt to guess the whole word: ")
...     if (len(letter) > 1):
...         print ("this is the test word: word, this is letter:" + letter)
...         if letter == "word":
...             print ("You win!!!")
...             letterCount = 0
...     else:
...         x = temp1.find(letter)
...         while x != -1:
...             x = temp1.find(letter)
...             temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
...             guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
...         print (("Your guess is now: " + guess))
...     letterCount = letterCount - 1
...     x = 0
...
Guess a letter in the word or attempt to guess the whole word: "word"
this is the test word: word, this is letter:word
You win!!!
>>>

您需要将输入转换为字符串,以便字符串比较测试能够工作。你知道吗

相关问题 更多 >