【问题标题】:desired_word_found variable is not being changed in PythonPython 中没有更改desired_word_found 变量
【发布时间】:2023-04-02 03:04:01
【问题描述】:

我正在用 Python 编写一个简单的程序来确定一个单词是否包含在一段文本中。问题是,当在文本中检测到desired_word 时,desired_word_found 变量不会被语句“desired_word_found == true”更改。我知道这与变量 (desired_word_found) 不是静态的有关,我什至尝试将变量更改为全局变量,但该语句仍未更改它。我是 Python 新手,需要一些帮助。

#这个程序判断给定的单词是否在一段文本中

desired_word_found = False 


#retrieving necessary data 
desired_word = input("What word would you like to search for? ")
raw_text = input("Please enter the text you would like us to search: ")

words = raw_text.split()#stores each word of the text in words list 



for i in range(len(words)):#loops through list of words to determine if our desired word is contained in the list 

    if words[i] == desired_word:
        desired_word_found == True ################### VARIABLE IS NOT BEING CHANGED BY THIS STATEMENT


if desired_word_found == True:
    print(desired_word+" was found")
else:
    print(desired_word+" was not found")

【问题讨论】:

  • 输出总是“desired_word was not found”,即使我的循环在文本中找到了这个词。我将问题隔离到desired_word_found 变量没有被标记为“############”的语句更改
  • 您也可以只完成if desired_word in words: print("xxx")。无需循环检查每个单词。

标签:
python
python-3.x
variables
global-variables