
if语句中的“表达式”可以是关系表达式、逻辑表达式,甚至是数值表达式。其中最直观、最容易理解的是关系表达式。所谓关系表达式就是两个数值进行比较的式子。对于数值的使用,if语句可以很大的帮助我们进行计算操作。今天我们就来看看python中if语句的用法。
if条件语句的基本用法:
1 2 3 4 | if 判断条件:
执行语句……
else :
执行语句……
|
实例:判断数字是正数、负数或零。
方法一:使用内嵌 if 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <p style= "line-height: normal;" ># Filename :test.py
# author by : www.runoob.com# 内嵌 if 语句
num= float(input( "输入一个数字: " ))
if num>= 0:
if num== 0:
print ( "零" )
else :
print ( "正数" )
else :
print ( "负数" )<br></p>
|
方法二:使用 if...elif...else 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 | <p style= "line-height: normal;" ><span style= "color: rgb(0, 0, 0); text-decoration: none;" ># Filename : test.py
# author by : </span><a style= "color: rgb(0, 0, 0); text-decoration: none;" href= "http://www.runoob.com" ><span style= "color: rgb(0, 0, 0);" >www.runoob.com</span></a><span style= "color: rgb(0, 0, 0); text-decoration: none;" ># 用户输入数字<br>num= float(input( "输入一个数字: " ))
if num> 0: <br> print ( "正数" )
elif num== 0:
print ( "零" )
else :
print ( "负数" )<br></span></p>
|
以上就是用if语句判断判断数字是正数、负数或零的用法啦,完成判断这一步就可以进行进行接下来的计算啦~更多学习推荐:python学习网。