首页 > 解决方案 > Python中的两个简单的if-else代码,它们不应该返回相同的值吗?为什么每个人都会返回其他东西

问题描述

Python中的两个简单的if-else代码,它们不应该返回相同的值吗?为什么每个人都会返回其他东西。

def letter_check(word, letter):
  for i in word:
    if i == letter:
      return True
  return False

# This returns True    
print(letter_check("strawberry", "a"))

# Same function?
def letter_check(word, letter):
  for i in word:
    if i == letter:
      return True
    else:
      return False

# This returns False    
print(letter_check("strawberry", "a"))

标签: pythonif-statementcontrolsflow

解决方案


当你letter_check("strawberry", "a")第二次调用时,函数返回False,因为草莓的第一个字母是's'而不是'a'。


推荐阅读