变量

print("-------------输出语句-------------");
message="Hello Python world";
print(message);
print("-------------首字母大写-------------");
name="ada lovelace";
print(name.title());
print("-------------大小写-------------");
print(name.upper());
print(name.lower());
print("-------------拼接字符串-------------");
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name);
print("-------------添加空白-------------");
print("\tPython");
print("Languages:\nPython\nC\nJavaScript");
print("-------------删除空白-------------");
print("Hello ".rstrip());
print("-------------运算-------------");
print(2+3);
print(3-2);
print(2*3);
print(3/2);
print(3**2);
print(3**3);
print(10**6);
print(0.1+0.1);
print(0.2+0.2);
print("------------注释-------------");
# 测试注释
-------------输出语句-------------
Hello Python world
-------------首字母大写-------------
Ada Lovelace
-------------大小写-------------
ADA LOVELACE
ada lovelace
-------------拼接字符串-------------
ada lovelace
-------------添加空白-------------
Python
Languages:
Python
C
JavaScript
-------------删除空白-------------
Hello
-------------运算-------------
5
1
6
1.5
9
27
1000000
0.2
0.4
------------注释------------- Process finished with exit code 0
  1. 运行文件hello_world.py时,末尾的.py指出这是一个Python程序,因此编辑器将使用Python解释器来运行它
  2. 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
  3. 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
  4. 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,
  5. 变量名应既简短又具有描述性。
  6. 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0
  7. 在Python中,注释用井号( # )标识。井号后面的内容都会被Python解释器忽略

列表

print("-------------列表-------------");
bicycles = ['trek', 'cannondale', 'redline', 'specialized'];
print(bicycles);
print("-------------访问列表元素-------------");
print(bicycles[0]);
print("-------------修改列表元素-------------");
bicycles[0]='ducati';
print(bicycles);
print("-------------添加列表元素-------------");
bicycles.append('test');
print(bicycles);
print("-------------插入列表元素-------------");
bicycles.insert(0,'test2');
print(bicycles);
print("-------------删除列表元素-------------");
del bicycles[0];
print(bicycles);
print(bicycles.pop());
print(bicycles);
print("-------------排序列表元素-------------");
bicycles.sort();
print(bicycles);
print("-------------倒叙打印列表元素-------------");
print(bicycles.reverse());
print("-------------列表长度-------------");
print(len(bicycles));
print("-------------数值列表------------");
numbers=list(range(1,6));
print(numbers);
-------------列表-------------
['trek', 'cannondale', 'redline', 'specialized']
-------------访问列表元素-------------
trek
-------------修改列表元素-------------
['ducati', 'cannondale', 'redline', 'specialized']
-------------添加列表元素-------------
['ducati', 'cannondale', 'redline', 'specialized', 'test']
-------------插入列表元素-------------
['test2', 'ducati', 'cannondale', 'redline', 'specialized', 'test']
-------------删除列表元素-------------
['ducati', 'cannondale', 'redline', 'specialized', 'test']
test
['ducati', 'cannondale', 'redline', 'specialized'] Process finished with exit code 0
  1. 列表由一系列按特定顺序排列的元素组成
  2. 列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可
  3. Python方法 sort() 让你能够较为轻松地对列表进行排序。
  4. 要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数 sorted() 。函数sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
  5. 要反转列表元素的排列顺序,可使用方法 reverse()
  6. 使用函数 len() 可快速获悉列表的长度
  7. Python根据缩进来判断代码行与前一个代码行的关系。

选择结构

print("-------------检查是否相等-------------");
car='bmw';
print(car=='bmw');
print(car=='audi');
print(car=='BMW');
print(car.upper()=='BMW');
age=18;
print(age==18);
print(age>=18);
print(age<=18);
print(age>18);
print(age<18); age_0 = 22;
age_1 = 18;
print(age_0 >= 21 and age_1 >= 21);
print(age_0 >= 21 or age_1 >= 21);
print("-------------if语句-------------");
age = 19
if age >= 18:
print("You are old enough to vote!"); age=17
if age>=18:
print("You are old enough to vote!");
else:
print("Sorry you are too young"); age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.") age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
-------------检查是否相等-------------
True
False
False
True
True
True
True
False
False
False
True
-------------if语句-------------
You are old enough to vote!
Sorry you are too young
Your admission cost is $5.
Your admission cost is $5. Process finished with exit code 0
  1. 在Python中检查是否相等时区分大小写
  2. 要判断两个值是否不等,可结合使用惊叹号和等号( != )
  3. 要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一
  4. 关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。
  5. 在 if 语句中,缩进的作用与 for 循环中相同。如果测试通过了,将执行 if 语句后面所有缩进的代码行,否则将忽略它们。
  6. 经常需要检查超过两个的情形,为此可使用Python提供的 if-elif-else 结构

字典

print("-------------一个简单的字典-------------");
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
print("-------------访问字典中的值------------");
alien_0={'color':'green'};
print(alien_0['color']);
print("-------------先创建一个空字典------------");
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
print("-------------修改字典中的值------------");
alien_0={'color':'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
print("-------------删除键值对------------");
alien_0 = {'color': 'green', 'points': 5}
print(alien_0);
del alien_0['points']
print(alien_0);
print("-------------遍历字典------------");
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user_0.items():
print("\nKey:"+key)
print("Value:"+value)
-------------一个简单的字典-------------
green
5
-------------访问字典中的值------------
green
-------------先创建一个空字典------------
{'color': 'green', 'points': 5}
-------------修改字典中的值------------
The alien is green.
The alien is now yellow.
-------------删除键值对------------
{'color': 'green', 'points': 5}
{'color': 'green'}
-------------遍历字典------------ Key:username
Value:efermi Key:first
Value:enrico Key:last
Value:fermi Process finished with exit code 0
  1. 字典是一系列键 — 值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
  2. 要获取与键相关联的值,可依次指定字典名和放在方括号内的键
  3. 字典是一种动态结构,可随时在其中添加键 — 值对。要添加键 — 值对,可依次指定字典名、用方括号括起的键和相关联的值。
  4. 对于字典中不再需要的信息,可使用 del 语句将相应的键 — 值对彻底删除。
  5. 字典存储的是一个对象(游戏中的一个外星人)的多种信息,但你也可以使用字典来存储众多对象的同一种信息。

循环结构

print("-------------函数input()的工作原理-------------");
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
print("-------------编写清晰的程序-------------");
name=input("Please enter your name:");
print("Hello,"+name+"!");
print("-------------求模运算符-------------");
print(4%3);
print("-------------while循环-------------");
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
print("-------------让用户选择何时退出-------------");
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
print("-------------break语句-------------");
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
-------------函数input()的工作原理-------------
Tell me something, and I will repeat it back to you: Hello World
Hello World
-------------编写清晰的程序-------------
Please enter your name:Alice
Hello,Alice!
-------------求模运算符-------------
1
-------------while循环-------------
1
2
3
4
5
-------------让用户选择何时退出------------- Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello World
Hello World Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
-------------break语句------------- Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) ShangHai
I'd love to go to Shanghai! Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit Process finished with exit code 0
  1. 函数 input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
  2. 函数 input() 接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
  3. 每当你使用函数 input() 时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息——指出用户该输入任何信息的提示都行
  4. 使用函数 input() 时,Python将用户输入解读为字符串

函数

print("-------------函数-------------");
def greet_user():
print("Hello World")
print("-------------区分线-------------");
greet_user();
print("-------------调用函数-------------");
def tpl_sum( T ): #定义函数tpl_sum()
result = 0 #定义result的初始值为0
for i in T: #遍历T中的每一个元素i
result += i #计算各个元素i的和
return result #函数tpl_sum()最终返回计算的和
print("(1,2,3,4)元组中元素的和为:",tpl_sum((1,2, 3,4))) #使用函数tpl_sum()计算元组内元素的和
print("[3,4,5,6]列表中元素的和为:",tpl_sum([3,4, 5,6])) #使用函数tpl_sum()计算列表内元素的和
print("[2.7,2,5.8]列表中元素的和为:",tpl_sum([2.7, 2,5.8])) #使用函数tpl_sum()计算列表内元素的和
print("[1,2,2.4]列表中元素的和为:",tpl_sum([1,2,2.4]))
#使用函数tpl_sum()计算列表内元素的和
-------------函数-------------
-------------区分线-------------
Hello World
-------------调用函数-------------
(1,2,3,4)元组中元素的和为: 10
[3,4,5,6]列表中元素的和为: 18
[2.7,2,5.8]列表中元素的和为: 10.5
[1,2,2.4]列表中元素的和为: 5.4 Process finished with exit code 0
  1. 这个示例演示了最简单的函数结构
  2. 调用函数就是使用函数,在 Python 程序中,当定义一个函数后,就相当于给了函数一个名称,指定了函数里包含的参数和代码块结构。完成这个函数的基本结构定义工作后,就可以通过调用的方式来执行这个函数,也就是使用这个函数。
  3. 在 Python 程序中,使用关键字 def 可以定义一个函数,定义函数的语法格式如下所示。
def<函数名>(参数列表):
<函数语句>
return<返回值>

在上述格式中,参数列表和返回值不是必需的,return 后也可以不跟返回值,甚至连 return 也没有。如果 return 后没有返回值,并且没有 return 语句,这样的函数都会返回 None 值。有些函数可能既不需要传递参数,也没有返回值。

注意:当函数没有参数时,包含参数的圆括号也必须写上,圆括号后也必须有“:”。

在 Python 程序中,完整的函数是由函数名、参数以及函数实现语句(函数体)组成的。在函数声明中,也要使用缩进以表示语句属于函数体。如果函数有返回值,那么需要在函数中使用 return 语句返回计算结果。

根据前面的学习,可以总结出定义 Python 函数的语法规则,具体说明如下所示。

  • 函数代码块以 def 关键字开头,后接函数标识符名称和圆括号()。
  • 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串——用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的 return 相当于返回 None。

print("-------------类-------------");
class MyClass: #定义类MyClass
"这是一个类."
myclass = MyClass() #实例化类MyClass
print('输出类的说明:') #显示文本信息
print(myclass.__doc__) #显示属性值
print('显示类帮助信息:')
help(myclass)
print("-------------类对象-------------");
class MyClass: #定义类MyClass
"""一个简单的类实例"""
i = 12345 #设置变量i的初始值
def f(self): #定义类方法f()
return 'hello world' #显示文本
x = MyClass() #实例化类
#下面两行代码分别访问类的属性和方法
print("类MyClass中的属性i为:", x.i)
print("类MyClass中的方法f输出为:", x.f())
print("-------------构造方法-------------");
class Dog():
"""小狗狗"""
def __init__(self, name, age):
"""初始化属性name和age."""
self.name = name
self.age = age
def wang(self):
"""模拟狗狗汪汪叫."""
print(self.name.title() + " 汪汪")
def shen(self):
"""模拟狗狗伸舌头."""
print(self.name.title() + " 伸舌头")
print("-------------调用方法-------------");
def diao(x,y):
return (abs(x),abs(y))
class Ant:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
self.d_point()
def yi(self,x,y):
x,y = diao(x,y)
self.e_point(x,y)
self.d_point() def e_point(self,x,y):
self.x += x
self.y += y
def d_point(self):
print("亲,当前的位置是:(%d,%d)" % (self.x,self.y))
ant_a = Ant()
ant_a.yi(2,7)
ant_a.yi(-5,6)
-------------类-------------
输出类的说明:
这是一个类.
显示类帮助信息:
Help on MyClass in module __main__ object: class MyClass(builtins.object)
| 这是一个类.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined) -------------类对象-------------
类MyClass中的属性i为: 12345
类MyClass中的方法f输出为: hello world
-------------构造方法-------------
-------------调用方法-------------
亲,当前的位置是:(0,0)
亲,当前的位置是:(2,7)
亲,当前的位置是:(7,13) Process finished with exit code 0
  1. 把具有相同属性和方法的对象归为一个类
  2. 在 Python 程序中,类只有实例化后才能够使用。类的实例化与函数调用类似,只要使用类名加小括号的形式就可以实例化一个类。
  3. 方法调用就是调用创建的方法,在 Python 程序中,类中的方法既可以调用本类中的方法,也可以调用全局函数来实现相关功能。

【Python】Python基础知识【第一版】的更多相关文章

  1. Python数据挖掘——基础知识

    Python数据挖掘——基础知识 数据挖掘又称从数据中 挖掘知识.知识提取.数据/模式分析 即为:从数据中发现知识的过程 1.数据清理 (消除噪声,删除不一致数据) 2.数据集成 (多种数据源 组合在 ...

  2. Python 面向对象基础知识

    面向对象基础知识 1.什么是面向对象编程? - 以前使用函数 - 类 + 对象 2.什么是类什么是对象,又有什么关系? class 类: def 函数1(): pass def 函数2(): pass ...

  3. python 爬虫基础知识一

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动的抓取万维网信息的程序或者脚本. 网络爬虫必备知识点 1. Python基础知识2. P ...

  4. Python:基础知识

    python是一种解释型.面向对象的.带有动态语义的高级程序语言. 一.下载安装 官网下载地址:https://www.python.org/downloads 下载后执行安装文件,按照默认安装顺序安 ...

  5. Python学习-基础知识-2

    目录 Python基础知识2 一.二进制 二.文字编码-基础 为什么要有文字编码? 有哪些编码格式? 如何解决不同国家不兼容的编码格式? unicode编码格式的缺点 如何既能全球通用还可以规避uni ...

  6. python开发--基础知识-(持续更新)

    python基础 --基础: 1, 第一句python - 用cmd 调用--python (路径)+(文件名)) 扩展名是任意的 - 导入模块是,如果不是.py文件,可能导入不成功 - python ...

  7. 第2章 Python编程基础知识 第2.1节 简单的Python数据类型、变量赋值及输入输出

    第三节 简单的Python数据类型.变量赋值及输入输出 Python是一门解释性语言,它的执行依赖于Python提供的执行环境,前面一章介绍了Python环境安装.WINDOWS系列Python编辑和 ...

  8. Python:基础知识(二)

    常用模块 urllib2 :用于发送网络请求,获取数据 (Pyhton2中的urllib2工具包,在Python3中分拆成了urllib.request和urllib.error两个包.) json: ...

  9. 01认识Python和基础知识

     1.了解Python Python的发展历史,作者Guido, 荷兰人 Python的优缺点 Python在网站的开发,如YouTube,科学计算,数据分析,在游戏后台开发等方面广泛使用  2.编写 ...

  10. Python入门 ---基础知识

    Python入门不知道这些你还是承早放弃吧!真的 Python 简介 Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 的设计具有很强的可读性,相比其他语言 ...

随机推荐

  1. 云计算与云存储:使用云服务器搭建一个情侣纪念Web服务器

    做完了实验一,做完感觉这门还是蛮好玩的,而且第一实验就很有趣,搭建了一个可以在公网访问的纪念网站给女朋友秀了一下.写好实验报告后简单搬运,应该能给感兴趣的朋友带来帮助. 创建阿里云主机 进入阿里云官方 ...

  2. 微服务入门二:SpringCloud(版本Hoxton SR6)

    一.什么是SpringCloud 1.官方定义 1)官方定义:springcloud为开发人员提供了在分布式系统中快速构建一些通用模式的工具(例如配置管理.服务发现.断路器.智能路由.微代理.控制总线 ...

  3. CoLAKE: 如何实现非结构性语言和结构性知识表征的同步训练

    原创作者 | 疯狂的Max 论文CoLAKE: Contextualized Language and Knowledge Embedding 解读 01 背景与动机 随着预训练模型在NLP领域各大任 ...

  4. Phoenix使用

    目录 Phoenix连接 Phoenix常用命令 表映射 视图映射 表映射 Phoenix二级索引 开启索引支持 全局索引 创建索引后 创建多条件索引后 本地索引 覆盖索引 总结 Phoenix JD ...

  5. pygame写俄罗斯方块

    代码搬运修改自python编写俄罗斯方块 更新时间:2020年03月13日 09:39:17 作者:勤勉之 from tkinter import * from random import * imp ...

  6. 【行业Tip】三电是什么

    电动汽车的"三电"是指:电池.电机.电控.

  7. 七牛云cdn加速

    https://developer.qiniu.com/fusion/1228/fusion-quick-start https://blog.csdn.net/qq_27292113/article ...

  8. PAM学习小结

    PAM 目录 PAM 功能: 回文树 Fail指针 Trans指针 构建PAM 应用 P5496[模板]回文自动机(PAM) P4287[SHOI2011]双倍回文 P4555[国家集训队]最长双回文 ...

  9. 9.Flink实时项目之订单宽表

    1.需求分析 订单是统计分析的重要的对象,围绕订单有很多的维度统计需求,比如用户.地区.商品.品类.品牌等等.为了之后统计计算更加方便,减少大表之间的关联,所以在实时计算过程中将围绕订单的相关数据整合 ...

  10. Linux下swap(交换分区)的增删改

    swap介绍 Linux 的交换分区(swap),或者叫内存置换空间(swap space),是磁盘上的一块区域,可以是一个分区,也可以是一个文件,或者是他们的组合.交换分区的作用是,当系统物理内存吃 ...