🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972
个人介绍: 研一|统计学|干货分享
擅长Python、Matlab、R等主流编程软件
累计十余项国家级比赛奖项,参与研究经费10w、40w级横向
【Python操作基础】系列——if语句用法,建议收藏!
该篇文章首先利用Python展示了使用if语句的基本用法;elif语句;if与三元运算以及一些注意事项。
1 基本用法
运行程序:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" ##执行多输出
a=2
b=3
if(a<b):
print("a小于b")
else:
print("a不小于b")
if(a<=b):
if(a<b):
print(a)
else:
print(a)
else:
print(b)
运行结果:
a小于b
22.5
2 elif语句
运行程序:
if(a<=b):
if(a<b):
print(a)
elif(a==b):
print(a)
else:
print(b)
运行结果:
2
3 if与三元运算
运行程序:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" ##执行多输出
x=0
Result="Y" if x>0 else "N"
Result
x=1
Result="Y" if x>0 else "N"
Result
运行结果:
'N'
'Y'
4 注意事项
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = “all” ##执行多输出
if(a<=b): pass #利用pass代替空行 else: print(b)
import calendar calendar.isleap(2019) #判断是否闰年