Python基礎文法

來源:互聯網
上載者:User

標籤:Python   基礎語   

[TOC]

1.變數基礎與單一資料型別1.1變數解釋

變數儲存在記憶體中的值。這就意味著在建立變數時會在記憶體中開闢一個空間

name = ‘python‘number = 2017print(name);print(number);output:python2017
1.2變數命名規則

b變數名包含數字,字幕,底線,但是不能以數字開頭,可以字母或者底線開頭
變數名不能包含空格
變數名不能是python的關鍵字,也不能是python的內建函數名
變數名最好是見名知義

1.3字串1.3.1字串拼接
name = ‘python‘;info = ‘hello world‘;#python 中字串拼接使用(+)實現print(name+" "+info);output:python hello world
1.3.2 字串產常用函數

title : 首字母大寫的方式顯示每個單詞

upper : 字串全部轉化大寫

lower : 字串全部轉化為小寫

strip : 刪除字串兩端的空格

lstript : 刪除字串左端的空格

rstrip : 刪除字串右端的空格

str : 將非字元表示為字串

#使用樣本name = ‘python‘;number = 2017;info = ‘Hello world‘;#python 中字串拼接使用(+)實現newstr = name+" "+info;print(newstr);print(newstr.title());print(newstr.lower());print(newstr.upper());output:python Hello worldPython Hello Worldpython hello worldPYTHON HELLO WORLD
2.列表2.1列表釋義

列表是一系列按照特定順序排列的元素集合,一個列表中可以包含多個元素,每個元素之間可以沒有任何關係

2.2列表定義

在Python中使用中括弧 [ ] 來表示一個列表,列表中的元素使用英文逗號隔開

①列表中元素的索引是從0開始的 ②將索引指定為 -1 就指向了最後一個元素 ③ 指定索引超過了列表的長度,會報錯

2.3訪問列表中的元素
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘廣州‘,‘武漢‘,‘杭州‘,‘成都‘,‘重慶‘,‘長沙‘,‘南京‘];print(citys);print(citys[0]);print(citys[-1]);print(citys[1].upper());output:[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘南京‘]北京南京BEIJING
2.4列表操作2.4.1修改列表中元素
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘廣州‘,‘武漢‘,‘杭州‘,‘成都‘,‘重慶‘,‘長沙‘,‘南京‘];print(citys);#修改列表citys中第二個元素的值citys[1] = ‘雄安新區‘;print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘南京‘][‘北京‘, ‘雄安新區‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘南京‘]
2.4.2給列表添加元素
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘廣州‘,‘武漢‘,‘杭州‘,‘成都‘,‘重慶‘,‘長沙‘,‘南京‘];print(citys);#在列表末尾追加新的元素citys.append(‘南昌‘);citys.append(‘廈門‘);#在列表指定的索引位置添加新的元素citys.insert(1,‘石家莊‘);print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘南京‘][‘北京‘, ‘石家莊‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘南京‘, ‘南昌‘, ‘廈門‘]
2.4.3刪除列表中的元素
citys = [‘北京‘,‘beijing‘,‘上海‘,‘深圳‘,‘廣州‘,‘武漢‘,‘杭州‘,‘成都‘,‘重慶‘,‘長沙‘,‘小島‘,‘南京‘];print(citys);#刪除指定索引的元素del citys[1];print(citys);#彈出列表末尾或者指定位置的元素,彈出的值可以被接收result_end = citys.pop();result_index = citys.pop(3);print(result_end);print(result_index);print(citys);#刪除指定值的元素citys.remove(‘小島‘);print(citys);output[‘北京‘, ‘beijing‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘小島‘, ‘南京‘][‘北京‘, ‘上海‘, ‘深圳‘, ‘廣州‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘小島‘, ‘南京‘]南京廣州[‘北京‘, ‘上海‘, ‘深圳‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘, ‘小島‘][‘北京‘, ‘上海‘, ‘深圳‘, ‘武漢‘, ‘杭州‘, ‘成都‘, ‘重慶‘, ‘長沙‘]
2.4.4重組列表
lists_1 = [‘one‘,‘five‘,‘three‘,‘wo‘,‘xx‘,‘hhh‘];lists_2 = [‘one‘,‘five‘,‘three‘,‘wo‘,‘xx‘,‘hhh‘];#sort()按字母進行永久排序lists_1.sort();print(‘列表list_1排序之後的結果:‘)print(lists_1);#sort(reverse=True)按字母進行永久排序print(‘列表list_1逆排序之後的結果:‘)lists_1.sort(reverse=True);print(lists_1);#sorted()對列表按字母進行臨時排序list2_tmp = sorted(lists_2);list2_tmp_reverse = sorted(lists_2,reverse=True);print(‘列表list2_tmp臨時排序之後的結果:‘)print(list2_tmp);print(‘列表list2_tmp_reverse臨時逆排序之後的結果:‘)print(list2_tmp_reverse);print(‘列表list_2臨時排序之後,但是原來列表不變:‘)print(lists_2);output列表list_1排序之後的結果:[‘five‘, ‘hhh‘, ‘one‘, ‘three‘, ‘wo‘, ‘xx‘]列表list_1逆排序之後的結果:[‘xx‘, ‘wo‘, ‘three‘, ‘one‘, ‘hhh‘, ‘five‘]列表list2_tmp臨時排序之後的結果:[‘five‘, ‘hhh‘, ‘one‘, ‘three‘, ‘wo‘, ‘xx‘]列表list2_tmp_reverse臨時逆排序之後的結果:[‘xx‘, ‘wo‘, ‘three‘, ‘one‘, ‘hhh‘, ‘five‘]列表list_2臨時排序之後,但是原來列表不變:[‘one‘, ‘five‘, ‘three‘, ‘wo‘, ‘xx‘, ‘hhh‘]
lists_1 = [‘one‘,‘five‘,‘three‘,‘wo‘,‘xx‘,‘hhh‘];#對列表進行永久反轉;lists_1.reverse();print(lists_1);#統計列表的長度result_len = len(lists_1);print(result_len);print(lists_1.__len__());output[‘hhh‘, ‘xx‘, ‘wo‘, ‘three‘, ‘five‘, ‘one‘]66
2.4.5 列表迴圈操作
citys = [‘北京‘,‘上海‘,‘深圳‘,‘廣州‘,‘武漢‘,‘杭州‘,‘成都‘,‘重慶‘,‘長沙‘,‘南京‘];otherCitys = [];for city in citys:    print(city+‘ is nice‘);    otherCitys.append(city);otherCitys.reverse();print(otherCitys);output北京 is nice上海 is nice深圳 is nice廣州 is nice武漢 is nice杭州 is nice成都 is nice重慶 is nice長沙 is nice南京 is nice[‘南京‘, ‘長沙‘, ‘重慶‘, ‘成都‘, ‘杭州‘, ‘武漢‘, ‘廣州‘, ‘深圳‘, ‘上海‘, ‘北京‘]
2.4.6 建立數值列表
#建立一個數值列表list_num = list(range(1,10,2));print(list_num);sq = [];for num in list_num:    result = num**2;    sq.append(result);print(sq);#擷取列表中的最小值print(min(sq));#擷取列表中的最大值print(max(sq));#擷取數值列表的總和print(sum(sq));output[1, 3, 5, 7, 9][1, 9, 25, 49, 81]181165
2.4.7 使用列表一部分 切片
num = [‘zero‘,‘one‘,‘two‘,‘three‘,‘four‘,‘five‘,‘six‘,‘seven‘,‘eight‘,‘nine‘,‘ten‘];print(num);print(num[:5]);print(num[5:]);print(num[1:4]);print(num[-3:]);# 切片複製num_part = num[1:5];print(num_part);output:[‘zero‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘, ‘six‘, ‘seven‘, ‘eight‘, ‘nine‘, ‘ten‘][‘zero‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘][‘five‘, ‘six‘, ‘seven‘, ‘eight‘, ‘nine‘, ‘ten‘][‘one‘, ‘two‘, ‘three‘][‘eight‘, ‘nine‘, ‘ten‘][‘one‘, ‘two‘, ‘three‘, ‘four‘]
2.4.8元組

元素值不可變的列表稱為元組

#定義一個元組 使用();coordinate = (39.9,116.3);print(coordinate[0]);print(coordinate[1]);#擷取元組的長度print(len(coordinate));#遍曆元組for val in coordinate:    print(val);#不能修改元組中的單個元素的值,但是可以給儲存元組的變數賦值coordinate = (111,222);print(coordinate);output39.9116.3239.9116.3(111, 222)
3.字典3.1 字典基礎使用3.1.1 建立字典

字典是一系列的索引值對,每一個鍵都和一個值相關聯,值可以是數字、字串、列表、字典或者python對象

# 建立一個有索引值對的字典people_0 = {‘name‘:‘張三‘,‘age‘:99,‘addr‘:‘Beijing‘,‘children‘:{‘son‘:‘張源風‘,‘daughter‘:‘張慕雪‘}}# 建立一個空字典people_1 ={};
3.1.2 訪問字典中的元素
people_0 = {‘name‘:‘張三‘,‘age‘:99,‘addr‘:‘Beijing‘,‘children‘:{‘son‘:‘張源風‘,‘daughter‘:‘張慕雪‘}};#訪問字典中的值print(people_0[‘children‘][‘son‘]);people_1 ={};#output張源風
3.1.3 往字典中添加索引值對
people_1 ={};#添加索引值people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;print(people_1);# output {‘name‘: ‘李四‘, ‘age‘: 80}
3.1.4 修改字典中的索引值
people_1 ={};people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;print(people_1[‘age‘]);#將字典中的鍵age的值修改people_1[‘age‘] = 90;print(people_1[‘age‘]);# output 8090
3.1.5 刪除字典中的索引值對
people_1 ={};people_1[‘name‘] = ‘李四‘;people_1[‘age‘] = 80;people_1[‘addr‘] = ‘Provence‘;print(people_1);#刪除一個索引值對del people_1[‘age‘];print(people_1);#output{‘name‘: ‘李四‘, ‘age‘: 80, ‘addr‘: ‘Provence‘}{‘name‘: ‘李四‘, ‘addr‘: ‘Provence‘}
3.2 遍曆字典3.2.1 遍曆字典中的所有的索引值對
Favorite_programming_language = {    ‘喬丹‘:‘java‘,    ‘約翰遜‘:‘C‘,    ‘拉塞爾‘:‘C++‘,    ‘鄧肯‘:‘python‘,    ‘奧尼爾‘:‘C#‘,    ‘張伯倫‘: ‘JavaScript‘,    ‘科比‘: ‘php‘,    ‘加內特‘:‘Go‘,};for name,language in Favorite_programming_language.items():    print(name.title() + "‘s favorite program lnaguage is " + language.title() + ‘.‘);# output喬丹‘s favorite program lnaguage is Java.約翰遜‘s favorite program lnaguage is C.拉塞爾‘s favorite program lnaguage is C++.鄧肯‘s favorite program lnaguage is Python.奧尼爾‘s favorite program lnaguage is C#.張伯倫‘s favorite program lnaguage is Javascript.科比‘s favorite program lnaguage is Php.加內特‘s favorite program lnaguage is Go.
3.2.2 遍曆字典中的鍵
Favorite_programming_language = {    ‘喬丹‘:‘java‘,    ‘約翰遜‘:‘C‘,    ‘拉塞爾‘:‘C++‘,    ‘鄧肯‘:‘python‘,    ‘奧尼爾‘:‘C#‘,    ‘張伯倫‘: ‘JavaScript‘,    ‘科比‘: ‘php‘,    ‘加內特‘:‘Go‘,};names = [‘喬丹‘,‘加內特‘];for name in Favorite_programming_language.keys():    print(name.title());    if name in names :        print(‘I can see‘ + name.title() +‘ like ‘+ Favorite_programming_language[name].title());#output 喬丹I can see喬丹 like Java約翰遜拉塞爾鄧肯奧尼爾張伯倫科比加內特I can see加內特 like Go
3.2.3 遍曆字典中的值
Favorite_programming_language = {    ‘喬丹‘:‘java‘,    ‘約翰遜‘:‘C‘,    ‘拉塞爾‘:‘C++‘,    ‘鄧肯‘:‘python‘,    ‘奧尼爾‘:‘C#‘,    ‘張伯倫‘: ‘JavaScript‘,    ‘科比‘: ‘php‘,    ‘加內特‘:‘Go‘,};print(‘this is languages:‘);for language in Favorite_programming_language.values():    print(language.title());# outputthis is languages:JavaCC++PythonC#JavascriptPhpGo
Favorite_programming_language = {    ‘喬丹‘:‘java‘,    ‘約翰遜‘:‘C‘,    ‘拉塞爾‘:‘C++‘,    ‘鄧肯‘:‘python‘,    ‘奧尼爾‘:‘C#‘,    ‘張伯倫‘: ‘JavaScript‘,    ‘科比‘: ‘php‘,    ‘加內特‘:‘Go‘,};print(‘this is languages:‘);#調用sorted函數對值列表排序for language in sorted(Favorite_programming_language.values()):    print(language.title());# outputthis is languages:CC#C++GoJavascriptJavaPhpPython
3.3 字典列表嵌套3.3.1 列表中嵌套字典
#字典列表嵌套people_1 = {‘name‘:‘張三‘,‘addr‘:‘英國‘};people_2 = {‘name‘:‘李四‘,‘addr‘:‘美國‘};people_3 = {‘name‘:‘王五‘,‘addr‘:‘法國‘};peoples = [people_1,people_2,people_3];for people in peoples :    print(people);print(‘=======================‘);botanys = [];for number in range(30):    new_botany = {‘colour‘:‘green‘,‘age‘:‘1‘};    botanys.append(new_botany);for botany in botanys[:2]:    if botany[‘colour‘] == ‘green‘:        botany[‘colour‘] = ‘red‘;        botany[‘age‘] = ‘3‘;    print(botany);print(‘.....‘);for pl in botanys[0:5]:    print(pl);print(‘how much ‘ + str(len(botanys)));#output : {‘name‘: ‘張三‘, ‘addr‘: ‘英國‘}{‘name‘: ‘李四‘, ‘addr‘: ‘美國‘}{‘name‘: ‘王五‘, ‘addr‘: ‘法國‘}======================={‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘red‘, ‘age‘: ‘3‘}.....{‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘red‘, ‘age‘: ‘3‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}{‘colour‘: ‘green‘, ‘age‘: ‘1‘}how much 30
3.3.2 字典中嵌套列表
#定義一個字典&包含列表use_language = {    ‘name_a‘:[‘java‘,‘php‘],    ‘name_b‘:[‘python‘,‘C++‘],    ‘name_c‘:[‘Go‘],    ‘name_d‘:[‘.net‘],    ‘name_e‘:[‘C#‘,‘JavaScript‘],};#迴圈字典for name,languages in use_language.items():    print("\n" + name.title() + ‘ use this language:‘);    #迴圈列表    for language in languages :        print("\t"+language.title());#output : Name_A use this language:    Java    PhpName_B use this language:    Python    C++Name_C use this language:    GoName_D use this language:    .NetName_E use this language:    C#    Javascript
3.3.3 字中嵌套字典
#字典中嵌套字典person_from ={  ‘戰三‘:{‘province‘:‘hubei‘,‘city‘:‘wuhan‘,‘dis‘:1000},  ‘李思‘:{‘province‘:‘jiangsu‘,‘city‘:‘nanjing‘,‘dis‘:1500},  ‘宛舞‘:{‘province‘:‘guangzhou‘,‘city‘:‘shengzhen‘,‘dis‘:2000},};for name,use_info in person_from.items() :    print("\n username " + name);    form_info = use_info[‘province‘] + ‘_‘ + use_info[‘city‘] ;    print("\t from " +form_info);#output : username 戰三     from hubei_wuhan username 李思     from jiangsu_nanjing username 宛舞     from guangzhou_shengzhen
4.流程式控制制4.1 簡單的if語句
score = 60;if score >= 60 :    print(‘You passed the exam‘);#output :You passed the exam
4.2 if-else 語句
score = 50;if score >= 60 :    print(‘You passed the exam‘);else:    print(‘You failed in your grade‘);#output : You failed in your grade
citys = [‘北京‘,‘天津‘,‘上海‘,‘重慶‘];city = ‘深圳‘;if city in citys :    print(‘welcome‘);else:    print(‘not found‘);#output : not found
4.3 if-elif-else 語句
score = 88;if score < 60 :    print(‘You failed in your grade‘);elif score >=60 and score <= 80 :    print(‘You passed the exam‘);elif score >=80 and score <=90 :    print(‘Your grades are good‘);else:    print(‘YOU are very good‘);# output : Your grades are good
english = 90;Chinese = 80;if english >= 80 or Chinese >=80 :    print("You‘re terrific");else :    print(‘You need to work hard‘);#output:Your grades are good
colour_list = [‘red‘,‘green‘,‘blue‘,‘violet‘,‘white‘];my_colour = [‘red‘,‘black‘];for monochromatic in colour_list:    if monochromatic in my_colour:        print(‘the colour :‘+ monochromatic + ‘ is my like‘);    else:        print("\n the colour :"+monochromatic + ‘ is not‘);#output :the colour :red is my likethe colour :green is notthe colour :blue is notthe colour :violet is notthe colour :white is not
5.while 迴圈5.1簡單的while迴圈
num = 1;while num <=6:    print(num);    num +=1;#output : 123456
5.2 使用標識退出while迴圈

input()函數能讓程式暫停,等待使用者輸入一些文本,使用者輸入文本之後將其儲存在一個變數中,方便後面使用

#等待使用者輸入常值內容,並且將內容值儲存到變數name中name = input(‘please input you name : ‘);print(‘nice to meet you ‘+name);#output:please input you name : zhifnanice to meet you zhifna
flag = True;while flag :messge = input(‘please input :‘);if messge == ‘quit‘:flag = False;else:print(messge);# output :please input :oneoneplease input :twotwoplease input :quit

Process finished with exit code 0

#### 5.3 使用break 退出迴圈```pythoninfo = "\n please enter the name of city you have visited :";info += "\n(Enter ‘quit‘ when you want to ove)";while True:    city = input(info);    if city == ‘quit‘:        break;    else:        print(‘I like the city :‘+ city.title());#output :please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)北京I like the city :北京 please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)上海I like the city :上海 please enter the name of city you have visited :(Enter ‘quit‘ when you want to ove)quitProcess finished with exit code 0
5.4 使用while 處理列表和字典
Unauthenticated_user = [‘name_a‘,‘name_b‘,‘name_c‘,‘name_e‘];allow_user = [];while Unauthenticated_user :    temp_user = Unauthenticated_user.pop();    print("verifying user " + temp_user.title());    allow_user.append(temp_user);print("\nshow all allow user : ");for user_name in allow_user:    print(user_name.title());#output :verifying user Name_Everifying user Name_Cverifying user Name_Bverifying user Name_Ashow all allow user : Name_EName_CName_BName_A
user_infos = {};flag = True ;while flag :    name = input(‘please enter you name :‘);    sport = input("What‘s your favorite sport :");    user_infos[name] = sport;    repeat = input(‘Do you want to continue the question and answer (y/n): ‘);    if repeat == ‘n‘ :        flag = False ;print("\n-------ALL----");for name,sport in user_infos.items():    print(name.title() + ‘ like ‘+sport.title());#output :please enter you name :李思What‘s your favorite sport :舞蹈Do you want to continue the question and answer (y/n): yplease enter you name :王武What‘s your favorite sport :足球Do you want to continue the question and answer (y/n): n-------ALL----李思 like 舞蹈王武 like 足球

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.