习题 3: 数字和数学计算

阅读原文

每一种编程语言都包含处理数字和进行数学计算的方法。不必担心,程序员经常撒谎说他们是多么牛的\ 数学天才,其实他们根本不是。如果他们真是数学天才,他们早就去从事数学相关的行业了,而不是\ 写写广告程序和社交网络游戏,从人们身上偷赚点小钱而已。

这章练习里有很多的数学运算符号。我们来看一遍它们都叫什么名字。你要一边写一边念出它们的\ 名字来,直到你念烦了为止。名字如下:

  • + plus 加号
  • - minus 减号
  • / slash 斜杠
  • * asterisk 星号
  • % percent 百分号
  • < less-than 小于号
  • > greater-than 大于号
  • <= less-than-equal 小于等于号
  • >= greater-than-equal 大于等于号

有没有注意到以上只是些符号,没有运算操作呢?写完下面的练习代码后,再回到上面的列表,写出每\ 个符号的作用。例如 + 是用来做加法运算的。

print "I will now count my chickens:"

print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4

print "Now I will count the eggs:"

print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

print "Is it true that 3 + 2 < 5 - 7?"

print 3 + 2 < 5 - 7

print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7

print "Oh, that's why it's False."

print "How about some more."

print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2

在你运行之前完全确保你键入的字符同上。把你敲的每行代码都同我的做一下对比。

What You Should See

$ python ex3.py
I will now count my chickens:
Hens 30
Roosters 97
Now I will count the eggs:
7
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False.
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False

Study Drills

  1. 使用 # 在代码每一行的前一行为自己写一个注解,说明一下这一行的作用。
  2. 记得开始时的 <练习 0> 吧?用里边的方法把 Python 运行起来,然后使用刚才学到的运算符号,把Python当做计算器玩玩。
  3. 自己找个想要计算的东西,写一个 .py 文件把它计算出来。
  4. 有没有发现计算结果是"错"的呢?计算结果只有整数,没有小数部分。研究一下这是为什么,搜索一下“浮点数(floating point number)”是什么东西。
  5. 使用浮点数重写一遍 ex3.py,让它的计算结果更准确(提示: 20.0 是一个浮点数)。

Common Student Questions

Why is the % character a "modulus" and not a "percent"?
Mostly that's just how the designers chose to use that symbol. In normal writing you are correct to read it as a "percent." In programming this calculation is typically done with simple division and the / operator. The % modulus is a different operation that just happens to use the % symbol.
How does % work?
Another way to say it is, "X divided by Y with J remaining." For example, "100 divided by 16 with 4 remaining." The result of % is the J part, or the remaining part.
What is the order of operations?
In the United States we use an acronym called PEMDAS which stands for Parentheses Exponents Multiplication Division Addition Subtraction. That's the order Python follows as well.
Why does / (divide) round down?
It's not really rounding down; it's just dropping the fractional part after the decimal. Try doing 7.0 / 4.0 and compare it to 7 / 4 and you'll see the difference.

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""