1.Python基礎

序言

隨著AI人工智能的興起,沒有理由不趕緊學習起來了,之后我會把學習唐宇迪老師的系列課程以筆記的形式進行分享。廢話不多說,那就從python開始AI之旅吧

一、變量

1.申明變量,無需申明變量類型,無需分號
int_test = 365
str_test = "2月"
float_test = 122.5
bool_test = True

2.輸出
print(day)

3.判斷變量類型
print(type(int_test))
print(type(str_test))
print(type(float_test))
print(type(bool_test))
==============輸出結果==============
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>
===================================

4.類型轉換
#int轉string
  str_eight = str(8)
#string轉int ,注意必須是可以轉成功的值,如果是"test"將會報錯
  str_eight = "8"
  int_eight = int(str_eight)

5.運算
china=10
united_states=100
china_plus_10 = china + 10
us_times_100 = united_states * 100
print(china_plus_10)
print(us_times_100)
print (china**2)
==============輸出結果==============
20
10000
100
===================================

6.字符串的常用操作
 *split:分隔符,會將字符串分割成一個list
 yi = '1 2 3 4 5'
 yi.split()

*join:連接字符串,會與字符串中的每個字符元素進行一次拼接
yi = '1,2,3,4,5'
yi_str = '#'
yi_str.join(yi)

*replace:字符替換
yi = 'hello python'
yi.replace('python','world')

*字符串大寫:upper()
*字符串小寫:lower()

*去除空格
去除左右空格strip()
去除左空格lstrip()
去除右空格rstrip()

*字符賦值
'{} {} {}'.format('liu','yi','s')
'{2} {1} {0}'.format('liu','yi','s')
'{liu} {yi} {s}'.format(liu = 10, yi =5, s = 1)

二、List列表和tuple元組

************list**************
通過[]來創建一個list結構
里面放任何類型都可以的,沒有一個長度限制
1.申明、復制
months = []
print (type(months))
print (months)
months.append("January")
months.append("February")
print (months)
==============輸出結果==============
<class 'list'>
[]
['January', 'February']
===================================

2.根據索引取值
temps = ["China", 122.5, "India", 124.0, "United States", 134.1]
one = temps[0]
print(one)
last = temps[-1]
print(two)
==============輸出結果==============
China
134.1
===================================

3.獲取List長度
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
length = len(int_months) 

4.獲取List區間值
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
# 取前不取后
two_four = months[2:4]
print (two_four)
==============輸出結果==============
['Mar', 'Apr']
===================================
three_six = months[3:]
print (three_six)
==============輸出結果==============
['Apr', 'May', 'Jun', 'Jul']
===================================

5.刪除某個值del listname[i]
6.判斷list中是否有某個值 listname in a 返回一個bool類型
7.計數listname.count()
8.查看索引值listname.index('name')
9.插入listname.insert(2,'name')
10.刪除指定值listname.remove('name')
11.從小到達排序listname.sort()
12.對稱位置互換listname.reverse()

************tuple**************
另一種有序列表叫元組:tuple。tuple和list非常類似,但是tuple一旦初始化就不
能修改,此處的不能修改表示的是最初指定的指向不能進行修改,比如最初定義了
一個叫students的list,就一定得是這個list,但是list本身是可以改變的。
定一個學生元組:
students = ('tom', 'jack', ['liu','zhang','li'])
students[0] = 'lucy'---此處是不可以修改的
students[2][0]='wang'----這種修改操作是可行的

students這個tuple確定了就不能進行修改了,它也沒有insert()和append()
這樣的方法。其他獲取元素的方法和list是一樣的,你可以正常地使用
students[0],students[-1],但不能賦值成另外的元素。

不可變的tuple有什么意義?因為tuple不可變,所以代碼更安全。
如果可能,能用tuple代替list就盡量用tuple。


三、循環結構

1.for循環
cities = ["Austin", "Dallas", "Houston"]
for city in cities:
    #注意此處是以四個空格或者一個tab作為與for的關聯
    print(city)
#此處便與for沒有關系
print ('123')
==============輸出結果==============
Austin
Dallas
Houston
123
===================================

2.嵌套for循環
cities = [["Austin", "Dallas", "Houston"],['Haerbin','Shanghai','Beijing']]
#print (cities)
for city in cities:
    print(city)
    
for i in cities:
    for j in i:
        print (j)
==============輸出結果==============
['Austin', 'Dallas', 'Houston']
['Haerbin', 'Shanghai', 'Beijing']
Austin
Dallas
Houston
Haerbin
Shanghai
Beijing
===================================

3.while循環
i = 0
while i < 3:
    i += 1
    print (i)
==============輸出結果==============
1
2
3
===================================

四、判斷結構

number = 6
temp = (number > 5)
if temp:                    
    print(1)
else:
    print(0)
==============輸出結果==============
1
===================================

五、字典模式

字典是以key value的形式進行存儲,key必須保持唯一性
scores = {} 
print (type(scores))
scores["Jim"] = 80
scores["Sue"] = 85
scores["Ann"] = 75
#print (scores.keys())
print (scores)
print (scores["Sue"])

==============輸出結果==============
<class 'dict'>
{'Jim': 80, 'Sue': 85, 'Ann': 75}
85
===================================

2種初始化值的方式:
students = {}
students["Tom"] = 60
students["Jim"] = 70
print (students)

students = {
    "Tom": 60,
    "Jim": 70
}
print (students)
==============輸出結果==============
{'Tom': 60, 'Jim': 70}
{'Tom': 60, 'Jim': 70}
===================================

3.打印所有key值dict.keys()
4.打印所有value值dict.values()
5.打印所有的key,value值dict.items()

六、函數

def printHello():
    print ('hello python')
   
def add(a,b):
    return a+b
    
printHello()
print (add(1,2))

==============輸出結果==============
hello python
3
===================================

七、set集合

set和dict類似,也是一組key的集合,但不存儲value。由于key不能重復,所以,
在set中,沒有重復的key,主要用于保留唯一的那些元素。

set:一個無序和無重復元素的集合

定義:yi = set(['11','121','12313','11'])
     type(yi)

1.取并集a.union(b) 或a|b
2.取交集a.intersection(b) 或a&b
3.取差異值a.difference(b),差異出的是b中沒有的值,或者a-b
4.往集合中加值,setname.add(value),如果set中沒有value才有進行添加,一次只能添加一個值
5.一次更新多個值進去,setname.update([1,2,3])
5.刪除某個值,setname.remove(value)
6.彈出第一個值setname.pop(),也就是刪除第一個值

八、模塊與包

* 編寫一個腳本寫入到本地
  %%writefile tang.py

  tang_v = 10

  def tang_add(tang_list):
    tang_sum = 0
    for i in range(len(tang_list)):
        tang_sum += tang_list[i]
    return tang_sum
  tang_list = [1,2,3,4,5]
  print (tang_add(tang_list))

* 運行該腳本:%run tang.py

* 倒入該腳本并取一個別名import tang as tg
  倒入之后便可以隨意的調用腳本文件中的變量或者函數了
  tg.tang_v   tg.tang_add(tang_list)

*直接倒入某個變量或者函數
from tang import tang_v,tang_add

*倒入所有變量或者函數
from tang import *

*刪除該腳本,需要倒入一個系統的os庫
import os
os.remove('tang.py')
#當前路徑
os.path.abspath('.')

九、異常處理

基本用法:
try:
    1/0
except ValueError:
        print ('ValueError: input must > 0')
except ZeroDivisionError:
        print ('log(value) must != 0')
except Exception:
        print ('ubknow error')
finally:
    print ('finally')

自定義異常類:
class TangError(ValueError):
    pass

cur_list = ['tang','yu','di']
while True:
    cur_input = input()
    if cur_input not in cur_list:
        raise TangError('Invalid input: %s' %cur_input)

十、文件處理

1.文件讀取
#文件必須存在
f = open("test.txt", "r")

g = f.read()
print(g)
#讀完記得close
f.close()

2.寫入文件-覆蓋式的寫入
#文件可以不存在,沒有會自動創建
f = open("test_write.txt", "w")
f.write('123456')
f.write('\n')
f.write('234567')
f.close()

3.添加式的寫入
txt = open('tang_write.txt','a')

3.上述的方法都需要手動close文件,如果不想手動關閉文件可以使用with
with open('tang_write.txt','w') as f:
f.write('jin tian tian qi bu cuo')

十一、類

class people:
    '幫助信息:XXXXXX'
    #所有實例都會共享
    number = 100
    #構造函數,初始化的方法,當創建一個類的時候,首先會調用它
    #self是必須的參數,調用的時候可以不傳
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def display(self):
        print ('number = :',people.number)
    def display_name(self):
        print (self.name)

創建實例
p1 = people('yi',30)
p1.name

*判斷是否有該對象的屬性hasattr(p1,'name')
*獲取對象中的某個屬性值getattr(p1,'name')
*設置對象中的某個屬性值setattr(p1,'name','yudiTang')
*刪除對象中的某個屬性值delattr(p1,'name')

十二、時間

*打印時間戳
import time
print (time.time())

*數組的形式表示即(struct_time),共有九個元素,分別表示,同一個時間戳的
struct_time會因為時區不同而不同
time.localtime(time.time())

*格式化時間
time.asctime(time.localtime(time.time()))

*自定義格式化類型的時間
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

*日歷
import calendar
print (calendar.month(2017,11))
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容