1. 程式人生 > >笨方法學Python(1-3)

笨方法學Python(1-3)

習題1:第一個程式

print "Hello Word !"
print "Hello Again"
print "I like typing this"
print "This is fun."
print "Yay! Printing."
print "I'd much rather you 'not'."
print "I 'said' do not touch this. "

將上述程式碼儲存到Python1.py。如何在Python環境下檢視檔案內容呢?

  • 第一種方式:開啟Terminal(終端),輸入python,拖拽檔案即可。

    第一種方式

  • 第二種方式:cd+資料夾的路徑,python+檔名

    第二種方式

總結: 注意區分中文英文標點符號以及單雙引號。

加分習題

  • 讓你的指令碼在多列印一行。【\n】
print "Hello Word !"
print "\n"
print "Hello Again"
print "I like typing this"
print "This is fun."
print "Yay! Printing."
print "I'd much rather you 'not'."
print "I 'said' do not touch this. "
  • 讓你的指令碼只打印一行。【,】
print "Hello Word !"
, print "Hello Again", print "I like typing this", print "This is fun.", print "Yay! Printing.", print "I'd much rather you 'not'.", print "I 'said' do not touch this. "

習題2:註釋和井號

# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this."
# and the comment after is ignored # You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print "This will run."
  • 終端讀取資料為:

顯示資料

習題3:數字和數學計算

# -- coding: utf-8 --
# + 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 "Whatis3+2?",3+2 
print "Whatis5-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
  • 終端讀取資料為:

顯示資料

練習說明

# -- coding:utf-8 --
print 25+30/6    #25加上30除以6 和為30
print 100-25*3%4  #100減去25乘以3的積再除以4的餘數,就是100-3=97  
print 100%16    #100除以16的餘數=4
print 1/4   #1除以4,然後因為是整數,所以四舍5入為0
print 1.0/4.0   ##1.0除以4.0,因為是浮點數,所以等於0.25
print 3+5<5+4   #判斷語句,返回的值為布林型,true or false 8<9  為 true
  • 終端讀取資料為:

顯示資料