Python基礎語法

[TOC]

1.變量基礎與簡單數據類型

1.1變量解釋

變量存儲在內存中的值。這就意味着在創建變量時會在內存中開闢一個空間

name = 'python'
number = 2017
print(name);
print(number);

output:
python
2017

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 world
Python Hello World
python hello world
PYTHON 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']
6
6
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]
1
81
165
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);

output
39.9
116.3
2
39.9
116.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 
80
90
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());
# output
this is languages:
Java
C
C++
Python
C#
Javascript
Php
Go
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());

# output
this is languages:
C
C#
C++
Go
Javascript
Java
Php
Python

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
    Php

Name_B use this language:
    Python
    C++

Name_C use this language:
    Go

Name_D use this language:
    .Net

Name_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 like
the colour :green is not
the colour :blue is not
the colour :violet is not
the colour :white is not

5.while 循環

5.1簡單的while循環

num = 1;
while num <=6:
    print(num);
    num +=1;
#output : 
1
2
3
4
5
6

5.2 使用標識退出while循環

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

#等待用戶輸入文本內容,並且將內容值存儲到變量name中
name = input('please input you name : ');
print('nice to meet you '+name);
#output:
please input you name : zhifna
nice to meet you zhifna

flag = True;
while flag :
messge = input('please input :');
if messge == 'quit':
flag = False;
else:
print(messge);
# output :
please input :one
one
please input :two
two
please input :quit

Process finished with exit code 0

#### 5.3 使用break 退出循環
```python
info = "\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)quit

Process 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_E
verifying user Name_C
verifying user Name_B
verifying user Name_A

show all allow user : 
Name_E
Name_C
Name_B
Name_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): y
please enter you name :王武
What's your favorite sport :足球
Do you want to continue the question and answer (y/n): n

-------ALL----
李思 like 舞蹈
王武 like 足球
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章