变量

  1. print("-------------输出语句-------------");
  2. message="Hello Python world";
  3. print(message);
  4. print("-------------首字母大写-------------");
  5. name="ada lovelace";
  6. print(name.title());
  7. print("-------------大小写-------------");
  8. print(name.upper());
  9. print(name.lower());
  10. print("-------------拼接字符串-------------");
  11. first_name = "ada"
  12. last_name = "lovelace"
  13. full_name = first_name + " " + last_name
  14. print(full_name);
  15. print("-------------添加空白-------------");
  16. print("\tPython");
  17. print("Languages:\nPython\nC\nJavaScript");
  18. print("-------------删除空白-------------");
  19. print("Hello ".rstrip());
  20. print("-------------运算-------------");
  21. print(2+3);
  22. print(3-2);
  23. print(2*3);
  24. print(3/2);
  25. print(3**2);
  26. print(3**3);
  27. print(10**6);
  28. print(0.1+0.1);
  29. print(0.2+0.2);
  30. print("------------注释-------------");
  31. # 测试注释
  1. -------------输出语句-------------
  2. Hello Python world
  3. -------------首字母大写-------------
  4. Ada Lovelace
  5. -------------大小写-------------
  6. ADA LOVELACE
  7. ada lovelace
  8. -------------拼接字符串-------------
  9. ada lovelace
  10. -------------添加空白-------------
  11. Python
  12. Languages:
  13. Python
  14. C
  15. JavaScript
  16. -------------删除空白-------------
  17. Hello
  18. -------------运算-------------
  19. 5
  20. 1
  21. 6
  22. 1.5
  23. 9
  24. 27
  25. 1000000
  26. 0.2
  27. 0.4
  28. ------------注释-------------
  29. 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解释器忽略

列表

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

选择结构

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

字典

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

循环结构

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

函数

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

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

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

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

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

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

  1. print("-------------类-------------");
  2. class MyClass: #定义类MyClass
  3. "这是一个类."
  4. myclass = MyClass() #实例化类MyClass
  5. print('输出类的说明:') #显示文本信息
  6. print(myclass.__doc__) #显示属性值
  7. print('显示类帮助信息:')
  8. help(myclass)
  9. print("-------------类对象-------------");
  10. class MyClass: #定义类MyClass
  11. """一个简单的类实例"""
  12. i = 12345 #设置变量i的初始值
  13. def f(self): #定义类方法f()
  14. return 'hello world' #显示文本
  15. x = MyClass() #实例化类
  16. #下面两行代码分别访问类的属性和方法
  17. print("类MyClass中的属性i为:", x.i)
  18. print("类MyClass中的方法f输出为:", x.f())
  19. print("-------------构造方法-------------");
  20. class Dog():
  21. """小狗狗"""
  22. def __init__(self, name, age):
  23. """初始化属性name和age."""
  24. self.name = name
  25. self.age = age
  26. def wang(self):
  27. """模拟狗狗汪汪叫."""
  28. print(self.name.title() + " 汪汪")
  29. def shen(self):
  30. """模拟狗狗伸舌头."""
  31. print(self.name.title() + " 伸舌头")
  32. print("-------------调用方法-------------");
  33. def diao(x,y):
  34. return (abs(x),abs(y))
  35. class Ant:
  36. def __init__(self,x=0,y=0):
  37. self.x = x
  38. self.y = y
  39. self.d_point()
  40. def yi(self,x,y):
  41. x,y = diao(x,y)
  42. self.e_point(x,y)
  43. self.d_point()
  44. def e_point(self,x,y):
  45. self.x += x
  46. self.y += y
  47. def d_point(self):
  48. print("亲,当前的位置是:(%d,%d)" % (self.x,self.y))
  49. ant_a = Ant()
  50. ant_a.yi(2,7)
  51. ant_a.yi(-5,6)
  1. -------------类-------------
  2. 输出类的说明:
  3. 这是一个类.
  4. 显示类帮助信息:
  5. Help on MyClass in module __main__ object:
  6. class MyClass(builtins.object)
  7. | 这是一个类.
  8. |
  9. | Data descriptors defined here:
  10. |
  11. | __dict__
  12. | dictionary for instance variables (if defined)
  13. |
  14. | __weakref__
  15. | list of weak references to the object (if defined)
  16. -------------类对象-------------
  17. MyClass中的属性i为: 12345
  18. MyClass中的方法f输出为: hello world
  19. -------------构造方法-------------
  20. -------------调用方法-------------
  21. 亲,当前的位置是:(0,0)
  22. 亲,当前的位置是:(2,7)
  23. 亲,当前的位置是:(7,13)
  24. 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. QUIC协议详解

    声明 本文可以自由转载但需注明原始链接.本文为本人原创,作者LightningStar,原文发表在博客园.本文主体内容参考论文[1]完成. 介绍 QUIC,发音同quick,是"Quick ...

  2. 微信小程序节流使用方法

    函数节流: 英文 throttle 有节流阀的意思.大致意思也是 节约触发的频率 那么,函数节流,真正的含义是:单位时间n秒内,第一次触发函数并执行,以后 n秒内不管触发多少次,都不执行.直到下一个单 ...

  3. ubuntu 16.04和18.04 忘记登录密码的解决办法

    1:开机按Shift键,出现如下界面.(手速要快,Shift键要按时间久一点)选择第二项 2:按回车键进入如下界面,然后选中有recovery mode的选项(第三项) 3:按e进入如下界面,并找到图 ...

  4. CentOS 5.11源修改

    CentOS 5.11源 将源中所有网址替换为 http://archive.kernel.org/centos-vault/你的版本/ 一条sed命令即可解决 sed -i 's@http://xx ...

  5. FreeBSD 利用IPFW实现限制局域网使用QQ

    QQ服务器分为三类: 1.UDP 8000端口类7个:速度最快,服务器最多.QQ上线会向这7个服务器发送UDP数据包,选择回复速度最快的一个作为连接服务器.这7个服务器名字均以sz-sz7开头,域后缀 ...

  6. 内置方法 __new__ __del__

    1.__new__ 构造方法 实例化对象是先执行__new__方法,但是类中没有__new__方法,所以先到父类object类中的new方法,开辟一个属于对象的空间,然后再执行init方法 设计模式: ...

  7. 6月7日 python 复习 collections

    collections是Python内建的一个集合模块,提供了许多有用的集合类. namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: >>> ...

  8. 用strace处理程序异常挂死情况

    1. 环境: ubuntu 系统 + strace + vim 2.编写挂死程序:(参考博客) #include <stdio.h> #include <sys/types.h> ...

  9. Linux开发板(树莓派)和服务器进行双向通信(socket)

    前言 ​ 物联网是目前嵌入开发必备的属性之一,我们常常需要把自己开发板和云端进行交互,本篇博文就记录一下. ​ 使用Socket来实现Linux开发板和服务器进行双向通信,Python中是默认集成了s ...

  10. linklist template

    #include <iostream.h> typedef int ElemType; typedef struct LNode { ElemType data; struct LNode ...