Learn Python The Hard Way学習(3)-数字と数学計算

1809 ワード

どのプログラム言語にも数学の計算方法があり、プログラマーはよく自分が数学の天才だと思っていますが、実はそうではありません.数学の天才であれば、広告プログラムやソーシャルゲームを書いてお金を稼ぐのではなく、数学に関する仕事をします.
数学の記号は私たちが知らないので、みんな知っています.コードを直接付けましょう.
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.浮動小数点数でex 3を記述する.py、結果をより正確にします.
5番目の文を修正します.
print 3 + 2 + 1 - 5 + 4 % 2 - 1.0/4 + 6
運転後の結果:6.75