洞悉 Python基礎概況

2020-12-24 18:00:33
欄目介紹掌握Python基礎概況

推薦(免費):

Python基礎

theme: juejin

highlight: Python基礎
Python 是一種解釋型、物件導向、動態資料型別的高階程式設計語言。
Python 由 Guido van Rossum 於 1989 年底發明,第一個公開發行版發行於 1991 年。像 Perl 語言一樣, Python 原始碼同樣遵循 GPL(GNU General Public License) 協定。官方宣佈,2020 年 1 月 1 日, 停止 Python 2 的更新。Python 2.7 被確定為最後一個 Python 2.x 版本。
出自 www.runoob.com/python/pyth…

一. 變數型別

在Python中沒有和C , Java一樣要求對於基本變數的定義所以只要定義其變數名稱直接賦值就行,類似於預設javascript中的var只是作為一個宣告,這是一個變數。
# 位元組 字串 整型 浮點型 bool型別
# pass 換行
# true false 代表布林做if判斷使用
var0 = 'a'print(var0)pass
var1 = "hr"print(var1)pass
var2 = 10print(var2)pass
var3 = 100000.00print(var3)pass
# 注意:True 與 False 在python中首字母需要大寫的
varTrue = True
varFalse = Falseif varTrue:
    print("bool值True is True")else:
    print("bool值false is True")passif not varFalse:
    print("bool值True is False")else:
    print("bool值false is False")pass
# 字串的用法
str = "你是誰老豆?"# 只需要前兩位print(str[:2])# 需要第2位到最後一位print(str[2:len(str) - 1])pass
# 列表(List)用法
list1 = ['python', 'java', 1996, 2020]list2 = [1, 2, 3, 4, 5]list3 = ["a", "b", "c", "d"]# 列表的資料項不需要具有相同的型別,型別為 Objectprint(list1)# 可以自由拼接print(list1 + list2)# 可以自由使用任意型別拼接該陣列中 使用方法 append
# 方式1:
list3.append(1)list3.append(2)list3.append(3)print(list3)# 方式2:(注意新增的如果是個陣列 格式為:[ ... , [], ... ])list3.insert(2, 3)list3.insert(2, list1)print(list3)# 刪除指定下標的資料
# 方式1:
del list3[1]print(list3)# 方式2:
list3.remove("c")print(list3)pass
# 元元件 (類似於陣列列表 元組使用的是() 而 列表(list)使用的是[])a = (1, 2, 3, 4, 5, "1", "2")print(a)pass
# 字典 (是一個key value 的 hash值)a = {"key1": "value1", "key2": "value2"}print(a)# 存取字典裡的值
# 方法 1:print(a["key1"])# 方法 2:print(a.get("key1"))# 修改字典中資料
a["key2"] = "my love"print(a["key2"])# 刪除字典中資料
del a['key2']  # 刪除鍵是'Name'的條目
# a.clear()      # 清空字典所有條目
# del a          # 刪除字典print(a)pass
複製程式碼

二. 算術運運算元

運運算元描述
+a值 + b值
-a值 - b值
*a值 * b值
/a值 / b值
%a值 % b值
**a值 ** b值
//a值 // b值
# Python -- 運運算元
int1 = 2int2 = 6int3 = 8int4 = 10int5 = 3# 加法print("int加法: ", int1 + int2)# 減法print("int減法: ", int4 - int2)# 乘法print("int乘法: ", int3 * int2)# 除法print("int除法: ", int4 / int1)# 取模print("int取模: ", int4 % int5)# 冪等print("int冪等: ", int1 ** int2)# 取整除print("int整除: ", int4 // int5)pass
double1 = 10.00double2 = 20.10double3 = 30.20double4 = 40.30# 加法print("double加法:", double1 + double2)# 減法print("double減法:", double4 - double3)# 乘法print("double乘法:", double4 * int2)# 除法print("double除法:", double4 / int1)# 取模print("double取模:", double4 / double1)# 冪等print("double冪等: ", double4 ** int2)# 取整除print("double整除: ", double4 // int5)複製程式碼

三. 條件語句與迴圈語句

常用語句:
1. if…else…
2. while
3. for
4. break,continue
# if...else 條件語句
a = 0if a == 0:
    print("我等於0哦!")else:
    print("我不等於0哦!")pass
# while 迴圈語句
# 1. while 無限迴圈 (注意:使用 Stop 或者 Ctrl+C 結束)a = 0b = 0while a == 0:
    print("我來了第", b, "次!")
    b = b + 1# 2. while 條件迴圈
a = 0while a < 5:
    print("我是", a, "號!")
    a = a + 1# 3. while 迴圈語句 + 條件語句
a = 0exact = []not_exact = []while a < 10:
    # 0 - 10 是否存在被整除的數    if a % 2 == 0:
        exact.append(a)
    # 不能被整除的數    else:
        not_exact.append(a)
    a = a + 1else:
    print("這個迴圈我結束了!")print("能被被整除的數:", exact)print("不能被被整除的數:", not_exact)pass
# 4. while 迴圈語句 + 條件語句 + 跳出迴圈
a = 0exact = []while a < 10:
    # 0 - 10 是否存在被整除的數    if a % 2 == 0:
        exact.append(a)
    # 不能被整除的數    else:
        a = a + 1
        continue
    a = a + 1print("能被被整除的數 continue :", exact)pass
# 5. while 迴圈語句 + 條件語句 + 跳出迴圈
a = 0exact = []while a < 10:
    # 0 - 10 是否存在被整除的數    if a % 2 == 0:
        exact.append(a)
    # 不能被整除的數    else:
        a = a + 1
        break
    a = a + 1print("能被被整除的數 break :", exact)pass
# for 迴圈語句
# 1. for 迴圈
a = [1, 2, 3, "4", 5, True]for b in a:
    print(b)pass
# 2. for 迴圈 + 條件語句
a = [1, 2, 3, "4", 5, True, 9, '10']b = False
d = []for c in a:
    if c == True:
        b = True        continue
    d.append(c)print("含有bool值嗎? ", b)print("不含bool值的陣列:", d)pass
複製程式碼

四. 日期與時間

# 日期與時間
# 引入time模組import time
pass
# 獲取毫秒值
ticks = time.time()print("當前時間戳為:", ticks)pass
# 獲取本地時間
localtime = time.localtime(time.time())print("本地時間為 :", localtime)pass
# 獲取有時間結構的資料
localtime = time.asctime(time.localtime(time.time()))print("本地時間為 :", localtime)pass
# 1. 格式化時間:
# 格式化成2020-12-04 15:44:05形式print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))# 格式化成Fri Dec 04 15:44:05 2020形式print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))# 將格式字串轉換為時間戳
a = "Sat Mar 28 22:24:24 2016"print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))pass
# 2. 獲取某月日曆
# 引入Calendar模組有很廣泛的方法用來處理年曆和月曆,例如列印某月的月曆import calendar
cal = calendar.month(2020, 1)print("輸出2020年1月份的日曆:")print(cal)pass
複製程式碼

五. 函數與模組(Module)

1. 函數是組織好的,可重複使用的,用來實現單一,或相關聯功能的程式碼段。
2. 函數能提高應用的模組性,和程式碼的重複利用率。
3. 模組 能定義函數,類和變數,模組裡也能包含可執行的程式碼。
# 自定義一個函數
def test_function(str):
    if str % 2 == 0:
        return str    else:
        return False

str = 3print(test_function(str))複製程式碼
# 匯入模組import dbtest
# 使用模組中的函數print(dbtest.test_function(2))pass
複製程式碼

六. File檔案使用方法

# input([prompt]) 函數可以接收一個Python表示式作為輸入,並將運算結果返回
str = input("請輸入:")print("最終值為:", str)pass
# open函數
# file object = open(file_name [, access_mode][, buffering])# 1.file_name:file_name變數是一個包含了你要存取的檔名稱的字串值。
# 2.access_mode:access_mode決定了開啟檔案的模式:唯讀,寫入,追加等。所有可取值見如下的完全列表。這個引數是非強制的,預設檔案存取模式為唯讀(r)。
# 3.buffering:如果buffering的值被設為0,就不會有寄存。如果buffering的值取1,存取檔案時會寄存行。如果將buffering的值設為大於1的整數,表明了這就是的寄存區的緩衝大小。如果取負值,寄存區的緩衝大小則為系統預設。
# 4.encoding: 一般使用utf8
# 5.errors: 報錯級別
# 6.newline: 區分換行符
# 7.closefd: 傳入的file引數型別
# 8.opener: 設定自定義開啟器,開啟器的返回值必須是一個開啟的檔案描述符
fo = open("D:\\桌面\\test.txt", "w+", -1)print("檔名: ", fo.name)print("是否已關閉 : ", fo.closed)print("存取模式 : ", fo.mode)# print("末尾是否強制加空格 : ", fo.softspace)pass
# 寫入檔案內容 write([string])fo.write("當一個檔案物件的參照被重新指定給另一個檔案時,Python 會關閉之前的檔案。用 close()方法關閉檔案是一個很好的習慣。")print("寫入成功!")pass
# 讀取檔案內容 read([number])var = fo.read(10)print("檔案內容:", var)pass
# 檔案定位 tell()print("檔案位置:", fo.tell())pass
# close 關閉
# 當一個檔案物件的參照被重新指定給另一個檔案時,Python 會關閉之前的檔案。用 close()方法關閉檔案是一個很好的習慣。
fo.close()print("已關閉")pass
# 檔案重新命名 os.rename([string -- old],[string -- new])import os
var1 = "D:\\桌面\\test.txt"var2 = "D:\\桌面\\test2.txt"os.rename(var1, var2)print(var1, "已重新命名", var2)pass
# 檔案移除(檔案刪除)os.remove([string -- filename])os.remove(var2)print(var2, ",該檔案已被刪除!")pass
# 改變當前目錄 chdir([string]) 方法
var3 = "D:\\桌面\\"os.chdir(var3)print("已跳轉目錄至:", var3)pass
# 建立資料夾方式 os.mkdir([string])var4 = "123456789"# os.mkdir(var4)print("建立成功!")pass
# os.rmdir([string]) rmdir()方法刪除目錄,目錄名稱以引數傳遞。 刪除資料夾
var5 = var3+var4
# os.rmdir(var5)print(var3, var4, ",該檔案已被刪除!")pass
# File 寫入多行檔案 writelines([string])var6 = "D:\\桌面\\test123.txt"# 建立檔案 os.mknod([string -- file_path])# os.mknod(var6)fo2 = open(var6, "w+")# readline() 方法用於從檔案讀取整行,包括 "\n" 字元。如果指定了一個非負數的引數,則返回指定大小的位元組數,包括 "\n" 字元
line_read = fo2.readline(10)print("讀取的字串為: %s" % line_read)# writelines() 方法用於向檔案中寫入一序列的字串
a = 0while 10 > a:
    fo2.writelines("我開始嘍!")
    a += 1print("錄入成功!")pass

# isatty() 方法檢測檔案是否連線到一個終端裝置,如果是返回 True,否則返回 False
ret = fo2.isatty()print(ret)# 重新整理緩衝區
fo2.flush()# 關閉檔案
fo2.close()pass

以上就是洞悉 Python基礎概況的詳細內容,更多請關注TW511.COM其它相關文章!