雲計算學習筆記,雲計算Python自動化基本用法
行和縮進:
學習Python時,遇到的第一個需要註意的地方是,不使用括號來表示代碼的類和函數定義塊或流程控制。代碼塊是由行縮進,這是嚴格執行表示方式。 縮進位的數目是可變的,但是在塊中的所有語句必須縮進相同的量。在這個例子中,兩個功能塊都很好使用:
if True:
print "True"
else:
print "False"
在本例中的第二塊將產生一個錯誤:
if True:
print "Answer" print "True"
else:
print "Answer"
print "False"
因此,在Python中所有的連續線縮進的空格數同樣的會結成塊。
多行語句:
Python語句通常用一個新行結束。 但是,Python允許使用續行字符()來表示,該行應該繼續下去(跨行)。
例如:
total = (item_one +
item_two +
item_three)
包含在[],{}或()括號內的陳述並不需要使用續行符。 例如:
days = [‘Monday‘, ‘Tuesday‘, ‘Wednesday‘,
‘Thursday‘, ‘Friday‘]
可以使用三引號"""或‘‘‘來打印多行語句,寫什麽格式就打印什麽格式。 比如:
print(‘‘‘hello this
is
a
test 多行語句‘‘‘)
打印結果如下:
hello this
is
a
test 多行語句
繼續符( \ ):
Python 語句,一般使用換行分隔,也就是說一行一個語句。一行過長的語句可以使用反斜杠( \ ) 分解成幾行,比如:
if (weather_is_hot == 1) and \
(shark_warnings == 0):
send_goto_beach_mesg_to_pager()
引號:
Python可以使用單引號(‘),雙引號(“)和三(‘‘‘或”””)引號,以表示字符串常量,只要是同一類型的引號開始和結束的字符串。三重引號可以用於跨越多個行的字符串。 例如:
word = ‘word‘
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
註釋:
單行註釋: 一個井號(#),“#”號之後字符到本行結束都是註釋,Python解釋器會忽略它們。比如:
#!/usr/bin/python
First comment
print "Hello, Python!" # second comment
運行結果:
Hello, Python!
使用三引號完成多行註釋:
‘‘‘
comment1
comment2
‘‘‘‘
等待用戶:
方式1:raw_input()
程序的下面一行顯示的提示,按回車鍵退出,等待用戶按下回車鍵:
#!/usr/bin/python
raw_input("Press the enter key to exit.")
一旦用戶按下鍵時,程序結束。這是一個很好的技巧,保持一個交互式對話,直到用戶完成應用程序運行。
方式2:input()
上面兩種等待用戶輸入的方式區別是:
raw_input不解釋用戶輸入
input會解釋用戶的輸入
在一行中多個語句:
分號( ; ) 允許在單行寫入多條語句,不管語句是否啟動一個新的代碼塊。下面是使用分號示例:
import sys; x = ‘foo‘; sys.stdout.write(x + ‘‘)
多個語句組作為套件:
一組單獨的語句, 在Python單一的代碼塊被稱為序列。復雜的語句,如if, while, def, and class,那些需要一個標題行和套件。 標題行開始與聲明(關鍵字),並終止與冒號(:),接著是一個或多個線構成該套件。
例如:
if expression :
suite
elif expression :
suite
else :
suite
命令行參數:
很多程序可以運行,它們提供有關如何運行的一些基本信息。 Python中可以使用 -h 做到這一點:
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
雲計算學習筆記,雲計算Python自動化基本用法