[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(" " + name.title() + ' use this language:');

#循环列表

for language in languages :

print(" "+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(" username " + name);

form_info = use_info['province'] + '_' + use_info['city'] ;

print(" 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(" 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 = " please enter the name of city you have visited :";

info += " (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(" show 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(" -------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基础语法相关推荐

  1. python基础常用语句-Python基本语句

    在学习W3Cschool python高级教程之前,大家接触过许多python语句,在本文中我们将Python一些基本的常用语句做了汇总,并简单介绍下这些python常用语句的用途和标准格式,放在一起 ...

  2. python基础常用语句-python爬虫之python一条语句分析几个常用函数和概念

    https://www.xin3721.com/eschool/pythonxin3721/ 前言 过年也没完全闲着,每天用一点点时间学点东西,本文为大家介绍几个python操作的细节,包含all.a ...

  3. python基础常用语句-Python基础6—常用语句

    一.条件分支语句 python中一般不用{},语句块一般用:,然后后面语句持续保持一样的缩进即可({}用来定义字典) 1.if ①语法 :if 条件表达式: block ②例子 1 money =20 ...

  4. python基础常用语句-Python语言的一些基本常用语句

    (1).赋值:创建变量引用值 a,b,c="aa","bb","cc" (2).调用:执行函数 log.write("spam,n ...

  5. SQL常用语句(基础篇)

    SQL常用语句(基础篇) 说明:创建数据库 CREATE DATABASE database-name 说明:删除数据库 drop database dbname 说明:备份sql server -创 ...

  6. python while循环语句-Python While 循环语句

    Python While 循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件(cond ...

  7. python字典常用操作方法,python字典的常用操作方法

    Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串.数字.元组等其他容器模型.本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建.访问.删除.其它操作等,需 ...

  8. python基础常用语句-Python-基础-常用术语对照表

    2to3 一个将 Python 2.x 代码转换为 Python 3.x 代码的工具,能够处理大部分通过解析源码并遍历解析树可检测到的不兼容问题. 2to3 包含在标准库中,模块名为 lib2to3: ...

  9. Python for 循环语句-Python 基础教程

    Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串. 语法: for循环的语法格式如下: for iterating_var in sequence:   statements( ...

最新文章

  1. Python TypeError: ‘int‘ object is not iterable
  2. Mysql高级调优篇——第二章:Explain执行计划深度剖析
  3. android Unable to add window -- token null is n...
  4. 第十七届全国大学智能车竞赛赛区划分
  5. python运行错误-Python在运行中发生错误怎么正确处理方法,案例详解!
  6. [YTU]_2439( C++习题 复数类--重载运算符+)
  7. 各种神经网络优化算法:从梯度下降到Adam方法
  8. 电气:6机30节点经济调度(考虑负荷平衡和线路容量,不考虑斜坡)代码实现
  9. Team Foundation Server安装指南
  10. 某IDC科技风登录页面模板
  11. OpenCV计算机视觉实战(Python版)_003阈值与平滑处理
  12. 提高代码的运行效率 (3)
  13. 打造“5G+IoT”生态,共创产业繁荣沃土
  14. 微服务实战之Prometheus使用分享
  15. BZOJ_1096_[ZJOI2007]_仓库建设_(斜率优化动态规划+单调队列+特殊的前缀和技巧)
  16. Google登录提示错误码12501
  17. 《白帽子讲web安全》读书笔记_2021-07-16
  18. Win10的Linux子系统Ubuntu安装图形界面
  19. 到底什么是IaaS、PaaS、SaaS?
  20. unity helios_用于Eclipse Helios的JBoss工具!

热门文章

  1. centos7 harbor 单机搭建
  2. 第三十九篇 Python异常处理
  3. Java 递归解决 quot;仅仅能两数相乘的计算器计算x^yquot; 问题
  4. FreeSwitch Sip【转】
  5. JavaScript一步一步:JavaScript 对象和HTML DOM 对象
  6. Java初学者如何迈出AOP第一步--使用Java 动态代理实现AOP
  7. python返回序列中的最小元素_python实现获取序列中最小的几个元素
  8. vscode使用教程python-VsCode使用教程
  9. python语言入门n-Python基础语法学习笔记
  10. pythonweb开发-如何用Python做Web开发?——Django环境配置