简单使用if语句,直接给的布尔值
furry=True
large=True
if furry:
if large:
print("It's a yeti.")
else:
print("It's a cat!")
else:
if large:
print("It's a whale!")
else:
print("It's a human. Or a hairless cat.")
输出
It's a yeti.
简单的分支情况
color="mauve"
if color=="red":
print("It's a tomato")
elif color=="green":
print("It's a green pepper")
elif color=="bee purple":
print("I don't know what it is, but only bees can see it")
else:
print("I've never heard of the color",color)
输出
I've never heard of the color mauve
空值的布尔值为False
some_list=[]
if some_list:
print("There's something in here")
else:
print("Hey, it's empty!")
输出
Hey, it's empty!
多重比较,复杂形式
letter='0'
if letter=='a' or letter=='e' or letter=='i'\
or letter=='u' or letter=='o':
print(letter,"is vowel")
else:
print(letter,"is not a vowel")
输出
0 is not a vowel
多重比较,使用in语句
vowels='aeiou'
letter='o'
if letter in vowels:
print(letter,"is a vowel")
输出
o is a vowel
表达式的判断
tweet_limit=280
tweet_string="Blah"*50
diff=tweet_limit-len(tweet_string)
if diff>=0:
print("A fitting tweet")
else:
print("Went over by",abs(diff))
输出
A fitting tweet
表达式的判断,用:=
tweet_limit=280
tweet_string="Blah"*50
if (diff:=tweet_limit-len(tweet_string))>=0:
print("A fitting tweet")
else:
print("Went over by",abs(diff))
输出
A fitting tweet
1.首先在1和10之间选一个数,将其赋给变量secret。然后在1和10之间再选一个数,将其赋给变量guess。接下来,编写条件测试(if、else和elif)。如果guess小于secret,就打印字符串‘too low’;如果guess大于secret,就打印字符串‘too high’;如果guess等于secret,就打印字符串‘just right’。
代码如下
secret=1
guess=9
if guess<secret:
print("too low")
elif guess>secret:
print("too high")
else:
pfint("just right")
2.将True和False分别赋值给small和green。编写一些if/else语句,打印出哪些匹配下列选择:cherry、pea、watermelon、pumpkin。
small=False
green=True
if green:
if small:
print("pea")
else:
print("watermelon")
elif small:
print("cherry")
else:
print("pumpkin")