python基礎學習

來源:互聯網
上載者:User

標籤:預設   訪問   綜合   表示   aaaaaa   變數   span   class   格式   

1.變數定義

Python的變數的類型不需要定義,只需要定義變數的名字,即a = 10
變數擷取的值為什麼類型,那麼該變數的資料類型即為該類型

2.資料的輸入

python的輸入採用input(),可以增加輸入時的提示即input("請輸入:")
需要注意的是python的預設輸入的類型都是string字串,那麼在需要數字是需要對資料進行強制轉化
如int(...), float(), str() 等等,涉及其他進階資料類型的轉換暫時不提。

1 int = int(input("整數:"))2 float = float(input("小數:"))3 string = input("字串:")
View Code

注意:當強制轉換的資料類型,無法成功轉換時,會報錯,此時就需要進行try拋異常

 1 try: 2  3        int = int(input("整數:")) 4        float = float(input("小數:")) 5        string = input("字串:") 6  7 except ValueError: 8        print("傳入無效參數!") 9 else:10        print("成功!")
View Code

這裡簡單的運用一下異常處理的內容

3.函數

python的函數樣式:def 函數名(<變數名>,<...>):
定義只需要一個關鍵字def,相對於其他語言,不需要設定傳回型別

 1 # 求和函數 2  3  4 def sum (a,b): 5        """求和""" 6  7        return a+b 8  9 # 預設參數10 11 12 def function(a,b = 50):13        """函數 預設參數"""14 15        print(a + "-" + b)16        return 
View Code

介紹兩種常用的傳參方式,預設參數的方式在傳參時如沒有傳入b的值,那麼b預設為50
在函數裡的第一行一般採用多行注釋的形式對函數進行描述,這樣在調用時對函數名Ctrl+q,就會顯示出對函數的註解,如所示:

最後,函數不管有沒有傳回型別,都加上return,表示結束

4.list列表

也可以稱為數組,部分功能上結合了資料結構中棧的思想

 1 # 建立列表和元組 2 list1 = ["aa", "bb", "cc", "dd"] 3 seq = ("ee", "ff") 4  5 # 長度 6 len(list1) 7  8 # 元群組轉換為列表 9 list2 = list(seq)10 11 # 添加元素12 list1.append(["ff"])13 list1.extend(list2)14 print(list1)15 16 # 查詢元素索引位置17 print(list1.index("ff"))18 19 # 插入20 list1.insert(0, ["gg"])21 print(list1)22 23 # 移除24 list1.pop(5)25 print(list1)26 list1.remove("ee")27 print(list1)28 list1.clear()
View Code

 建立列表和元組,這邊只介紹列表,元組就是不能改變值的列表,比較簡單
擷取列表的長度,採用len(),這個函數可以用在很多方面
添加元素,主要兩個append和extend,兩者都是只能在列表末尾添加,append能夠保留原來格式,如添加的是一個列表,那麼在顯示是裡面會嵌套一個列表
而extend是直接將對象裡面的內容拆分成一個個進行添加
index比較簡單,查詢存在值的索引,如果值不存在會報錯,採用這個方法需要注意
insert插入,傳入兩個變數插入的位置以及傳入的對象
移出有三種,pop(int),刪除指定位置的值,如果不填預設為末尾
remove(“值”),通過擷取值來刪除,這兩種方式如果值或位置不存在都會報錯
最後是clear,清空列表

5.字典

字典是通過key索引值來擷取對應的值

1 # 字典2 dictionary = {"name": "hjhj"}3 4 # 擷取值5 print(dictionary.get("name"))6 7 # 更新8 dictionary.update({"age": 20, "name": "aaaaaa"})9 print(dictionary)
View Code

字典是無序的,只有通過key值訪問
通過列表和字典的綜合使用,可以形成JSON格式的資料,對於網上抓取到的資料可以通過這種方式解析。

{"HeWeather": 
  [{"basic":{
    "cid":"CN101190401",
    "location":"蘇州",
    "parent_city":"蘇州",
    "admin_area":"江蘇",
    "cnty":"中國",
    "lat":"31.29937935",
    "lon":"120.61958313",
    "tz":"+8.00",
    "city":"蘇州",
    "id":"CN101190401",
    "update":{
      "loc":"2018-08-07 10:48",
      "utc":"2018-08-07 02:48"}},
    "update":{
      "loc":"2018-08-07 10:48",
      "utc":"2018-08-07 02:48"},
    "status":"ok",
    "now":{
      "cloud":"6",
      "cond_code":"104",
      "cond_txt":"陰",
      "fl":"37",
      "hum":"70",
      "pcpn":"0.0",
      "pres":"1006",
      "tmp":"33",
      "vis":"20",
      "wind_deg":"150",
      "wind_dir":"東南風",
      "wind_sc":"2",
      "wind_spd":"9",
      "cond":{
        "code":"104","txt":"陰"}
      },
    "daily_forecast":[
      {"date":"2018-08-07","cond":{"txt_d":"晴"},"tmp":{"max":"36","min":"28"}},
      {"date":"2018-08-08","cond":{"txt_d":"晴"},"tmp":{"max":"36","min":"27"}},
      {"date":"2018-08-09","cond":{"txt_d":"多雲"},"tmp":{"max":"36","min":"27"}}],
    "aqi":{
      "city":{"aqi":"39","pm25":"23","qlty":"優"}},
      "suggestion":{"comf":{"type":"comf","brf":"很不舒適","txt":"白天天氣晴好,但烈日炎炎會使您會感到很熱,很不舒適。"},"sport":{"type":"sport","brf":"較不宜","txt":"天氣較好,但氣溫很高,風力較大,請減少運動時間並降低運動強度,戶外運動須注意避風防晒。"},"cw":{"type":"cw","brf":"較適宜","txt":"較適宜洗車,未來一天無雨,風力較小,擦洗一新的汽車至少能保持一天。"}}}]}

6.字串

字串涉及的方法比較多,這裡簡單的介紹幾個常見的

 1 # 字串 2 string = "asd fghjkla sdf" 3  4 # 計數 5 num = string.count("a") 6 print(num) 7  8 # 找索引 9 num2 = string.index("a")10 print(num2)11 12 # 擷取指定位置字元13 print(string[0])14 15 # 分割16 list = string.split(" ")17 print(list)18 19 # 合并成字串20 list.insert(1, "ssssss")21 string2 = " ".join(list)22 print(string2)
View Code

 

-------------------------------------------------------------------------------------------------------------------------

暫時就到這

 

python基礎學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.