Python基础知识:数据类型与函数
生活随笔
收集整理的這篇文章主要介紹了
Python基础知识:数据类型与函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- Python3.x
1 數據類型
1.0 標準數據類型
Python3.x標準數據類型有6中,如下:
| 1 | 數字 | Number |
| 2 | 字符串 | String |
| 3 | 列表 | List |
| 4 | 元組 | Tuple |
| 5 | 字典 | Dictionary |
| 6 | 集合 | Set |
1.2 數字(Number)
數字包括整數,浮點數,布爾數據和復數四種,python3.x中將True和False定義成關鍵字,表示1和0,python2.x中沒有布爾類型,用1和0表示.
| 1 | bool | True,False |
| 2 | int | a=2,b=3 |
| 3 | float | a=2.2,b=20.5+e10,c=33.3-E22 |
| 4 | complex | a=4j,b=1+2j |
1.3 字符串(String)
- 單引號或雙引號表示,反斜杠\表示轉義字符,如換行\n.
- 截取字符串:變量[索引,位置]
- 左向右從0開始索引,右向左從-1開始索引;
| 1 | 字符串 | ‘a’,“a”,‘abc’,’\n’ |
1.5 元組
- tu = (“a”, “b”);
- 元組元素定義之后不能動態修改;
- tu[索引:位置];
| 1 | 元組 | (‘abc’, ‘b’,234) |
1.4 列表
- 列表元素獲取:變量[索引:位置];
- 列表可同時存儲不同類型的數據;
- 列表元素可動態添加;
| 1 | 列表 | li = [‘abc’,32,‘b’] |
1.6 字典
- dict = {“name”:“xindaqi”}
- key是唯一的
- 通過鍵獲取元素,dict[“key”];
- 遍歷鍵:dict.keys();
- 遍歷值:dict.values();
- 可動態添加鍵值對;
| 1 | 字典 | {‘key’:‘value’} |
1.7 集合
- 用于成員關系測試和刪除重復元素;
- sets = {“xin”, “daqi”};
- 空集合set();
- 可動態添加元素,即并集(|)和交集(&),補集(-);
- 不可遍歷;
| 1 | 集合 | {‘abc’,‘b’} |
1.8 數據類型及操作
| 1 | 字符串,采用str()顯示 | %s |
| 2 | 字符串,采用repr()顯示 | %r |
| 3 | 單個字符 | %c |
| 4 | 二進制整數 | %b |
| 5 | 十進制整數 | %d |
| 6 | 十進制整數 | %i |
| 7 | 八進制整數 | %o |
| 8 | 十六進制整數 | %x |
| 9 | 指數,基底為e | %e |
| 10 | 指數,基底為E | %E |
| 11 | 指數e或浮點數(根據顯示長度) | %g |
| 12 | 指數E或浮點數(根據顯示長度) | %G |
| 13 | 浮點數 | %f |
| 14 | 浮點數 | %F |
| 15 | 字符"%" | %% |
2 python函數
- python函數是組織好,可復用功能的代碼段。
- 格式:
2.1 定義并調用函數
#-*-coding:utf-8-*- #定義函數 def greet_user(user):print(user) #調用函數 greet_user('xindaqi')2.2 位置實參調用函數
#定義函數 def describe_pet(animal_type, pet_name):print("Animal type is " + animal_type)print("Animal name is " + pet_name) #位置實參 #按照順序賦值 describe_pet("Dog", "Li") describe_pet("Li", "Dog")2.3 關鍵字實參調用函數
#關鍵字實參 #給關鍵字變量直接賦值 describe_pet(animal_type="Cat", pet_name="G") #默認值:給形參賦值 def describe_goods(goods,made='China'):print("I want to buy " + goods + "!")print(goods + " made in " + made) describe_goods(goods='iPhone')2.4 函數返回值
#返回值 def return_0(user, age):info = user + " is " + agereturn info return_1 = return_0(user='xindaqi', age='22') print(return_1)2.5 根據實際參數,傳入實參
#實參可選 def get_name(first_name, last_name, middle_name=''):if middle_name:full_name = first_name + ' ' + middle_name + ' ' + last_nameelse:full_name = first_name + ' ' + last_namereturn full_name.title() people_info = get_name('daqi', 'xin') print(people_info)people_info1 = get_name('john', 'lala', 'hi') print(people_info1)2.6 調用函數,返回字典格式數據
#返回字典 def get_name_1(first_name, last_name):people = {'first': first_name, 'last': last_name}return people people = get_name_1('daqi', 'xin') print(people)2.6 實參為列表調用函數
#實參傳遞列表 def get_name_2(names):print(names) usernames = ['xindq', 'xinxq', 'xinerqi'] get_name_2(usernames)2.7 函數中修改列表及禁止修改列表
#函數中修改列表 for i in range(10):print("==",end='') print('\n') def student_name(all_stus, new_stus):while new_stus:current_stu = new_stus.pop()print(current_stu)all_stus.append(current_stu)def show_all_stus(all_suts):for stu in all_suts:print(stu)new_stus = ['xindaqi', 'xinxiaoqi', 'xinerqi'] all_stus = [] #保持原列表 student_name(all_stus, new_stus[:]) print(new_stus) #修改原列表 student_name(all_stus, new_stus) print(new_stus) show_all_stus(all_stus)2.8 實參為任意數量調用函數
#任意數量的實參 def goods(*toppings):for topping in toppings:print("-" + topping)goods('cup', 'shoes') goods('box', 'pencil', 'paper', 'ruler')2.9 位置實參和任意數量實參調用函數
#位置實參和任意數量實參 #函數接受不同類型實參,在函數定義時將接受任意數量實參的形參放在最后 def goods(num, *tops):print(num)for topping in tops:print("-" + topping) goods(12, 'cup', 'pencil')2.10 任意數量關鍵字實參調用函數
#任意數量關鍵字實參 #**stu_info創建一個空字典,將接受的所有鍵-值對封裝在字典中 def stu_info(first, last, **stu_info):profile = {}profile['first_name'] = firstprofile['last_name'] = last for key, value in stu_info.items():profile[key] = valuereturn profilestu_info = stu_info('daqi', 'xin',address='China',email='123@gmail.com') print(stu_info)3 模塊定義及使用
- 模塊
Python模塊是*.py文件,包含定義的類、對象、方法和函數等python代碼。
將第二章的代碼封裝成fun.py模塊。 - 導入整個模塊
import fun - 導入指定函數
from fun import stu_info
導入指定函數,調用函數時無需使用句點,直接使用函數名即可完成調用。 - 導入全部函數
from fun import *
導入全部函數時,調用函數無需使用句點,直接使用函數名即可完成調用。 - 指定模塊別名
import fun as F - 使用
model_name.funciton_name() - 代碼段
5 range和xrange
for i in range(4):print(i) from six.moves import xrange for i in xrange(4):print(i) 0 1 2 36 輸出位數
6.2 指定輸出位數
【兩位有效數據】
a = 1.323434 b = 20.23434 print("data: {:.2}".format(a)) print("data: {:.2}".format(b)) data: 1.3 data: 20e+01【小數點后數字個數】
a = 1.323434 b = 20.23434 print("data: {:.2f}".format(a)) print("data: {:.2f}".format(b))【Result】
data: 1.35 data: 20.246.2 字符串輸出
a = "tainlanlan" pirnt("data: {}".format(a)) data: tianlanlan7 總結
(1) 數據類型:
| 列表 | [“xin”,“daqi”] | 可動態修改元素,增刪 | 偏移量遍歷,索引+位置 |
| 字典 | {“name”:“xindaqi”} | 可動態修改值 | 鍵值對,通過鍵獲取數據 |
| 集合 | {“xin”, “daqi”} | 可動態修改(使用交,并,補集) | 不可索引 |
| 數字 | a=250 | 不可動態修改某個元素 | 不需索引 |
| 字符串 | string=“xindaqi” | 不可動態修改某一個元素 | 偏移量遍歷,索引+位置 |
| 元組 | tup = (“xin”,“daqi”) tup1 = (“xin”,)一個元素加, | 不可動態修改元組中的某個元素 | 偏移量索引,索引+位置 |
(2)使用函數讓程序更簡潔,易讀,良好的函數命名規則有助于程序的測試和后期維護。建議將工程函數封裝使用。
(3) range和xrange作用一致,而python3.x中xrange在six.moves中導入;
(4) format輸出有效數據格式:{:.n},其中n為有效數據位數;
[參考文獻]
[1]https://www.runoob.com/python3/python3-data-type.html
[2]https://www.runoob.com/python3/python3-module.html
總結
以上是生活随笔為你收集整理的Python基础知识:数据类型与函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 星际(stardict)
- 下一篇: 兄弟连专注IT教育 九周年再创辉煌