Python編程常用的十大語法和代碼匯總

2021-03-02 江大食科2008

C.1.1 Python的「Hello World」

[輸入]

source_code/appendix_c_python/example00_helloworld.py
print "Hello World!"

[輸出]

$ python example00_helloworld.py
Hello World!

C.1.2 注釋

注釋不會被Python執行。它以字符#開頭,以行尾結束。

[輸入]

# source_code/appendix_c_python/example01_comments.py
print "This text will be printed because the print statement is executed."
#這只是一個注釋,不會被執行
#print "Even commented statements are not executed."
print "But the comment finished with the end of the line."
print "So the 4th and 5th line of the code are executed again."

[輸出]

$ python example01_comments.py
This text will be printed because the print statement is executed
But the comment finished with the end of the line.
So the 4th and 5th line of the code are executed again.

C.2 數據類型

Python的一些有效數據類型如下所示。

數字數據類型:整型、浮點型。

文本數據類型:字符串型。

複合數據類型:元組、列表、集合、字典。

C.2.1 整型

整數數據類型只能存儲整數值。

[輸入]

# source_code/appendix_c_python/example02_int.py
rectangle_side_a = 10
rectangle_side_b = 5
rectangle_area = rectangle_side_a * rectangle_side_b
rectangle_perimeter = 2*(rectangle_side_a + rectangle_side_b)
print "Let there be a rectangle with the sides of lengths:"
print rectangle_side_a, "and", rectangle_side_b, "cm."
print "Then the area of the rectangle is", rectangle_area, "cm squared."
print "The perimeter of the rectangle is", rectangle_perimeter, "cm."

[輸出]

$ python example02_int.py
Let there be a rectangle with the sides of lengths: 10 and 5 cm.
Then the area of the rectangle is 50 cm squared.
The perimeter of the rectangle is 30 cm.

C.2.2 浮點型

浮點數據類型也可以存儲非整數的有理數值。

[輸入]

# source_code/appendix_c_python/example03_float.py
pi = 3.14159
circle_radius = 10.2
circle_perimeter = 2 * pi * circle_radius
circle_area = pi * circle_radius * circle_radius
print "Let there be a circle with the radius", circle_radius, "cm."
print "Then the perimeter of the circle is", circle_perimeter, "cm."
print "The area of the circle is", circle_area, "cm squared."

[輸出]

$ python example03_float.py
Let there be a circle with the radius 10.2 cm.
Then the perimeter of the circle is 64.088436 cm.
The area of the circle is 326.8510236 cm squared.

C.2.3 字符串

字符串變量可以用於存儲文本。

[輸入]

# source_code/appendix_c_python/example04_string.py
first_name = "Satoshi"
last_name = "Nakamoto"
full_name = first_name + " " + last_name
print "The inventor of Bitcoin is", full_name, "."

[輸出]

$ python example04_string.py
The inventor of Bitcoin is Satoshi Nakamoto.

C.2.4 元組

元組數據類型類似於數學中的向量。例如,tuple = (integer_number, float_number)。

[輸入]

# source_code/appendix_c_python/example05_tuple.py
import math
point_a = (1.2,2.5)
point_b = (5.7,4.8)
#math.sqrt計算浮點數的平方根
#math.pow計算浮點數的冪
segment_length = math.sqrt(
math.pow(point_a[0] - point_b[0], 2) +
math.pow(point_a[1] - point_b[1], 2))
print "Let the point A have the coordinates", point_a, "cm."
print "Let the point B have the coordinates", point_b, "cm."
print "Then the length of the line segment AB is", segment_length, "cm."

[輸出]

$ python example05_tuple.py
Let the point A have the coordinates (1.2, 2.5) cm.
Let the point B have the coordinates (5.7, 4.8) cm.
Then the length of the line segment AB is 5.0537115074 cm.

C.2.5 列表

Python中的列表指的是一組有序的數值集合。

[輸入]

# source_code/appendix_c_python/example06_list.py
some_primes = [2, 3]
some_primes.append(5)
some_primes.append(7)
print "The primes less than 10 are:", some_primes

[輸出]

$ python example06_list.py
The primes less than 10 are: [2, 3, 5, 7]

C.2.6 集合

Python中的集合指的是一組無序的數值集合。

[輸入]

# source_code/appendix_c_python/example07_set.py
from sets import Set
boys = Set(['Adam', 'Samuel', 'Benjamin'])
girls = Set(['Eva', 'Mary'])
teenagers = Set(['Samuel', 'Benjamin', 'Mary'])
print 'Adam' in boys
print 'Jane' in girls
girls.add('Jane')
print 'Jane' in girls
teenage_girls = teenagers & girls #intersection
mixed = boys | girls #union
non_teenage_girls = girls - teenage_girls #difference
print teenage_girls
print mixed
print non_teenage_girls

[輸出]

$ python example07_set.py
True
False
True
Set(['Mary'])
Set(['Benjamin', 'Adam', 'Jane', 'Eva', 'Samuel', 'Mary'])
Set(['Jane', 'Eva'])

C.2.7 字典

字典是一種數據結構,可以根據鍵存儲數值。

[輸入]

# source_code/appendix_c_python/example08_dictionary.py
dictionary_names_heights = {}
dictionary_names_heights['Adam'] = 180.
dictionary_names_heights['Benjamin'] = 187
dictionary_names_heights['Eva'] = 169
print 'The height of Eva is', dictionary_names_heights['Eva'], 'cm.'

[輸出]

$ python example08_dictionary.py
The height of Eva is 169 cm.

C.3 控制流

條件語句,即我們可以使用if語句,讓某段代碼只在特定條件被滿足的情況下被執行。如果特定條件沒有被滿足,我們可以執行else語句後面的代碼。如果第一個條件沒有被滿足,我們可以使用elif語句設置代碼被執行的下一個條件。

[輸入]

# source_code/appendix_c_python/example09_if_else_elif.py
x = 10
if x == 10:
print 'The variable x is equal to 10.'
if x > 20:
print 'The variable x is greater than 20.'
else:
print 'The variable x is not greater than 20.'
if x > 10:
print 'The variable x is greater than 10.'
elif x > 5:
print 'The variable x is not greater than 10, but greater ' + 'than 5.'
else:
print 'The variable x is not greater than 5 or 10.'

[輸出]

$ python example09_if_else_elif.py
The variable x is equal to 10.
The variable x is not greater than 20.
The variable x is not greater than 10, but greater than 5.

C.3.1 for循環

for循環可以實現迭代某些集合元素中的每一個元素的功能,例如,range集合、列表。

C3.1.1 range的for循環

[輸入]

source_code/appendix_c_python/example10_for_loop_range.py
print "The first 5 positive integers are:"
for i in range(1,6):
print i

[輸出]

$ python example10_for_loop_range.py
The first 5 positive integers are:
1
2
3
4
5

C3.1.2 列表的for循環

[輸入]

source_code/appendix_c_python/example11_for_loop_list.py
primes = [2, 3, 5, 7, 11, 13]
print 'The first', len(primes), 'primes are:'
for prime in primes:
print prime

[輸出]

$ python example11_for_loop_list.py
The first 6 primes are:
2
3
5
7
11
13

C3.1.3 break和continue

for循環可以通過語句break提前中斷。for循環的剩餘部分可以使用語句continue跳過。

[輸入]

source_code/appendix_c_python/example12_break_continue.py
for i in range(0,10):
if i % 2 == 1: #remainder from the division by 2
continue
print 'The number', i, 'is divisible by 2.'
for j in range(20,100):
print j
if j > 22:
break;

[輸出]

$ python example12_break_continue.py
The number 0 is divisible by 2.
The number 2 is divisible by 2.
The number 4 is divisible by 2.
The number 6 is divisible by 2.
The number 8 is divisible by 2.
20
21
22
23

C.3.2 函數

Python支持函數。函數是一種定義一段可在程序中多處被執行的代碼的好方法。我們可使用關鍵詞def定義一個函數。

[輸入]

source_code/appendix_c_python/example13_function.py
def rectangle_perimeter(a, b):
return 2 * (a + b)
print 'Let a rectangle have its sides 2 and 3 units long.'
print 'Then its perimeter is', rectangle_perimeter(2, 3), 'units.'
print 'Let a rectangle have its sides 4 and 5 units long.'
print 'Then its perimeter is', rectangle_perimeter(4, 5), 'units.'

[輸出]

$ python example13_function.py
Let a rectangle have its sides 2 and 3 units long.
Then its perimeter is 10 units.
Let a rectangle have its sides 4 and 5 units long.
Then its perimeter is 18 units.

C.3.3 程序參數

程序可以通過命令行傳遞參數。

[輸入]

source_code/appendix_c_python/example14_arguments.py
#引入系統庫以使用命令行參數列表
import sys
print 'The number of the arguments given is', len(sys.argv),'arguments.' print 'The argument list is ', sys.argv, '.'

[輸出]

$ python example14_arguments.py arg1 110
The number of the arguments given is 3 arguments.
The argument list is ['example14_arguments.py', 'arg1', '110'].

C.3.4 文件讀寫

下面程序將向文件test.txt寫入兩行文字,然後讀取它們,最後將其列印到輸出中。

[輸入]

# source_code/appendix_c_python/example15_file.py
#寫入文件"test.txt"
file = open("test.txt","w")
file.write("first line\n")
file.write("second line")
file.close()
#read the file
file = open("test.txt","r")
print file.read()

[輸出]

$ python example15_file.py
first line
second line

*聲明:版權歸原作者所有,如來源信息有誤或侵犯權益,請聯繫我們刪除或授權事宜。

文章轉載於公眾號:python

相關焦點

  • 第2天:Python 基礎語法
    Python 可以同一行顯示多條語句,方法是用分號 ; 分開,如:>>> print("hello");print("world");helloworldPython 關鍵字下面的列表顯示了在 Python 中的保留字。
  • Python編程入門——基礎語法詳解(經典)
    今天小編給大家帶來Python編程入門——基礎語法詳解。溫馨提示:亮點在最後!
  • 3000 字教你學會最地道的 Python 編程風格
    防禦編程風格3.1 程序每次運行都要檢查3.2 很難一次考慮所有可能異常3.3 代碼的可讀性下降1 基本編程習慣Python代碼的編程習慣主要參考PEP8:https://www.python.org/dev/peps/pep-0008/
  • Python GUI界面編程-初識篇
    作為 python 特定的GUI界面,是一個圖像的窗口,tkinter是python 自帶的,可以編輯的GUI界面,我們可以用GUI 實現很多直觀的功能,比如想開發一個計算器,如果只是一個程序輸入,輸出窗口的話,是沒用用戶體驗的。所有開發一個圖像化的小窗口,就是必要的。
  • 第1天:Python 環境搭建
    現在之所以這麼流行和社區、人工智慧的發展,有很大的關係。千裡之行始於足下,今天我們先來學習 Python 環境搭建。Python 介紹Python(英國發音:/ˈpaɪθən/ 美國發音:/ˈpaɪθɑːn/)是一種廣泛使用的解釋型、高級編程、通用型程式語言,由吉多·范羅蘇姆創造,第一版發布於1991年。
  • python基礎
    node類似,可以在終端輸入python 文件名就可以執行文件注釋python的注釋用一個 # 表示注釋是為了方便閱讀,增強代碼的可讀性多行注釋的話是"""或者'''數據類型數字類型布爾類型字符串類型 str列表類型 list元組 tuple集合
  • 如何把Python和Bash搞在一起解決問題
    Shell腳本還支持某些程式語言基礎知識,例如變量,流控制和數據結構。Shell腳本對於將經常重複運行的批處理作業非常有用。不幸的是,shell腳本有一些缺點:   Shell腳本很容易變得過於複雜,並且對於想要改進或維護它們的開發人員來說是不可讀的。   這些shell腳本的語法和解釋器通常很笨拙且不直觀。
  • Python黑帽編程1.3 Python運行時與包管理工具
    由於原書很多地方過於簡略,筆者根據實際測試情況和最新的技術發展對內容做了大量的變更,當然最重要的是個人偏好。教程同時提供圖文和視頻教程兩種方式,供不同喜好的同學選擇。0.2 前言前兩節裡,我們完成了作業系統和工具的安裝。
  • 和金融相關的python包匯總
    這些網站一般都會提供一個接口(API),使用各種程式語言都可以通過接口來直接獲取數據。>yql-financehttps://github.com/slawek87/yql-finance簡單快捷,返回當前時間段的股票收盤價和當前股票代碼ystockquotehttps://github.com/cgoldberg/ystockquote從雅虎財經檢索股票報價數據wallstreethttps
  • Python中的十大圖像處理工具
    圖像處理是分析和操縱數字圖像的過程,旨在提高其質量或從中提取一些信息,然後將其用於某些方面。圖像處理中的常見任務包括顯示圖像,基本操作(如裁剪、翻轉、旋轉等),圖像分割,分類和特徵提取,圖像恢復和圖像識別等。Python之成為圖像處理任務的最佳選擇,是因為這一科學程式語言日益普及,並且其自身免費提供許多最先進的圖像處理工具。
  • Python 基礎語法
    Python 是一門腳本語言,無需編譯就能直接運行,下面就總結性簡紹一下其語法特點。1、大小寫敏感(大小寫進行區分)。
  • Python+Selenium,讓瀏覽器自動幫你下文獻
    萬能的谷歌給我找到了一篇教程python 批量下載知網(CNKI)論文[1],嗯,使用python+selenium,就把瀏覽器調教成我們想要的樣子,讓它自動幫我們下文獻。感謝前人提供巨人的肩膀!在這篇文章、以及這篇文章作者提供的代碼的基礎上,通過學習和改造,就可以將其適用於外文資料庫。這裡以Chrome瀏覽器和SpringLink資料庫為例子進行說明。
  • 如何在 Linux 上安裝 Python | Linux 中國
    Python 現在是最流行、最常用的程式語言。Python 的簡單語法和較低的學習曲線使其成為初學者和專業開發人員的終極選擇。Python 還是一種非常通用的程式語言。從 Web 開發到人工智慧,它幾乎在除了移動開發的所有地方都有使用。如果你使用的是 Python,那麼你很有可能是一名開發人員(或想成為一名開發人員),而 Linux 是創建軟體的絕佳平臺。
  • 驗證常用腳本語言介紹
    ,本期就帶大家了解一下常用的腳本語言。而且由於腳本是動態解釋的,使得它具有很好的可移植性,只要系統安裝有解釋器,不論是安卓,linux,windows,幾乎都可以直接運行平臺無關的代碼。腳本易學易用,自帶標準庫中經常提供一些常用功能,對於實現相同的功能,往往只需要很少的代碼量。
  • 用 Webhook+Python+Shell 編寫一套 Unix 類系統監控工具
    Shell 命令的通配符和特殊字符常用的特殊字符表利用通配符可以同時引用多個文件,常用的通配符有 * 和 ?Python 解釋器有兩種模式,一種是交互式模式,在這種模式下,輸入的代碼在回車後會立即執行,並顯示代碼執行結果,在命令行中通過輸入 Python 進入交互式模式,輸入 exit() 退出交互式模式;另一種是命令行模式,即在命令行中輸入 python [文件名. py],直接執行 Python 程序。
  • 妙用正則表達式--Python中的re模塊
    課程通過案例教學模式,旨在幫助大家在短期內掌握Stata軟體編程、金融計量知識和實證分析方法,使大家熟悉Stata核心的爬蟲技術,以及Stata與其他軟體交互的高端技術。利用正則表達式,我們可以對文本內容進行精確快捷地匹配和提取。與Stata相比,正則表達式的元字符是通用的,不同的是函數。re庫中有若干個函數各司其職,在上一篇推文《Python標準庫re:正則表達式》中我們介紹了re庫中的三個常用函數,現在小編將從實用的角度再介紹幾個常用的函數。首先,我們回顧一下re模塊中有哪些屬性和方法。
  • Python 操作 Excel 匯總合集(代碼demo)
    作者:王翔丨來源:碼農升級python操作excel的模塊簡直不要太多,今天就為大家比較下各模塊之間的優缺點。模塊官網win32comhttp://pythonexcels.com/python-excel-mini-cookbook/DataNitrohttps://datanitro.com/這兩個模塊又是怎麼一回事兒?
  • GitHub 熱門:實用 Python 編程
    (給Python開發者加星標,提升Python技能)最近 GitHub 上的一個熱門倉庫/課程:Practical Python Programming/實用 Python 編程
  • Python,我只寫墜吊的
    防禦編程風格3.1 程序每次運行都要檢查3.2 很難一次考慮所有可能異常3.3 代碼的可讀性下降1 基本編程習慣Python代碼的編程習慣主要參考PEP8:https://www.python.org/dev/peps/pep-0008/
  • Linux, macOS和Windows 上一款整潔的 Python IDE
    它是跨平臺的,可以在Linux, macOS和Windows中運行。如果您是編程新手,或者是其他語言的切換者,建議您使用thonny。界面乾淨無幹擾。新手可以專注於語言,而不必專注於設置環境。默認情況下,Thonny安裝程序會安裝Python 3.8。內置調試器和逐步執行評估。