我发现好像哪里都会有if,下面就来聊聊Python当中if的常见用法。
最简单的格式就是,只有一个if,比如下面这个:
my_deposit=100000
his_deposit=200000
if my_deposit<150000 and his_deposit>150000:
my_deposit+=50000
his_deposit-=50000
print('now I got',my_deposit,'in my account and he got',his_deposit,'in his account')
###运行结果就会是:
"now I got 150000 in my account and he got 150000 in his account"
代码中的
my_deposit+=50000等效于my_deposit=my_deposit+50000
his_deposit-=50000则等效于his_deposit=his_deposit-50000
所以最后的结果就是
"now I got 150000 in my account and he got 150000 in his account"
当然啦if不可能只能弄一个是不,一个条件控制语句中if理论上来讲可以有无数个滴,所以当有多个条件语句的时候我们一般会让if搭配elif来使用,比如下面这段代码:
my_name='Sun'
if my_name=='Bao':
print('YES U R Bao')
elif my_name=='Chen':
print('NO U R not Chen')
elif my_name=='Zhang':
print('NO U R not Zhang either')
else:
print('Come on,who the hell are you!')
###运行结果是:
"Come on,who the hell are you!"
因为头一行代码已经设置了全局变量my_name为Sun,然后接下来的if条件语句中没有针对当my_name==Sun的return,那么就只能从else后面找了,所以系统会返回"Come on,who the hell are you!",另外这是一个比较科学的身材判定法,好好审视下自己,如果结果低于100了,还好意思吃这么多吗?
我们也可以将条件语句稍微丰富一下,比如加入一点算数运算之类的,请看下面这段代码:
weight=62
height=171
if height-weight==110:
print('Wow,you are in perfect shape!')
elif 105<=height-weight<=115 and height-weight!=110:
print('Your body is in good condition')
else:
print('please pay more attention to your body')
###运行结果是:
"Your body is in good condition"
好好瞅瞅返回啥是根据height-weight即171-162的结果来判定的,结果是109,所以就落在了"elif 105<=height-weight<=115 and height-weight!=110:"这里,所以返回的结果就是"Your body is in good condition"
还有谁说条件只能是单个的,让我们看看下面这个例子:
tall=False
rich=False
handsome=True
if tall and rich and handsome:
print('we match each other perfectly!')
elif tall and rich:
print('we might could make a good couple')
elif rich:
print('uhhh,I would say yes if you split half of your fortune to me')
else:
print('fuck off you bastard diors!')
###运行结果是:
"fuck off you bastard diors!"
布尔值True/False就是给if条件判断语句里的关键词赋值滴,另外代码为什么要编写的如此现实残酷,看来光帅还是不够的,这大概就是我到现在还没找到女朋友的原因吧,心塞~