1. 程式人生 > 其它 >基礎python的快速學習

基礎python的快速學習

  基礎語法快速學習下。

一:package

  自帶package和外部package

  外部package以及管理系統介紹: 使用easy_install, pip進行下載

import os
import requests

if __name__ == '__main__':
    # 自帶package
    a=os.getcwd()
    print(a)

    # 外部包
    r = requests.get('https://api.github.com/events')
    print(r.encoding)

二:資料型別

1.說明

  Python 中的變數賦值不需要型別宣告。

  每個變數在記憶體中建立,都包括變數的標識,名稱和資料這些資訊。

  每個變數在使用前都必須賦值,變數賦值以後該變數才會被建立。

2.型別

  Python有五個標準的資料型別:

  • Numbers(數字)
  • String(字串)
  • List(列表)
  • Tuple(元組)
  • Dictionary(字典)

三:數字

1.說明

  Python支援四種不同的數字型別:

  • int(有符號整型)
  • long(長整型,也可以代表八進位制和十六進位制)
  • float(浮點型)
  • complex(複數)

2.程式

# 數字型別

if __name__ == '__main__':
    a = 3
    b 
= 4 c = 5.66 d = 8.0 e = complex(c, d) f = complex(float(a), float(b)) print("a is type", type(a)) print("b is type", type(b)) print("c is type", type(c)) print("d is type", type(d)) print("e is type", type(e)) print("f is type", type(f)) print(a + b)
print(d / c) print(b / a) # 1,整除 print(b // a) # (5.66+8j) print(e) # (8.66+12j) print(e + f) print("e's real part is: ", e.real) print("e's imaginary part is: ", e.imag)

四:字串

1.說明

python的字串列表有2種取值順序:

  • 從左到右索引預設0開始的,最大範圍是字串長度少1
  • 從右到左索引預設-1開始的,最大範圍是字串開頭

2.程式

  基本操作,輸出

# 字串型別的程式碼

if __name__ == '__main__':
    # 字串的操作
    strDEmo = 'Hello World!'
    print(strDEmo)  # 輸出完整字串
    print(strDEmo[0])  # 輸出字串中的第一個字元
    print(strDEmo[2:5])  # 輸出字串中第三個至第六個之間的字串
    print(strDEmo[2:])  # 輸出從第三個字元開始的字串
    print(strDEmo * 2)  # 輸出字串兩次

    # 聯合
    print(strDEmo + "TEST")  # 輸出連線的字串

    # Format字串
    age = 3
    name = "Tom"
    print("{0} was {1} years old".format(name, age))

    # 中文
    zn = "你好"
    print(zn)

五:列表

1.說明

     建立      訪問      更新          刪除      指令碼操作符      函式方法   2.基本程式
# 列表程式

if __name__ == '__main__':
    # 建立一個列表
    number_list = [1, 3, 5, 7, 9]
    string_list = ["abc", "bbc", "python"]
    mixed_list = ['python', 'java', 3, 12]

    # 訪問列表中的值
    second_num = number_list[1]
    third_string = string_list[2]
    fourth_mix = mixed_list[3]
    print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix))

    # 更新列表
    print("number_list before: " + str(number_list))
    number_list[1] = 30
    print("number_list after: " + str(number_list))

    # 刪除列表元素
    print("mixed_list before delete: " + str(mixed_list))
    del mixed_list[2]
    print("mixed_list after delete: " + str(mixed_list))

    # Python指令碼語言
    print(len([1, 2, 3]))         # 長度
    print([1, 2, 3] + [4, 5, 6])  # 組合
    print(['Hello'] * 4)  # 重複
    print(3 in [1, 2, 3])  # 某元素是否在列表中

    # 列表的擷取
    # 字串也存在
    abcd_list = ['a', 'b', 'c', 'd']
    print(abcd_list[1])
    print(abcd_list[-2])
    print(abcd_list[1:])

3.其他的方法

  # 1、cmp(list1, list2):比較兩個列表的元素    # 2、len(list):列表元素個數    # 3、max(list):返回列表元素最大值    # 4、min(list):返回列表元素最小值    # 5、list(seq):將元組轉換為列表      # 列表操作包含以下方法:   # 1、list.append(obj):在列表末尾新增新的物件   # 2、list.count(obj):統計某個元素在列表中出現的次數   # 3、list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)   # 4、list.index(obj):從列表中找出某個值第一個匹配項的索引位置   # 5、list.insert(index, obj):將物件插入列表   # 6、list.pop(obj=list[-1]):移除列表中的一個元素(預設最後一個元素),並且返回該元素的值   # 7、list.remove(obj):移除列表中某個值的第一個匹配項   # 8、list.reverse():反向列表中元素   # 9、list.sort([func]):對原列表進行排序
 

六:元祖

1.說明

  元組是另一個數據型別,類似於 List(列表)。

  元組用 () 標識。內部元素用逗號隔開。但是元組不能二次賦值,相當於只讀列表。

2.程式

# 元組測試

if __name__ == '__main__':
    # 建立只有一個元素的tuple,需要用逗號結尾消除歧義
    a_tuple = (2,)

    # tuple中的list,可以進行修改
    mixed_tuple = (1, 2, ['a', 'b'])
    print("mixed_tuple: " + str(mixed_tuple))
    mixed_tuple[2][0] = 'c'
    mixed_tuple[2][1] = 'd'
    print("mixed_tuple: " + str(mixed_tuple))

    # 多次賦值
    v = ('a', 'b', 'e')
    (x, y, z) = v
    print(x)

七:字典

1.說明

  字典(dictionary)是除列表以外python之中最靈活的內建資料結構型別。列表是有序的物件集合,字典是無序的物件集合。

  兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。

  字典用"{ }"標識。字典由索引(key)和它對應的值value組成。

2.程式

# 字典型別

if __name__ == '__main__':
    # 建立一個詞典
    phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789}
    mixed_dict = {"Tom": 'boy', 11: 23.5}

    # 訪問詞典裡的值
    print("Tom's number is " + str(phone_book['Tom']))
    print('Tom is a ' + mixed_dict['Tom'])

    # 修改詞典
    phone_book['Tom'] = 999
    phone_book['Heath'] = 888
    print("phone_book: " + str(phone_book))

    # 如果沒有,則新增
    phone_book.update({'Ling': 159, 'Lili': 247})
    print("updated phone_book: " + str(phone_book))

    # 刪除詞典元素以及詞典本身
    del phone_book['Tom']
    print("phone_book after deleting Tom: " + str(phone_book))

    # 清空詞典
    phone_book.clear()
    print("after clear: " + str(phone_book))

    # 刪除詞典
    del phone_book

    # 不允許同一個鍵出現兩次。展示的是後一個
    rep_test = {'Name': 'aa', 'age': 5, 'Name': 'bb'}
    print("rep_test: " + str(rep_test))

八:函式

1.上程式

  一些型別的函式下面有說明

# 沒有引數和返回的函式
def say_hi():
    print(" hi!")

say_hi()
say_hi()


# 有引數,無返回值
def print_sum_two(a, b):
    c = a + b
    print(c)

print_sum_two(3, 6)



# 有引數,有返回值
def repeat_str(str, times):
    repeated_strs = str * times
    return repeated_strs

repeated_strings = repeat_str("Happy Birthday!", 4)
print(repeated_strings)


#全域性變數與區域性 變數
x = 60

def foo(x):
    print("x is: " + str(x))
    x = 3
    print("change local x to " + str(x))

foo(x)
print('x is still', str(x))


# 預設引數
def repeat_str(s, times=1):
    repeated_strs = s * times
    return repeated_strs

repeated_strings = repeat_str("Happy Birthday!")
print(repeated_strings)

repeated_strings_2 = repeat_str("Happy Birthday!", 4)
print(repeated_strings_2)


# 關鍵字引數: 呼叫函式時,選擇性的傳入部分引數
def func(a, b=4, c=8):
    print('a is', a, 'and b is', b, 'and c is', c)

func(13, 17)
func(125, c=24)
func(c=40, a=80)


# VarArgs引數
def print_paras(fpara, *nums, **words):
    print("fpara: " + str(fpara))  # fpara: hello
    print("nums: " + str(nums))    # nums: (1, 3, 5, 7)
    print("words: " + str(words))  # words: {'word': 'python', 'anohter_word': 'java'}

print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")

九:控制語句

1.if控制語句

#if

number = 59
guess = int(input('Enter an integer : '))

if guess == number:
    print('Bingo! you guessed it right.')
    print('(but you do not win any prizes!)')
elif guess < number:
    print('No, the number is higher than that')
else:
    print('No, the number is a  lower than that')

print('Done')

2.while用法

#while example

number = 59
guess_flag = False

while guess_flag == False:
    guess = int(input('Enter an integer : '))
    if guess == number:
        guess_flag = True
    elif guess < number:
        print('No, the number is higher than that, keep guessing')
    else:
        print('No, the number is a  lower than that, keep guessing')

print('Bingo! you guessed it right.')
print('Done')

3.for用法

#For

number = 59
num_chances = 3
print("you have only 3 chances to guess")

for i in range(1, num_chances + 1):
    print("chance " + str(i))
    guess = int(input('Enter an integer : '))
    if guess == number:
        print('Bingo! you guessed it right.')
        break
    elif guess < number:
        print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
    else:
        print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')


print('Done')

4.關鍵字brank,continue,pass

  和java中的一樣

十:檔案操作

1.程式

## 用Python內建的open()函式開啟一個檔案,建立一個file物件,相關的方法才可以呼叫它進行讀寫
import os

some_sentences = '''\
I love learning python
because python is fun
and also easy to use
'''

# 開啟一個檔案用於讀寫。如果該檔案已存在,檔案指標將會放在檔案的結尾。檔案開啟時會是追加模式。如果該檔案不存在,建立新檔案用於讀寫。
fileName = 'sentences.txt'
f = open(fileName, 'a+')
f.write(some_sentences)
f.close()

# 讀取
f = open('sentences.txt')
while True:
    line = f.readline()
    if len(line) == 0:
        break
    print(line)
# 重新整理緩衝區裡任何還沒寫入的資訊
f.close()

# 查詢當前位置
fo = open("foo.txt", "r")
position = fo.tell()
print("當前檔案位置 : ", position)

# 把指標再次重新定位到檔案開頭
position = fo.seek(0, 0)
str1 = fo.read(10)
print("重新讀取字串 : ", str1)
fo.close()

#os模組提供了幫你執行檔案處理操作的方法,比如重新命名和刪除檔案
# os.rename("original.txt", "senten4444ces2.txt")
# os.remove("original.txt")

# 顯示當前的工作目錄
os.getcwd()


# 建立目錄test
os.mkdir("test")
# 刪除目錄
os.rmdir('test')

十一:面向物件

1.