gpt4 book ai didi

python - 向脚本添加 while 循环会导致输入错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:21:15 24 4
gpt4 key购买 nike

我正在编写一些代码来玩 Hangman (Python 3.5.2)。我不希望我的代码永远运行,例如 while 1 < 2: ,但我开始在没有 while 的情况下正常工作的语句上出现语法错误。 。这是我的代码:

with open('dictionary.txt') as f:
words = f.read().splitlines()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words2 = ''
alphabetCount = []
guesses = []
input = input('Input: ')
for x in range(0, len(words)):
valid = True
if len(input) == len(words[x]):
for y in range(-1, len(input)-1):
if input[y] != words[x][y] and input[y] != '_':
valid = False
if valid:
words2 = words2 + (words[x])
for x in range(0, 26):
alphabetCount.append(0)
for x in range(0, len(words2)):
alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1
for z in range(0, 26):
if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input:
guesses.append(alphabet[alphabetCount.index(max(alphabetCount))])
alphabetCount[alphabetCount.index(max(alphabetCount))] = 0
print (guesses)

本质上,我想像这样循环它:

while 1 < 2:
with open('dictionary.txt') as f:
words = f.read().splitlines()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words2 = ''
alphabetCount = []
guesses = []
input = input('Input: ')
for x in range(0, len(words)):
valid = True
if len(input) == len(words[x]):
for y in range(-1, len(input)-1):
if input[y] != words[x][y] and input[y] != '_':
valid = False
if valid:
words2 = words2 + (words[x])
for x in range(0, 26):
alphabetCount.append(0)
for x in range(0, len(words2)):
alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1
for z in range(0, 26):
if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input:
guesses.append(alphabet[alphabetCount.index(max(alphabetCount))])
alphabetCount[alphabetCount.index(max(alphabetCount))] = 0
print (guesses)

最佳答案

出现这个问题是因为你屏蔽了内置函数 input() 作业:

input = input('Input: ')

对于一次迭代,这会工作得很好,因为您不会再次调用 input()。不过,多次执行此操作将使用被屏蔽的 input 值,在您的情况下使用 str 类型的值;调用 str 值将导致 TypeError

将名称更改为不同的名称,例如:

my_input = input('Input: ')

为了消除错误,请确保在整个代码中进行更改。

记住切勿将用户定义的名称与 built-in function names 混合使用因为你会得到奇怪的行为。

关于python - 向脚本添加 while 循环会导致输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38424345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com