python逻辑值_“字符串”的逻辑值是多少?在Python中?

I erroneously wrote this code in Python:

name = input("what is your name?")

if name == "Kamran" or "Samaneh":

print("That is a nice name")

else:

print("You have a boring name ;)")

It always prints out "That is a nice name" even when the input is neither "Kamran" nor "Samaneh".

Am I correct in saying that it considers "Samaneh" as a true? Why?

By the way, I already noticed my mistake. The correct form is:

if name == "Kamran" or name == "Samaneh":

解决方案

Any non empty string in Python (and most other languages) is true as are all non-zero numbers and non-empty lists, dictionaries, sets and tuples.1

A nicer way to do what you want is:

name = input("what is your name?")

if name in ("Kamran", "Samaneh"):

print("That is a nice name")

else:

print("You have a boring name ;)")

This creates a tuple containing the names that you want and performs a membership test.

1 As delnan points out in the comments, this applies to all well written collections. That is, if you implement a custom collection class, make sure that it is false when it's empty.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值