1. 程式人生 > >python學習筆記:python程式設計基礎

python學習筆記:python程式設計基礎

1、python的包的種類

自帶的包(built-in)package和外部(external)package

1.1 自帶package,舉例os、os.getwd().

 

3、環境變數中配置easy_install,pip

沒有提供引數,需要設定引數

easy_install --help 證明環境變數配置正確

 

4、使用easy_install,pip安裝package舉例

import os
import requests
print(os.getcwd())

r=requests.get("http://www.baidu.com")
print(r.url)
print(r.encoding)
print(r.text)

 

pip 可以用pip安裝額外的包

 

用pip嘗試安裝request

pip install requests

 

2.2 _Part2 字串(String),變數(Variable)

Format字串

age=3
name="Tom"
print("{0} waw {1} years old".format(name,age))

 

4、#註釋

#單行註釋

多行註釋:三引號,或者雙引號

 

5、縮排(identation)

縮排格式,使用縮排的時候會和程式的流程結合起來。

每行頂格寫,否則會出錯

 

第6課

 

例子:

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("c is type:",type(c))
print("e is type:",type(e))

 

print(a+b)
print(d/c)

print(b/a)
print(b//a) #約為整型

print(e)
print(e+f)

print(sys.float_info)

 

執行結果:

a is type: <class 'int'>

c is type: <class 'float'>

e is type: <class 'complex'>

7

1.4134275618374559

1.3333333333333333

1

(5.66+8j)

(8.66+12j)

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

 

3.1 資料結構:列表(List)

 

建立List

#建立List
number_list=[1,3,5,7,9]
print("number_list:"+str(number_list))

執行結果:

number_list:[1, 3, 5, 7, 9]

 

字串型別的 列表

string_list=["abc","bbc","python"]
print("string_list:"+str(string_list))

執行結果:
string_list:['abc', 'bbc', 'python']

 

資料型別和字串型別混合的列表

mixed_list=["python","java",3,12]
print("mixed_list:"+str(mixed_list))

執行結果:

mixed_list:['python', 'java', 3, 12]

 

訪問列表元素

#訪問列表中的元素
second_num=number_list[1]
third_string=string_list[2]
fourth_mixed=mixed_list[3]

print("second_num:{0} \nthird_string:{1}\nfourth_mixed:{2}".format(second_num,third_string,fourth_mixed))

執行結果:

second_num:3

third_string:python

fourth_mixed:12

 

更新元素

number_list[1]=30

print("number_list after:"+str(number_list))

執行結果:

number_list after:[1, 30, 5, 7, 9]

 

#刪除元素

del number_list[1]
print("number_list after:",number_list)

執行結果:

[1, 5, 7, 9]

 

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

3

[1, 2, 3, 4, 5, 6]

['Hello', 'Hello', 'Hello', 'Hello']

True


#列表的擷取
abcd_list=['a','b','c','d']
print(abcd_list[1]) #從左邊起,列表的第二位
print(abcd_list[-2]) #從右邊起,列表的第二位
print(abcd_list[1:]) #從左邊第二位開始擷取到所有剩下的元素

執行結果:

b

c

['b', 'c', 'd']

 

3.2 資料結構:元組(Tuple)

元祖一旦建立之後不可更改

#建立
number_tuple=(1,3,5,7,9)
# print("number_tuple:"+str(number_tuple))

string_tuple=("abc","bbc","python")
# print("string_tuple:"+str(string_tuple))

mixed_tuple=("python","java",3,12)
# print("mixed_tuple:"+str(mixed_tuple))

#訪問元組中的元素
second_num=number_tuple[1]
third_string=string_tuple[2]
fourth_mixed=mixed_tuple[3]

print("second_num:{0} \nthird_string:{1}\nfourth_mixed:{2}".format(second_num,third_string,fourth_mixed))

#更新元素,tuple不能被更改,所以程式會執行報錯
# number_tuple[1]=30
# print("number_tuple after:"+str(number_tuple))

#刪除元素,tuple不能被更改,所以程式會執行報錯
# del number_tuple[1]
# print("number_tuple after:",number_tuple)

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

#元組的擷取
abcd_tuple=('a','b','c','d')
print(abcd_tuple[1]) #從左邊起,列表的第二位
print(abcd_tuple[-2]) #從右邊起,列表的第二位
print(abcd_tuple[1:]) #從左邊第二位開始擷取

 

執行結果:

second_num:3

third_string:python

fourth_mixed:12

3

(1, 2, 3, 4, 5, 6)

HelloHelloHelloHello

True

b

c

('b', 'c', 'd')

 

tuple裡面的元素不能更改,但是能更改tuple裡面的list的元素

#建立只包含一個元素的tuple
a_tuple=(2,)

#建立tuple中的list
mixed_tuple=(1,2,['a','b'])

print("mixed_tuple:"+str(mixed_tuple))

#讀取tuple,更改tuple

mixed_tuple[2][0]='c'
mixed_tuple[2][1]='d'

print("mixed_tuple after:"+str(mixed_tuple))

執行結果:

mixed_tuple:(1, 2, ['a', 'b'])

3.3 字典(Dictionary)

資料型別如下

#建立字典,同一個字典裡可以出現多種不同的資料型別的元素
phone_book={'Tom':123,'Jerry':456,'Kim':789}
mixed_dict={'Tom':'boy',11:23.5}

#訪問字典中的值
print("Tom has phone number:"+str(phone_book['Tom']))

#修改字典中的值
phone_book['Tom']=999
print("Tom has phone number:"+str(phone_book['Tom']))

#新增
phone_book['Heath']=888
print('The added book is:'+str(phone_book))

#刪除字典中的元素
del phone_book['Tom']
print("The book after del is:"+str(phone_book))

#清空字典裡的資料
phone_book.clear()
print("The book after clear is:"+str(phone_book))

#刪掉整個字典
del phone_book
# print("The book after del all is:"+str(phone_book))

#特性
#一個字典裡面不允許出現兩個key相同的元素
rep_test={'Name':'aa',"age":5,"Name":'bb'}
print("rep_test:",rep_test)

#鍵是不可變的,可以用數字、字串、或者元組充當鍵,但是不可能用列表
#list_dict={['Name']:'John','Age':13} #執行時會報錯,因為不能用列表作為字典的鍵
list_dict={('Name'):'John','Age':13}
print("list_dict is:"+str(list_dict))

 

執行結果:

Tom has phone number:123

Tom has phone number:999

The added book is:{'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888}

The book after del is:{'Jerry': 456, 'Kim': 789, 'Heath': 888}

The book after clear is:{}

rep_test: {'Name': 'bb', 'age': 5}

list_dict is:{'Name': 'John', 'Age': 13}

 

 

3.4 函式(Function)Part1

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

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

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

執行結果:

happy Birthday!

 Happy Birthday !  Happy Birthday !  Happy Birthday !  Happy Birthday !

 

 

3.4 函式(Function)Part2

 

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)

def print_paras(fpara,*nums,**words):
   print("fpara:"+str(fpara))
   print("num:"+str(nums))
   print("words:"+str(words))

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

 

執行結果:

a is  13 and b is 17 and c is 8

a is  125 and b is 4 and c is 24

a is  80 and b is 4 and c is 40

fpara:hello

num:(1, 3, 5, 7)

words:{'word': 'python', 'another_word': 'java'}

 

 

4.1 控制流1:if & for 語句

 

if 語句例子:

number=59
guess=int(input('Enter an integer:'))
print('guess is :'+str(guess))

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')

 

for 語句例子:

for i in range(1,10):
    print(i)
else:
    print('the for loop is over')

 

for 例子2,遍歷列表

a_list=[1,3,5,7,9]
for i in a_list:
    print(i)

 

for 例子3,遍歷元組

a_tuple=(1,3,5,7,9)
for i in a_tuple:
    print(i)

 

For例子4

#遍歷字典
a_dict={'Tom':'111','Jerry':'222','Cathy':'333'}
for el in a_dict:
    print(el,':',a_dict[el])

 

For例子5

#用key和值,對字典進行遍歷
for key,elem in a_dict.items():
    print(key,":",elem)

 

 

 

4.2 控制流2:while& range 語句

import random

number=random.randint(0,1000)
print(number)
guess_flag=False
while guess_flag==False:
    print("==================================")
    guess=int(input('請輸入一個整數(0-1000):\n'))
    if guess==number:
        guess_flag=True
        print("恭喜您猜對了,但是沒有獎品,哈哈哈!!!")
    elif guess<number:
        print('錯了,您輸入的數字小於正確值。')
        print('正確值為:',number)
    elif guess>number:
         print('錯了,您輸入的數字大於正確值。')
         print('正確值為:',number)
    else:
         print("您輸入的數字不正確")
    print("==================================\n")

print("Done!!!")

 

固定次數迴圈

 

import random

num_change=5
number=random.randint(0,1000)
print(number)

for i in range(1,num_change+1):
    print("==================================")
    guess=int(input('請輸入一個整數(0-1000):\n'))
    if guess==number:
        print("恭喜您猜對了,但是沒有獎品,哈哈哈!!!")
        break
    elif guess<number:
        print('錯了,您輸入的數字小於正確值。')
        print("您還有"+str(num_change-i)+"次機會")
    elif guess>number:
         print('錯了,您輸入的數字大於正確值。')
         print( "\n您還有" + str(num_change-i) + "次機會")
    else:
         print("您輸入的數字不正確")
         print( + "\n您還有" + str(num_change-i) + "次機會")
    print("==================================\n")
print('正確值為:' + str(number) )

print("Done!!!")

 

4.3 Break、Continue、Pass

import random

 

number=random.randint(0,1000)

print(number)

guess_flag=False

while True:

    print("==================================")

    guess=int(input('請輸入一個整數(0-1000):\n'))

    if guess==number:

        print("恭喜您猜對了,但是沒有獎品,哈哈哈!!!")

        break

    elif guess<number:

        print('錯了,您輸入的數字小於正確值。')

        print('正確值為:',number)

        continue

    elif guess>number:

         print('錯了,您輸入的數字大於正確值。')

         print('正確值為:',number)

         continue

    else:

         print("您輸入的數字不正確")

         continue

print("==================================\n")

print("Done!!!")

 

#continue和Pass的例子

a_list=[0,1,2]

print("使用continue:")
for i in a_list:
        if not i:
            continue
        print(i)

print("使用Pass:")
for i in a_list:
      if not i:
          pass
      print(i)

5.1 輸入輸出方式介紹(Output  /  Format)

#take input from user
str_1=input("Enter a string:")
str_2=input("Enter another string:")

#ouput the strings
print("str_1 is :"+str_1+",str_2 is"+str_2)
print("str_1 is {},str_2 is {}".format(str_1,str_2))

 

 

5.2 讀寫檔案(FileIO)

1、讀入檔案

2、寫入檔案

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

#open for 'w'riting
f=open('sentence.txt','w')

#write text to file
f.write(some_sentences)
f.close()

#如果不是特殊mode,不用宣告'r'模式
f=open('sentence.txt')
while True:
    line=f.readline()
    if len(line)==0:
        break
    print(line)
#close the file
f.close()

 

6.1 異常處理

try:
    f=open('sentence.txt')
    s=f.readline()
    i=int(s.strip())
except OSError as err:
    print("OS error:{0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")

 

 

7.2 面想物件程式設計(Object-Oriented)和裝飾器(decorator)

class Student:
    def __init__(self,name,grade):
        self.name=name
        self.grade=grade

    def introduce(self):
        print("hi! I am "+self.name)
        print("my grade is {}".format(self.grade))

    def improve(self,amount):
        self.grade=self.grade+amount


jim=Student("jim",86)
jim.introduce()
jim.improve(10)
jim.introduce()

 

 

#裝飾器

'''
def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

def make_cake():
    return "cake"
gift_func=add_candles(make_cake)

print(make_cake())
print(gift_func())
'''

'''
def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

def make_cake():
    return "cake"

make_cake=add_candles(make_cake)

print(make_cake())
'''

def add_candles(cake_func):
    def insert_candles():
        return cake_func()+" and candles"
    return insert_candles

@add_candles  #裝飾器標識
def make_cake():
    return "cake"

print(make_cake())

 

 

 

8.1 圖形介面(GUI)和猜數字遊戲

 

import random
from tkinter import *

import tkinter.simpledialog as dl
import tkinter.messagebox as mb

#GUI
root=Tk()
w=Label(root,text="猜數字遊戲")
w.pack()

number=random.randint(0,1000)
guess_flag=False
num_change=5
mb.showinfo("歡迎","歡迎來到猜數字遊戲介面\n您只有"+str(num_change)+"次猜數字機會")
while True:
    if num_change==0:
        mb.showinfo("結束", "您的猜數字機會已經用完\n正確數字為"+str(number))
        break
    guess = dl.askinteger("數子", "請輸入一個數字:")
    num_change=num_change-1
    if guess==number:
           output = '恭喜您猜對了\n但是沒有獎品,哈哈哈!!!'
           mb.showinfo("Output:", output)
           break
    elif guess<number:
        output = '錯了\n您輸入的數字小於正確值。\n您還剩'+str(num_change)+"次猜數字機會"
        mb.showinfo("Output:", output)
        continue
    elif guess>number:
         output = '錯了\n您輸入的數字大於正確值。\n您還剩'+str(num_change)+"次猜數字機會"
         mb.showinfo("Output:", output)
         continue
    else:
        output = '錯了\n您輸入的數字格式不正確。\n您還剩'+str(num_change)+"次猜數字機會"
        mb.showinfo("Output:", output)
        continue

 

 

9 建立一個網頁

# -*- Coding:utf-8 -*-

import web

 

urls=(

    '/','index'

)

 

app=web.application(urls,globals())

 

class index:

    def GET(self):

         greeting ='Hello World'

         return greeting

 

if __name__=="__main__":

    app.run()