习题 29: 如果(if)
目标与感悟:
•if语句的简单应用
•增值符 x += 1
ex29.py
#-*-coding:utf-8-*-
#本章涉及内容十分简单,即if sentence1: sentence2,
#if语句用法和函数有点像,第二行都需要缩进4个字符
#if语句执行过程如下:
#先执行语句一即判断语句,如果判断语句为真,则执行语句二。
#此处不一定是语句,只是一个条件,其值也可以是布尔值
peolple = 20
cats = 30
dogs = 15
if peolple < cats:
print"Too many cats! The world is doomed!"
if peolple > cats:
print"Not many cats! The world is saved!"
if peolple < dogs:
print"The world is drooled on!"
if peolple > dogs:
print"The world is dry!"
#此处出现新的符号+=,作者命名为加值符,其等同与:
#x += 1 和 x = x + 1
#其更简洁,此处dogs += 5,dogs = 20
dogs += 5
#下面3个条件都成立,所以全部输出
if peolple >= dogs:
print"People are greater than or equal to dogs."
if peolple <= dogs:
print"People are less than or equal to dogs."
if peolple == dogs:
print"People are dogs."
print "\t \t boolean test!"
print "\t -------------------------------- "
a = "test"
b = "testing"
if a != b:
print "\t \t Is true!"
print "\t\tboolean can be used"
print "\t -------------------------------- "
运行结果:
本文通过实例详细介绍了Python中if语句的应用,包括条件判断、布尔值使用及加值符的介绍。通过不同场景下的代码演示,加深了读者对if语句的理解。
1140

被折叠的 条评论
为什么被折叠?



