if 块的第一个条件被跳过
Posted
技术标签:
【中文标题】if 块的第一个条件被跳过【英文标题】:First condition of an if-block is getting skipped 【发布时间】:2020-09-29 07:05:40 【问题描述】:我正在使用 Python 2.7 编写代码来检查输入字符串中是否存在字符,但 Python 一直在跳过我的部分 if 语句。
每次我运行代码并输入一个guess
字符值时,都会直接执行else
语句,并且根本不会执行if(guess in PuzzleSetter) == True
块。
我做错了什么?
PuzzleSetter = " "
List = []
def setPuzzle():
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
print("Guessing player try guessing: "+PuzzleSetter.upper())
time.sleep(5)
print(chr(27) + "[2J")
List = [' __ ']*len(PuzzleSetter)
print("\n")
print(List)
while(True):
guess = raw_input("\nGuessing player make your guess: ")
if len(guess) != 1:
print("You are meant to enter a single letter")
continue
else:
guess = guess.upper()
print(guess)
if(guess in PuzzleSetter) == True:
finder = PuzzleSetter.find(guess)
print(PuzzleSetter+" contains "+str(PuzzleSetter.count(guess))+" "+guess+"'s")
for count in range(PuzzleSetter.count(guess)):
List[finder] = guess.upper()
finder = PuzzleSetter.find(guess, finder+1)
print(List)
if List.count("__") == 0:
print("Guessing player wins!")
break
else:
HangerMan()
enter += 1
if enter == 7:
print("Guessing player lost!")
print("\nPlayer two becomes the puzzle setter")
setPuzzle()
【问题讨论】:
什么是 PuzzleSetter?PuzzleSetter
是如何定义的?我看到它会被跳过的唯一原因基本上是如果guess
不在PuzzleSetter
中。如果 PuzzleSetter(似乎不是列表)无法处理 in
检查,则此行将始终评估为 False
并跳转到 else
块。强烈建议您也发布PuzzleSetter
的定义。
请edit您的问题并提供问题的minimal reproducible example。
关于风格的快速说明:== True
是多余的,最好省略。
如果PuzzleSetter
只包含小写字母,则永远不会在其中找到已转换为大写的guess
。
【参考方案1】:
正如我所想,您将PuzzleSetter
作为输入,而不是像guess
那样将其转换为大写。如果它包含任何小写字母,它们将永远找不到。试试这个:
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
PuzzleSetter = PuzzleSetter.upper()
print("Guessing player try guessing: "+PuzzleSetter)
【讨论】:
以上是关于if 块的第一个条件被跳过的主要内容,如果未能解决你的问题,请参考以下文章
由于错误条件,任务“NETSdkError”被跳过; ('$(_TargetFrameworkVersionWithoutV)' > '$(NETCoreAppMaximumVersion)')