我是python的新手,通常进行编码,而在做一个特定项目时,我被困在这里:
Guess_1 = input()
Number_2 = input()
Set_dead_1 = set()
def teste_dead_1():
index_1 = 0
while index_1 <= 3:
if Guess_1[index_1] == Number_2[index_1]:
Set_dead_1.add(Number_2[index_1])
else:
pass
for i in Set_dead_1:
print(i, "is dead.")
index_1 += 1
teste_dead_1()
为进一步说明,我试图比较每个字符串的每个字符,如果它是匹配类型,则表明“字符已死”。 但是问题是当我执行程序并插入数字时,会弹出这样的内容:
>1234
1234
1 is dead
2 is dead
1 is dead
3 is dead
2 is dead
1 is dead
4 is dead
3 is dead
2 is dead
1 is dead
但是我要它写:
>1 is dead
2 is dead
3 is dead
4 is dead
感谢您的理解!
PS:两个1234是我输入的
答案 0 :(得分:1)
我花了一些时间复制您的代码并运行它。我用if
检查输入长度来调试它。主要问题是您的for
循环在while循环的每次迭代中放置和运行均不正确。如果您不了解迭代过程,我会在纸上写下来。
已启用代码:
Guess_1 = input()
Number_2 = input()
Set_dead_1 = set()
def teste_dead_1():
index_1 = 0
Guess1Length = len(Guess_1)
Number2Length = len(Guess_1)
if Guess1Length < 3 or Number2Length < 3:
print('Input must be more than 3 characters')
return False
while index_1 <= 3:
if Guess_1[index_1] == Number_2[index_1]:
Set_dead_1.add(Number_2[index_1])
index_1 += 1
for i in Set_dead_1:
print(i, "is dead.")
return True
teste_dead_1()
答案 1 :(得分:0)
对我来说,您不需要循环就可以打印您的布景。在添加新成员时打印它们,
Guess_1 = input()
Number_2 = input()
Set_dead_1 = set()
def teste_dead_1():
index_1 = 0
while index_1 <= 3:
if Guess_1[index_1] == Number_2[index_1]:
Set_dead_1.add(Number_2[index_1])
print(Number_2[index_1], "is dead.")
else:
pass
index_1 += 1
teste_dead_1()