Skip to main content
 首页 » 编程设计

python之无法将变量与 while 循环中的输入进行比较

2025年05月04日10del

我在尝试学习 Python 时遇到了一些我正在制作的基本程序的问题,问题是我试图将用户输入与我设置的变量进行比较,但当我尝试比较它们。

这是有问题的循环:

    if del_question  == "1": 
    symbol = input("What symbol would you like to change?: ") 
    while len(symbol) != 1 or symbol not in words: 
        print("Sorry, that is not a valid symbol") 
        symbol = input("What symbol would you like to change?: ") 
    letter = input("What would you like to change it to?: ") 
    while letter in words and len(letter) != 1: 
        print("Sorry, that is not a valid letter") 
        letter = input("What letter would you like to change?: ") 
    dictionary[symbol] = letter 
    words = words.replace(symbol, letter) 
    print("Here is your new code: \n", words) 

这个游戏是关于通过配对字母和符号来破解密码的,这是字母和符号配对的地方,但是在我尝试制作它时输入的字母上,这样你就无法简单地将同一个字母配对两次绕过它。它正在处理符号输入,但我不确定为什么它在这里不起作用。

这里是导入的文本文件:

code_file = open("words.txt", "r") 
word_file = open("solved.txt", "r") 
letter_file = open("letter.txt", "r") 

和:

solved = word_file.read() 
words = code_file.read() 
clue = clues_file.read() 

这是单词文件的内容:

#+/084&" 
#3*#%#+ 
8%203: 
,1$& 
!-*% 
.#7&33& 
#*#71% 
&-&641'2 
#))85 
9&330* 

请您参考如下方法:

您的错误是一个简单的逻辑错误。当你真的想要一个 or 条件时,你有一个 and 条件。将您的第二个 while 语句更改为:

while letter in words or len(letter) != 1