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


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

数学符号我们就不去认识,大家都知道。直接上代码吧:
[python]
1. print "I will now count my chickens:" 
2.  
3.  
4. print "Hens", 25 + 30 / 6 
5. print "Roosters", 100 - 25 * 3 % 4 
6.  
7.  
8. print "Now I will count the eggs:" 
9.  
10.  
11. print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 
12.  
13.  
14. print "Is it true that 3 + 2 < 5 - 7?" 
15.  
16.  
17. print 3 + 2 < 5 - 7 
18.  
19.  
20. print "What is 3 + 2?", 3 + 2 
21. print "What is 5 - 7?", 5 - 7 
22.  
23.  
24. print "Oh, that's why it's False." 
25.  
26.  
27. print "How about some more." 
28.  
29.  
30. print "Is it greater?", 5 > -2 
31. print "Is it greatet or equal?", 5 >= -2 
32. 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

 作者:lixiang0522

相关内容

    暂无相关文章

评论关闭