码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础语法

时间:2018-03-26 10:56:21      阅读:197      评论:0      收藏:0      [点我收藏+]

标签: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 足球

Python基础语法

标签:Python   基础语   

原文地址:http://blog.51cto.com/11845347/2091001

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!