Learn Python The Hard Way学习(3) - 数字和数学计算

每种程序语言都有数学计算方法,程序员经常认为自己是数学天才,其实不是,如果是数学天才的话,就会去做数学相关的工作了,而不是写一下广告程序和社交游戏赚点小钱。

数学符号我们就不去认识,大家都知道。直接上代码吧:
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 greatet or equal?", 5 >= -2
print "is it less or equal?", 5 <= -2


运行结果应该是这样的:
root@he-desktop:~/mystuff# 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 greatet or equal? True
is it less or equal? False
root@he-desktop:~/mystuff# 

加分练习
1. 用#号给每行加个注释。
# 百分号是取余数的意思
print "Roosters", 100 - 25 * 3 % 4

2. 像练习(0)一样,在Terminal中输入python,把python运行起来,然后逐句执行上面的代码。

3. 自己找一个要计算的东西,写一个py文件。

4. 看看上面的程序是不是有错误,你会发现只有整数,没有小数,搜索并了解一下“浮点数”。

5. 用浮点数编写ex3.py,让结果更加正确。
修改第5句为:
print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6
运行后的结果是:6.75

你可能感兴趣的:(Learn Python The Hard Way学习(3) - 数字和数学计算)