Learn Python the Hard Way 5: Ex03 Numbers and Math

来源:互联网 发布:it类书籍 编辑:程序博客网 时间:2024/06/06 00:22

5 Ex03 Numbers and Math

很多编程语言中, 运算符是必不可少的. (当当当… 数学课)

5.1 运算符

  • + plus 加
  • - minus 减
  • / slash 斜杠(取商)
  • * asterisk 星号(乘)
  • % percent 百分号(取余)
  • < less-than 小于
  • > greater-than 大于
  • <= less-than-equal 小于等于
  • >= greater-than-equal 大于等于
# -*- coding: utf-8 -*print "Hens", 25 + 30 / 6print "Roosters", 100 - 25 * 3 % 4print "Now I will count the eggs:"print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6print "It's true that 3 + 2 < 5 - 7?"print 3 + 2 < 5 - 7print "what is 3 + 2?", 3 + 2print "What is 5 - 7?", 5 - 7print "Oh, that's why it's false."print "How about some more."print "Is it greater?", 5 > -2print "Is it greater or equal?", 5 >= -2print "Is it less or equal?", 5 <= -2

这是你应该要看到的输出:
Ex03

5.2 研究学习

  1. 请解释每一行运算符是如何工作的.
  2. 重写整个程序,请需要的地方使用浮点类型数据.
# -*- coding: utf-8 -*print "Hens", 25 + 30 / 6#取商/优先级高于+,先算 30 / 6, 然后25 + 5 = 30print "Roosters", 100 - 25 * 3 % 4#*和取余%优先级高于-, 先算25 * 3 = 75, 然后75 / 4 = 13余3,所以75 % 4 = 3, 最后算100 - 3 = 97print "Now I will count the eggs:"print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6#先算4 % 2 = 0 然后算 1 / 4 = 0, 然后从做到右3 + 2 + 1 - 5 + 0 - 0 + 6 =  7 print "It's true that 3 + 2 < 5 - 7?"print 3 + 2 < 5 - 7#先算 3 + 2 = 5, 然后算 5 - 7 = -2, 最后计算逻辑 5 < -2print "what is 3 + 2?", 3 + 2 #3 + 2 = 5print "What is 5 - 7?", 5 - 7 #5 - 7 = -2print "Oh, that's why it's false."print "How about some more."#下面均是逻辑运算,输出真(True)或假(False)#注意Python中的真假Ture,False需要大写首字母print "Is it greater?", 5 > -2print "Is it greater or equal?", 5 >= -2print "Is it less or equal?", 5 <= -2

# -*- coding: utf-8 -*print "Hens", 25.0 + 30.0 / 6.0print "Roosters", 100.0 - 25 * 3 % 4print "Now I will count the eggs:"print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4.0 + 6 #这里需要用浮点型print "It's true that 3 + 2 < 5 - 7?"print 3 + 2 < 5 - 7print "what is 3 + 2?", 3 + 2print "What is 5 - 7?", 5 - 7print "Oh, that's why it's false."print "How about some more."print "Is it greater?", 5 > -2print "Is it greater or equal?", 5 >= -2print "Is it less or equal?", 5 <= -2
0 0
原创粉丝点击