Python筆記之入門(基礎篇)__Python

來源:互聯網
上載者:User
Python 3筆記之入門 Python簡單介紹

  Python 是一個高層次的結合瞭解釋性、編譯性、互動性和物件導向的指令碼語言。Python 的設計具有很強的可讀性,相比其他語言經常使用英文關鍵字,其他語言的一些標點符號,它具有比其他語言更有特色文法結構。
   Python 是一種解釋型語言: 這意味著開發過程中沒有了編譯這個環節。類似於PHP和Perl語言。 Python 是互動式語言: 這意味著,您可以在一個Python提示符,直接互動執行寫你的程式。 Python 是物件導向語言: 這意味著Python支援物件導向的風格或代碼封裝在對象的編程技術。 Python 是初學者的語言:Python 對初級程式員而言,是一種偉大的語言,它支援廣泛的應用程式開發,從簡單的文文書處理到 WWW 瀏覽器再到遊戲。 Python 環境搭建 作業系統: win8 64bit 下載響應的win平台的Python安裝包 下載連結,將下載的安裝包按照提示安裝。 環境變數配置
程式和可執行檔可以在許多目錄,而這些路徑很可能不在作業系統提供可執行檔的搜尋路徑中。 Python 中文編碼

關於在sublime text中中文編碼的支援的問題
使用Sublime在build python程式時,有時候會遇到Decode error -output not utf-8或者是cp936。
原因是python編譯運行後的流的編碼方式和Sublime的解碼方式不同,Sublime Ctrl+B build一個python程式時,
輸出output not cp936,說明Sublime中的Python build預設接收的編碼是cp936,
如果你的python 程式是utf-8編碼,有漢字輸出時,Sublime就會報not cp936的錯誤。
如果報的是output not utf-8,說明python在編譯運行源碼後預設將輸出結果以cp936編碼發送給Sublime。
而Sublime中的預設接收編碼是utf-8。Sublime Text在接收到python輸出後,試圖以utf-8編碼cp936編碼的流。
當cp936編碼的流中沒有中文字元時,用utf-8解碼不會出錯,當cp936編碼的流中有中文字元時,因為漢子集在cp936與utf-8的編碼不相容,所以用utf-8解碼就會報錯。
解決問題的關鍵就是弄明白你的python程式的編碼和Sublime的python build中指定的編碼。
python sublime decode errorcp936 utf-8 output not utf-8utf-8 cp936 output not cp936比如,你的python代碼中制定了編碼格式是utf-8,現在sublime報錯了output not cp936的錯誤,則設定Sublime中python build編碼格式為utf-8,反之亦然。Python.sublime-build
位置:
Sublime Text 2 : SublimeText2/Data/Packages/Python/ Python.sublime-build
Sublime Text 3 :SublimeText3/Packages/Python.sublime-package
Python.sublime-build檔案:

{"cmd": ["python", "-u", "$file"],"file_regex": "^[ ]*File /"(...*?)/", line ([0-9]*)","selector": "source.python","encoding":"utf-8"}
input函數問題解決

關於使用者輸入的互動問題在sublime text中解決。
Sublime3編譯Python程式EOFError:EOF when reading a line。
具體的解決辦法已經在網上找到,連結在這裡,希望對你能夠有協助。總的來講就是: 下載一個SublimeRepl外掛程式; 將外掛程式放在如下圖所示的位置 啟動並執行時候按照下圖選擇:

解決方案

#!/usr/bin/pythonprint ("dddd中國")if True:    print ("true");    print ('true你好')else:    print ("false");    print ("dddd中國")word = 'word'sentence = "這是一個句子。"paragraph = """這是一個段落。包含了多個語句"""print (paragraph)'''注釋多行注釋'''item_one=1;item_two=2;item_three=4total = item_one + \        item_two + \        item_three;print (total);import sys; x = 'runoob'; sys.stdout.write(x + '\n')import sysprint (sys.stdin.encoding);print (sys.stdout.encoding);x = 'runoob'; sys.stdout.write(x + '\n')#input("\n\nPress the enter key to exit.")#測試輸入效果xx=input("\n\nPress the enter key to exit:");print (“當前的字元”+xx);
基礎文法的參考教程

這裡寫連結內容
其中這個教程主要是面向python2的,因此一些python3中有區別的地方,我在下面給出一下代碼案例: 資料類型

import sysprint (sys.stdin.encoding);print (sys.stdout.encoding);#自動類型封裝counter = 100 # 賦值整型變數miles = 1000.0 # 浮點型name = "John" # 字串print (counter)print (miles)print (name)a, b, c = 1, 2, "john"print (a)print (b)print (c)##Number  數字資料類型用於儲存數值。var1 = 1print (var1)var2 = 10##String 字串或串(String)是由數字、字母、底線組成的一串字元。str = 'Hello World!'print (str) # 輸出完整字串print (str[0]) # 輸出字串中的第一個字元print (str[2:5]) # 輸出字串中第三個至第五個之間的字串print (str[2:]) # 輸出從第三個字元開始的字串print (str * 2) # 輸出字串兩次print (str + "TEST") # 輸出串連的字串##list list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tinylist = [123, 'john']print list # 輸出完整列表print list[0] # 輸出資料行表的第一個元素print list[1:3] # 輸出第二個至第三個的元素 print list[2:] # 輸出從第三個開始至列表末尾的所有元素print tinylist * 2 # 輸出資料行表兩次##元組tou1 = ('11','33','23','1234124');print (tou1);tup1 = ('physics', 'chemistry', 1997, 2000);tup2 = (1, 2, 3, 4, 5, 6, 7 );print ("tup1[0]: ", tup1[0])print ("tup2[1:5]: ", tup2[1:5])tup3=tup1+tup2;print (tup3);#任意無符號的對象,用逗號隔開 預設為元組print ('abc', -4.24e93, 18+6.6j, 'xyz');x, y = 1, 2;print ("Value of x , y : ", x,y);dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};del dict['Name']; # 刪除鍵是'Name'的條目#dict.clear();     # 清空詞典所有條目#del dict ;        # 刪除詞典print ("dict['Age']: ", dict['Age']);#print ("dict['School']: ", dict['School']);
運算子 算術運算子 比較(關係)運算子 賦值運算子 邏輯運算子 位元運算符 成員運算子 身份運算子 運算子優先順序
##算術運算子a = 21b = 10c = 0c = a + bprint ("1 - c 的值為:", c)c = a - bprint ("2 - c 的值為:", c)c = a * bprint ("3 - c 的值為:", c) c = a / bprint ("4 - c 的值為:", c)c = a % bprint ("5 - c 的值為:", c)# 修改變數 a 、b 、ca = 2b = 3c = a**b print ("6 - c 的值為:", c)a = 10b = 5c = a//b print ("7 - c 的值為:", c)##比較子a = 21b = 10c = 0if ( a == b ):   print ("1 - a 等於 b")else:   print ("1 - a 不等於 b")if ( a != b ):   print ("2 - a 不等於 b")else:   print ("2 - a 等於 b")if ( a < b ):   print ("4 - a 小於 b") else:   print ("4 - a 大於等於 b")if ( a > b ):   print ("5 - a 大於 b")else:   print ("5 - a 小於等於 b")# 修改變數 a 和 b 的值a = 5;b = 20;if ( a <= b ):   print ("6 - a 小於等於 b")else:   print ("6 - a 大於  b")if ( b >= a ):   print ("7 - b 大於等於 b")else:   print ("7 - b 小於 b")##Python賦值運算子#a=6;c=2;c **= aprint ("6 - c 的值為:", c)c //= aprint ("7 - c 的值為:", c)##Python位元運算符c = a ^ b;        # 49 = 0011 0001print ("3 - c 的值為:", c)c = ~a;           # -61 = 1100 0011print ("4 - c 的值為:", c)c = a << 2;       # 240 = 1111 0000print ("5 - c 的值為:", c)c = a >> 2;       # 15 = 0000 1111print ("6 - c 的值為:", c)##Python邏輯運算子#a = 10b = 20if ( a and b ):   print ("1 - 變數 a 和 b 都為 true")else:   print ("1 - 變數 a 和 b 有一個不為 true")if ( a or b ):   print ("2 - 變數 a 和 b 都為 true,或其中一個變數為 true")else:   print ("2 - 變數 a 和 b 都不為 true")# 修改變數 a 的值a = 0if ( a and b ):   print ("3 - 變數 a 和 b 都為 true")else:   print ("3 - 變數 a 和 b 有一個不為 true")if ( a or b ):   print ("4 - 變數 a 和 b 都為 true,或其中一個變數為 true")else:   print ("4 - 變數 a 和 b 都不為 true")if not( a and b ):   print ("5 - 變數 a 和 b 都為 false,或其中一個變數為 false")else:   print ("5 - 變數 a 和 b 都為 true")##Python成員運算子a = 10b = 20list = [1, 2, 3, 4, 5 ];if ( a in list ):   print ("1 - 變數 a 在給定的列表中 list 中")else:   print ("1 - 變數 a 不在給定的列表中 list 中")if ( b not in list ):   print ("2 - 變數 b 不在給定的列表中 list 中")else:   print ("2 - 變數 b 在給定的列表中 list 中")# 修改變數 a 的值a = 2if ( a in list ):   print ("3 - 變數 a 在給定的列表中 list 中")else:   print ("3 - 變數 a 不在給定的列表中 list 中")##Python身份運算子a = 20b = 20if ( a is b ):   print ("1 - a 和 b 有相同的標識")else:   print ("1 - a 和 b 沒有相同的標識")if ( id(a) == id(b) ):   print ("2 - a 和 b 有相同的標識")else:   print ("2 - a 和 b 沒有相同的標識")# 修改變數 b 的值b = 30if ( a is b ):   print ("3 - a 和 b 有相同的標識")else:   print ("3 - a 和 b 沒有相同的標識")if ( id(a) is not id(b) ):   print ("4 - a 和 b 沒有相同的標識")else:   print ("4 - a 和 b 有相同的標識")##Python運算子優先順序a = 20b = 10c = 15d = 5e = 0e = (a + b) * c / d       #( 30 * 15 ) / 5print ("(a + b) * c / d 運算結果為:",  e)

基本語句

##Whilei = 1while i < 10:       i += 1    if i%2 > 0:     # 非雙數時跳過輸出        continue    print (i)         # 輸出雙數2、4、6、8、10i = 1while 1:            # 迴圈條件為1必定成立    print (i)         # 輸出1~10    i += 1    if i > 10:     # 當i大於10時跳出迴圈        break##for 迴圈語句for letter in 'Python':     # 第一個執行個體   print ('當前字母 :', letter)fruits = ['banana', 'apple',  'mango']for f in fruits:    print ("當前字母",f);for index in range(len(fruits)):   print ('當前fruit :', fruits[index])##python 中,for … else 表示這樣的意思,#for 中的語句和普通的沒有區別,else 中#的語句會在迴圈正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。for num in range(10,20):  # 迭代 10 到 20 之間的數字   for i in range(2,num): # 根據因子迭代      if num%i == 0:      # 確定第一個因子         j=num/i          # 計算第二個因子         print ('%d 等於 %d * %d' % (num,i,j))         break            # 跳出當前迴圈   else:                  # 迴圈的 else 部分      print (num, '是一個質數')###else是在for正常執行結束之後才會執行else'''Python break語句,就像在C語言中,打破了最小封閉for或while迴圈。break語句用來終止迴圈語句,即迴圈條件沒有False條件或者序列還沒被完全遞迴完,也會停止執行迴圈語句。break語句用在while和for迴圈中。如果您使用嵌套迴圈,break語句將停止執行最深層的迴圈,並開始執行下一行代碼。''''''Python continue 語句跳出本次迴圈,而break跳出整個迴圈。continue 語句用來告訴Python跳過當前迴圈的剩餘語句,然後繼續進行下一輪迴圈。continue語句用在while和for迴圈中。'''for letter in 'Python':     # 第一個執行個體   if letter == 'h':      continue   print ('當前字母 :', letter)var = 10                    # 第二個執行個體while var > 0:                 var = var -1   if var == 5:      break;   print ('當前變數值 :', var)'''Python pass 語句Python pass是空語句,是為了保持程式結構的完整性。pass 不做任何事情,一般用做佔位語句。'''for letter in 'Python':   if letter == 'h':      pass      print ('這是 pass 塊')   print ('當前字母 :', letter)##字串格式化輸出print ("My name is %s and weight is %d kg!" % ('Zara', 21) )hi = '''hi there'''repr(hi)print (repr(hi));print (str(hi))hi #reprlist = ['physics', 'chemistry', 1997, 2000];print ("Value available at index 2 : ")print (list[2]);list[2] = 2001;print ("New value available at index 2 : ")print (list[2]);print (len(list));print (1997 in list);print (list *4);print (list[1:]);print (list[1:3]);print (list[-2]);list.append(122);print (list)print (list.count(122));#print (list.reverse());print (list);print (len(list));mylist = ['aa','cc','bb'];print (mylist);print (min(mylist));print (max(mylist));print (list.reverse());
日期時間函數
##常用的工具函數import time;  # 引入time模組ticks = time.time()print ("目前時間戳為:", ticks)print (time.localtime(time.time()));# 格式化成2016-03-20 11:45:39形式print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )# 將格式字串轉換為時間戳記t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)secs = time.mktime( t )print ("time.mktime(t) : %f" % secs)print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))##calendar# 獲得今天的日期,並計算昨天和明天的日期'''You have a file called operator.py in the current directory,so import operator is picking up your module and not the Python standard library module operator.You should rename your file to not conflict with Python's standard library.'''import datetimeimport calendartoday = datetime.date.today()yesterday = today - datetime.timedelta(days = 1)tomorrow = today + datetime.timedelta(days = 1)print(yesterday, today, tomorrow)last_friday = datetime.date.today()oneday = datetime.timedelta(days = 1)while last_friday.weekday() != calendar.FRIDAY:    last_friday -= onedayprint(last_friday.strftime('%A, %d-%b-%Y'))today = datetime.date.today()target_day = calendar.FRIDAY; #目標print ("目標",target_day)this_day = today.weekday(); #今天的星期print ("today",this_day)delta_to_target = (this_day - target_day) % 7print ("求餘",delta_to_target)va = (0-4)%7;##負數求模就是做差print (va)last_friday = today - datetime.timedelta(days = delta_to_target)print(last_friday.strftime("%d-%b-%Y"))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.