下面是你要写的作业,这段向你介绍了“ if 语句”。把这段输入进去,让它能正确执行。然后我们看看你是否有所收获。
# -*- Coding:utf-8 -*-people = 20cats = 30dogs = 15if people < cats: print "Too many cats! The world is doomed!"if people > cats: print "Not many cats! The world is saved!"if people < dogs: print "The world is drooled on!"if people > dogs: print "The world is dry!"dogs += 5if people >= dogs: print "People are greater than or equal to dogs."if people <= dogs: print "People are less than or equal to dogs."if people == dogs: print "People are dogs."
结果
Too many cats! The world is doomed!The world is dry!People are greater than or equal to dogs.People are less than or equal to dogs.People are dogs.
另外一种精简写法:
# -*- Coding:utf-8 -*-people = 20cats = 30dogs = 15if people < cats: print "Too many cats! The world is doomed!"elif people > cats: print "Not many cats! The world is saved!"if people < dogs: print "The world is drooled on!"elif people > dogs: print "The world is dry!"dogs += 5if people > dogs: print "People are greater than or equal to dogs."elif people < dogs: print "People are less than or equal to dogs."else: print "People are dogs."
加分习题
猜猜“ if 语句”是什么,它有什么用处。在做下一道习题前,试着用自己的话回答下面的问题 :
1.你认为 if 对于它下一行的代码做了什么?
如果if判断成功则进行下面,否则退出判断。
2. 为什么 if 语句的下一行需要 4 个空格的缩进?
和def一样
3. 如果不缩进,会发生什么事情?
报错
4. 把习题 27 中的其它布尔表达式放到 ``if 语句 `` 中会不会也可以运行呢?试一下。
5. 如果把变量 people,cats,和 dogs 的初始值改掉,会发生什么事情?
判断结果不一样
常见问题回答
+= 是什么意思?
x += 1 和 x = x + 1 一样,只不过可以少打几个字母。你可以把它叫做加值符。一样的,你后面还会学到 -= 以及很多别的表达式。
以上是内存溢出为你收集整理的笨办法学Python 习题 29: 如果(if)全部内容,希望文章能够帮你解决笨办法学Python 习题 29: 如果(if)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)