Python简明教程
来源:互联网 发布:mac注销用户快捷键 编辑:程序博客网 时间:2024/05/17 23:53
翻译自Pycharm Edu教程introduction to Python
介绍
我们的第一个程序
依照传统,你用任何编程语言所写的第一个程序都是”Hello World!”。
把你介绍给这个世界吧。
提示:在右键菜单中选择Run <name>
可以运行脚本
print("Hello, world! My name is yin")
注释
Python中的注释是以#开头的,它会作用于一整行。
在Pycharm中你可以使用Ctrl + /
来将一行注释或取消注释
# This is the comment for the comments.py fileprint("Hello!") # this comment is for the second lineprint("# this is not a comment")# this is my first comment
变量
变量定义
变量用于存储值,以便稍后引用它。一个变量就像一个标签,你可以使用等于号=
来给这个变量赋值。
赋值语句可以是链式的,例如:a = b = 2
a = b = 2 # This is called a "chained assignment". It assigns the value 2 to variables "a" and "b".print("a = " + str(a)) # We'll explain the expression str(a) later in the course. For now it is used to convert the variable "a" to a string.print("b = " + str(b))greetings = "greetings"print("greetings = " + str(greetings))greetings = 1print("greetings = " + str(greetings))
未定义变量
变量名只能由字母,数字和下划线组成,并且不能以数字开头。
如果你使用了一个你从未定义过的变量会发生什么事?尝试打印一个未定义的变量。
variable = 1print(hello)
变量类型
在Python中,有两种主要的数字类型:整形和浮点型。他们之间最主要的不同就是浮点型数字包含一个小数点,而整形数没有。
number = 9print(type(number)) # print type of variable "number"float_number = 9.0print(type(float_number))
类型转换
Python中有一些类型转换内建函数,这些函数会返回一个转换后的对象。 int(x)
将x转换为一个整形数,float(x)
将x转换为一个浮点型数,str()
将x转换为字符串表达形式。
number = 9print(type(number)) # print type of variable "number"float_number = 9.0print(float_number)print(int(float_number))
算术操作符
就像其他编程语言,Python中也可以使用加号,减号,乘号,除号来操作数字,并且在Python还可以使用幂运算符(**)和取模运算符(%).
number = 9.0 # float numberresult = number / 2remainder = number % 2print("result = " + str(result))print("remainder = " + str(remainder))
赋值语句
增量赋值语句是指在一个语句中包含两个操作,例如+=
,-=
number = 9.0print("number = " + str(number))number -= 2print("number = " + str(number))number += 5print("number = " + str(number))
布尔操作
Boolean是一种值类型,它只有True
或False
两个值。 ==
操作符用来比较两个变量是否相等,返回一个Boolean值。
two = 2three = 3is_equal = two == threeprint(is_equal)
比较操作符
Python有许多种类的比较操作符,比如>=,<=,<,>,等。
Python中的所有比较操作符都有相同的优先级,返回值是一个Boolean
one = 1two = 2three = 3print(one < two < three) # 这个链式比较的意思是(one < two) 并且 (two < three)同时成立is_greater = three > twoprint(is_greater)
字符串
字符串的连接
用加号可以把两个字符串连接在一起
hello = "Hello"world = 'World'hello_world = hello + ' ' + worldprint(hello_world) # Note: you should print "Hello World"
字符串的乘法
Python支持逐字符乘法(但不是其他方式!)。
hello = "hello"ten_of_hellos = hello * 10print(ten_of_hellos)
字符串的索引
如果你知道一个字符在字符串中的位置,你就可以访问它。
例如,str[index]将会返回字符串str中index位置的字符。
注意字符串索引总是以0开始,索引还可能是负值,这时将会从右侧开始计数。
注意-0和0是相同的,负索引从-1开始。
python = "Python"print("h " + python[3]) # Note: string indexing starts with 0p_letter = python[0]print(p_letter)long_string = "This is a very long string!"exclamation = long_string[-1]print(exclamation)
字符串切片(slicing)
切片被用来从一个字符串中获取多个子字符串,它的语法和索引类似,只是你需要使用
两个由冒号分割的数字来指定一个子串。例如 str[ind1:ind2]
monty_python = "Monty Python"monty = monty_python[:5] # 索引可以被省略, monty_python[:5] 等价于 monty_python[0:5]print(monty)python = monty_python[6:]print(python)
in操作符
如果你想要检测一个字符串中是否含有某个特定的字符或子字符串,你可以使用关键字in
ice_cream = "ice cream"print("cream" in ice_cream) # print boolean result directlycontains = 'ice' in ice_creamprint(contains)
字符串长度
len()函数被用来计算一个字符串中包含几个字符。
phrase = """It is a really long stringtriple-quoted strings are usedto define multi-line strings"""first_half = phrase[0:int(len(phrase) / 2)]print(first_half)
转义字符
反斜杠可以用来转义单引号或双引号,例如'It\'s me'
或"She said \"Hello\""
特殊符号’\ n’用于向字符串添加换行符。
单引号可以被用在双引号之中而无需转义,反之亦然。
dont_worry = "Don't worry about apostrophes"print(dont_worry)print("\"Sweet\" is an ice-cream")print('The name of this ice-cream is "Sweet\'n\'Tasty" ')
基本的字符串方法
字符串有很多有用的方法。你可以使用lower()
方法来去掉在你字符串中的任何大写字符, upper()
方法可以将一个字符串变成大写。
想要调用一个字符串的方法,你可以在这个字符串(或者一个包含字符串的变量)的后面输入一个.
,然后在点号后面
跟上你想使用的方法。比如"John".upper()
。
在PyCharm中,你可以在点号后面按下Ctrl+Space
键来浏览所有可获得的方法。
monty_python = "Monty Python"print(monty_python)print(monty_python.lower()) # print lower-cased version of the stringprint(monty_python.upper())
字符串格式化
字符串后面的%
可以将一个字符串和几个变量组合起来。 %
会将字符串中的%s
替换为字符串后面紧跟的变量。
特殊符号%d
可以用做数字量的占位符。
name = "John"print("Hello, PyCharm! My name is %s!" % name) # Note: %s is inside the string, % is after the stringyears = 21print("I'm %d years old" % years)
数据结构
列表简介
列表是一种数据结构,可用于在单个变量名下存储不同信息集合。
列表能够被一个数组所赋值,这个数组要放在方括号之间,中间的值用逗号分割。
例如lst = [item1, item2]
列表也可以包含不同类型的数据,但通常情况下它们是同类型的。
列表可以被索引和切片,就像字符串一样。
squares = [1, 4, 9, 16, 25] # create new listprint(squares)print(squares[1:4])
列表操作
你可以通过使用append()
方法向一个列表的末端添加一个新的项。
与字符串不同,列表是可变类型,比如说你可以使用lst[index] = new_item
来改变它的内容
animals = ['elephant', 'lion', 'tiger', "giraffe"] # create new listprint(animals)animals += ["monkey", 'dog'] # add two items to the listprint(animals)animals.append("dino") # add one more item to the list using append() methodprint(animals)animals[-1] = "dinosaur"print(animals)
列表项
给列表的切片赋值也是可以的,我们甚至可以通过这种方法来改变列表的大小或清空它
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog'] # create new listprint(animals)animals[1:3] = ['cat'] # replace 2 items -- 'lion' and 'tiger' with one item -- 'cat'print(animals)animals[1:3] = [] # remove 2 items -- 'cat' and 'giraffe' from the listprint(animals)animals[:] = []print(animals
元组
元组和列表非常相似,他们之间唯一的明显区别就是元组是无法被改变的:你无法对元祖
进行添加,修改和删除元素的操作。
元组能够被一个用括号括起来的数组所构建。例如:(a,b,c)
单个的元组必须有一个逗号,否则Python解析器无法分辨(a)
是一个元素a还是一个元组。
alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')print(len(alphabet))
字典
字典与列表也很相似,只是你需要通过键值来访问它的值而非通过索引。
键值可以是任意字符串或一个数字。字典是由花括号括起来的,
例如dec = {'key1':"value1",'key2':"value2"}
# create new dictionary.phone_book = {"John": 123, "Jane": 234, "Jerard": 345} # "John", "Jane" and "Jerard" are keys and numbers are valuesprint(phone_book)# Add new item to the dictionaryphone_book["Jill"] = 345print(phone_book)# Remove key-value pair from phone_bookdel phone_book['John']print(phone_book['Jane'])
关键字in
关键字in可以用来检测一个列表、元组或者字典中是否包含指定的项。
用法与string中in的用法相同
grocery_list = ["fish", "tomato", 'apples'] # create new listprint("tomato" in grocery_list) # check that grocery_list contains "tomato" itemgrocery_dict = {"fish": 1, "tomato": 6, 'apples': 3} # create new dictionaryprint('fish' in grocery_dict)test_tuple = ("fish", "hello")print('fish' in test_tuple)
条件表达式
布尔操作符
布尔运算符比较语句并以布尔值返回结果。 当两边的表达式为True时,布尔运算符“and”返回True。 布尔运算符“or”在两边的至少一个表达式为True时返回True。 布尔运算符’not’反转其前面的布尔表达式。
name = "John"age = 17print(name == "John" or age == 17) # checks that either name equals to "John" OR age equals to 17print(name == "John" and age != 23)
布尔操作符求值顺序
布尔操作符并不是从左到右求值,布尔操作符的求值顺序如下:
not第一个求值,下一个是and,or最后求值。
name = "John"age = 17print(name == "John" or not age > 17)print(name == "John" or not age > 17)print("name" is "Ellis" or not ("name" == "John" and age == 17))
if语句
if关键字用于形成一个条件语句,它在检查其表达式是否为True后执行一些指定的代码。
Python使用缩进来定义代码块
else语句补充了if语句,elif是”else if”的缩写。
name = "John"age = 17if name == "John" or age == 17: # check that name is "John" or age is 17. If so print next 2 lines. print("name is John") print("John is 17 years old")tasks = ['task1', 'task2'] # create new listif len(tasks): print("empty") x = 28if x < 0: print('x < 0') # executes only if x < 0elif x == 0: print('x is zero') # if it's not true that x < 0, check if x == 0elif x == 1: print('x == 1') # if it's not true that x < 0 and x != 0, check if x == 1else: print('non of the above is true')name = "John"if name == 'John': print(True)else: print(False)
循环
for循环
for循环被用来遍历一个给定的序列。
每次循环,在for循环中定义的变量都会被赋予列表中的下一个值。
for i in range(5): # for each number i in range 0-4. range(5) function returns list [0, 1, 2, 3, 4] print(i) # this line is executed 5 times. First time i equals 0, then 1, ...primes = [2, 3, 5, 7] # create new listfor prime in primes: print(prime)
while循环
while循环和if语句很像:当某些条件为真时,它就会执行一些代码。
它们两个之间最主要的区别是只要条件为真,while循环会不停的执行缩进的代码。
square = 1while square <= 10: print(square) # This code is executed 10 times square += 1 # This code is executed 10 timesprint("Finished") # This code is executed oncesquare = 0number = 1while number < 10: square = number ** 2 print(square) number += 1
关键字break
一个死循环是永远无法退出的,如果一个循环的条件永远为真,那它就是个死循环。
关键字break被用来退出这样的循环
count = 0while True: # this condition cannot possibly be false print(count) count += 1 if count >= 5: break # exit loop if count >= 5zoo = ["lion", 'tiger', 'elephant']while True: # this condition cannot possibly be false animal = zoo.pop() # extract one element from the list end print(animal) if animal == 'elephant': break # exit loop
关键字continue
关键字continue被用于跳过当前正在被执行的循环中的余下的代码,并且返回到for或while声明
for i in range(5): if i == 3: continue # skip the rest of the code inside loop for current i value print(i)for x in range(10): if x % 2 == 0: continue # skip print(x) for this loop print(x)
函数
函数的定义
函数可以将你的代码划分为有用的块,并且使得它更易读,更容易重用。
函数使用关键字def定义,后面跟着函数名
def hello_world(): # function named my_function print("Hello, World!")for i in range(5): hello_world() # call function defined above 5 times
函数的参数与调用
函数的参数被定义在括号中,跟随在函数后面,
参数充当传递参数的变量名。
def foo(x): # x is a function parameter print("x = " + str(x))foo(5) # pass 5 to foo(). Here 5 is an argument passed to function foo.
返回值
函数可以通过关键字return来向调用者返回一个值,你可以用返回值来给一个变量赋值或者直接打印它。
def sum_two_numbers(a, b): return a + b # return result to the function callerc = sum_two_numbers(3, 12) # assign result of function execution to variable 'c'def fib(n): """This is documentation string for function. It'll be available by fib.__doc__() Return a list containing the Fibonacci series up to n.""" result = [] a = 1 b = 1 while a < n: result.append(a) tmp_var = b b = a + b a = tmp_var return resultprint(fib(10))
默认参数
有时给一个或更多的函数参数指定一个默认值可能是很有用的。
这样你调用函数的时候就可以少写几个参数了
def multiply_by(a, b=2): return a * bprint(multiply_by(3, 47))print(multiply_by(3)) # call function using default value for b parameter
类和对象
类的定义
对象是由变量和函数组成的一个单一实体,对象从类中获得他的函数和变量。
类是创建对象所需的必要模板,对象的函数叫做方法。
class MyClass: variable = 0 def foo(self): # we'll explain self parameter later in task 4 print("Hello from function foo")my_object = MyClass() # variable "my_object" holds an object of the class "MyClass" that contains the variable and the "foo" functionmy_object.foo()
访问变量
您可以更改此类中为该类的不同实例(对象)定义的变量的值。
class MyClass: variable1 = 1 variable2 = 2 def foo(self): # we'll explain self parameter later in task 4 print("Hello from function foo")my_object = MyClass()my_object1 = MyClass()my_object.variable2 = 3 # change value stored in variable2 in my_objectprint(my_object.variable2)print(my_object1.variable2)my_object.foo() # call method foo() of object my_objectprint(my_object.variable1)
self的说明
是时候解释一下前面使用的self参数了。self是Python中的一个习惯性的写法,你也可以写成其他,
self是传递给任何类方法的第一个参数,Python将使用self参数来引用正在创建的对象。
class Calculator: current = 0 def add(self, amount): self.current += amount def get_current(self): return self.current
特殊的init方法
init方法被用来初始化一个对象。init是initialize的缩写。
init方法通常会接收最少一个参数,self。
init方法设置有这个类所创建的每一个对象。
class Car: def __init__(self,color): self.color = colorcar = Car("blue") # Note: you should not pass self parameter explicitly, only color parameterprint(car.color)
模块和包
导入模块
Python中的模块就是一个简单的Python文件,它以.py为扩展名,包含了Python的声明和定义。
当你希望在多个程序中使用你的函数而不想在每个文件中复制一大段代码时,模块就可以为你带来方便。
我们可以使用import关键字来导入模块,语法为import + 模块名,模块名就是文件名去掉后缀。
模块首次加载到正在运行的Python脚本中时,会通过执行模块中的代码进行初始化。
import calculatorcalc = calculator.Calculator() # create new instance of Calculator class defined in calculator modulecalc.add(2)print(calc.get_current())
内建模块
Python自带了一个标准模块库。
记住你可以在一个.之后按下Ctrl+Space来浏览一个模块中可用的方法。
import datetimeprint(datetime.datetime.now())
from import
一个from import声明会将模块中的名称直接导入到导入模块的符号表中。
这样你就可以直接使用导入的名称而无需模块名前缀。
from calculator import Calculatorcalc = Calculator() # here we can use Calculator class directly without prefix calculator.calc.add(2)print(calc.get_current())
文件的输入输出
读取文件
Python有多个内建函数来对你计算机中的文件进行读写操作。
open函数可以打开一个文件,文件可以以读模式(使用”r”作为第二个参数)或写模式(使用”w”作为第二个参数)打开
open函数返回一个文件对象,你需要存储它以稍后关闭文件。
f = open("input.txt", "r") # here we open file "input.txt". Second argument used to identify that we want to read file # Note: if you want to write to the file use "w" as second argumentfor line in f.readlines(): # read lines print(line)f.close() # 关闭文件以释放系统资源是很重要的
写入文件
你可以通过使用”w”作为open函数的第二个参数来创建一个新的空文件。
注意如果已经存在一个同名文件,它将会被删除,如果你想向一个已经存在的文件中写入
一些内容,你应当使用”a”(append)而非”w”
zoo = ['lion', "elephant", 'monkey']if __name__ == "__main__": f = open("output.txt", "a") for i in zoo: f.write(i) f.close()
- 简明 Python 教程
- 简明 Python 教程
- 简明Python 教程 --模块
- 简明Python教程
- 简明 Python 教程
- 《简明Python教程》读书笔记
- [ 转]简明 Python 教程
- 《简明Python教程》笔记
- python简明教程
- 简明 Python 教程
- 再读简明Python教程
- 《简明Python教程》读书笔记
- 简明python教程网址
- python简明教程
- 学习《简明Python教程》
- 简明Python教程
- 简明python教程
- 简明 Python 教程
- win10 +keras +gpu
- Multiple dex files define问题另一种解法
- How to make a automated testing for web applications
- tomcat系列之 什么是tomcat
- Java集合深入学习:ArrayList的实现原理
- Python简明教程
- HDOJ2022
- 选项卡的完整代码~~还有一些自己copy
- not1,not2,bind1st和bind2nd详解
- HDOJ2024
- Studio用布局编辑器设计UI界面
- 两个整数的交换方法
- <ACM>求多边形重心和面积问题
- bzoj4976 宝石镶嵌