python - 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"))
解决方案
当你letter_check("strawberry", "a")
第二次调用时,函数返回False
,因为草莓的第一个字母是's'而不是'a'。
推荐阅读
- java - 未在可执行 jar 中加载的依赖类
- java - DynarchCalendar 无法点击截止日期月份和日期
- functional-dependencies - 主要属性和部分依赖说明
- php - 获取可变产品的每个 WooCommerce 变体的特定产品属性名称和值
- node.js - 如何安装最新版本的primeng 7.1.0
- gradle - 需要在 build.gradle 中写入条件,如果满足它应该从特定的工件下载依赖项
- r - 未定义“逻辑”和“期间”类的算术运算符
- compilation - 编译器设计预处理和编译
- wcf - 启动用于与本机 api 通信的自托管 WCF 服务的快速方法
- jenkins - 如何为JVM分配内存