目录
python介绍
1.介绍
1.1第一个程序
1.2注释
2.变量(Variables)
3.字符串(Strings)
4.数据结构(Data structures)
5.条件表达式(Condition expressions)
6.循环(Loops)
7.函数(Functions)
8.类与对象(Classes and objects)
9.模块和包(Modules and packages)
10.文件输入/输出(File input/output)
1.介绍
1.1第一个程序hello_world.py
print("Hello, world! My name is dudu")
1.2注释(comments)
# This is the comment for the comments.py file
print("Hello!") # this comment is for the second line
print("# this is not a comment")
# new comment
2.变量
常用的数字数据类型(Common used numeric data types)
Name | Notation | Declaration e.g. |
---|---|---|
Integers | int | a = 10 |
Floating | float | b = 3.14 |
Complex | complex | c = 1 + 2j |
String | str | d = 'Python' |
- 备注:
- 在Python 2.7中,int与另一个int运算将导致int结果。 但是,一个浮点运算与int会导致浮点数。
- 在Python 3.x中,int与另一个int运算将导致浮点数。
2.1定义变量
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 = 2333
print("greetings = " + str(greetings))
2.2未定义的变量
variable = 1
print(other_variable)
2.3变量类型
number = 9
print(type(number)) # print type of variable "number"
float_number = 9.0
print(type(float_number))
2.4变量类型转变
number = 9
print(type(number)) # print type of variable "number"
float_number = 9.0
print(float_number)
print(int(float_number))
2.5算术运算符(arithmetic operator)
number = 9.0 # float number
result = number / 2
remainder = number % 2
print("result = " + str(result))
print("remainder = " + str(remainder))
2.6赋值(Assignments)
number = 9.0
print("number = " + str(number))
number -= 2
print("number = " + str(number))
number += 5
print("number = " + str(number))
2.7逻辑算子/布尔操作符(boolean operator)
two = 2
three = 3
is_equal = two == three
print(is_equal)
2.8比较运算符(Comparison operator)
one = 1
two = 2
three = 3
print(one < two < three) # This chained comparison means that the (one < two) and (two < three) comparisons are performed at the same time.
is_greater = three > two
print(is_greater)
3.字符串
3.1串联(concatenation)
hello = "Hello"
world = 'World'
hello_world = hello + ' ' + world
print(hello_world) # Note: you should print "Hello World"
3.2字符串相乘(string multiplication)
hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
3.3字符串索引(string indexing)
python = "Python"
print("h " + python[3]) # Note: string indexing starts with 0
p_letter = python[0]
print(p_letter)
3.4字符串负索引(string negative indexing)
long_string = "This is a very long string!"
exclamation = long_string[-1]
print(exclamation)
3.5字符切割(string slicing)
monty_python = "Monty Python"
monty = monty_python[:5] # one or both index could be dropped. monty_python[:5] is equal to monty_python[0:5]
print(monty)
python = monty_python[6:]
print(python)
Example
str[start:end] # items start through end-1
str[start:] # items start through the rest of the array
str[:end] # items from the beginning through end-1
str[:] # a copy of the whole array
3.6 In operator
ice_cream = "ice cream"
print("cream" in ice_cream) # print boolean result directly
contains = 'ice' in ice_cream
print(contains)
3.6字符串长度
phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""
first_half = phrase[:int(len(phrase)/2)]
print(first_half)
3.7字符转义(Character escaping)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"')
3.8 Basic string methods
monty_python = "Monty Python"
print(monty_python)
print(monty_python.lower()) # print lower-cased version of the string
print(monty_python.upper())
3.9 String formatting
name = "John"
print("Hello, PyCharm! My name is %s!" % name) # Note: %s is inside the string, % is after the string
print("I'm %d years old" % 80)
4.数据结构
4.1列表介绍(Lists introduction)
squares = [1, 4, 9, 16, 25] # create new list
print(squares)
print(squares[1:4])
4.2 Lists operator
animals = ['elephant', 'lion', 'tiger', "giraffe"] # create new list
print(animals)
animals += ["monkey", 'dog'] # add two items to the list
print(animals)
animals.append("dino") # add one more item to the list using append() method
print(animals)
animals[-1] = 'dinosaur'
print(animals)
4.3 Lists items
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog'] # create new list
print(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 list
print(animals)
animals[:] = []
print(animals)
4.4元组(tuples)
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))
元组几乎与列表相同。元组和列表之间唯一显著的区别是元组不能更改:您不能从元组中添加、更改或删除元素。元组由括在括号中的逗号运算符构成,例如(a, b, c)。
4.5字典(dictionaries)
# create new dictionary.
phone_book = {"John": 123, "Jane": 234, "Jerard": 345} # "John", "Jane" and "Jerard" are keys and numbers are values
print(phone_book)
# Add new item to the dictionary
phone_book["Jill"] = 345
print(phone_book)
# Remove key-value pair from phone_book
del phone_book['John']
print(phone_book['Jane'])
4.6 Dictionary Keys()and values()phone_book = {"John": 123, "Jane": 234, "Jerard": 345} # create new dictionary
print(phone_book)
# Add new item to the dictionary
phone_book["Jill"] = 456
print(phone_book)
print(phone_book.keys())
print(phone_book.values())
4.7 In keywordgrocery_list = ["fish", "tomato", 'apples'] # create new list
print("tomato" in grocery_list) # check that grocery_list contains "tomato" item
grocery_dict = {"fish": 1, "tomato": 6, 'apples': 3} # create new dictionary
print('fish' in grocery_dict.keys())
5.条件表达式(Condition expressions)
5.1布尔运算符(Boolean operators)
name = "John"
age = 17
print(name == "John" or age == 17) # checks that either name equals to "John" OR age equals to 17
print(name == 'John' and age != 23)
5.2布尔运算符的顺序(Boolean operators order)
name = "John"
age = 17
print(name == "John" or not age > 17)
print(name == "John" or not age > 17)
print(name is "Ellis" or not (name is "John" and age == 17))
Boolean operators are not evaluated from left to right.布尔运算符不会从左到右进行计算。
There's an order of operations for boolean operators: not is evaluated first, and is evaluated next, or is evaluated last.
5.3条件语句(if statement)
name = "John"
age = 17
if 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 list
if len(tasks) == 0:
print("empty")
5.4 Else, elif part in if statement
else语句补充if语句。elif关键字是“else if”的缩写。
x = 28
if x < 0:
print('x < 0') # executes only if x < 0
elif x == 0:
print('x is zero') # if it's not true that x < 0, check if x == 0
elif x == 1:
print('x == 1') # if it's not true that x < 0 and x != 0, check if x == 1
else:
print('non of the above is true')
name = "John"
if name == 'John':
print(True)
else:
print(False)
6.循环(Loops)
6.1 For循环(For loop)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 list
for prime in primes:
print(prime)
6.2 For loop using string
hello_world = "Hello, World!"
for ch in hello_world: # print each character from hello_world
print(ch)
length = 0 # initialize length variable
for ch in hello_world:
length += 1 # add 1 to the length on each iteration
print(len(hello_world) == length)
6.3 While loopsquare = 1
while square <= 10:
print(square) # This code is executed 10 times
square += 1 # This code is executed 10 times
print("Finished") # This code is executed once
square = 0
number = 1
while square < 81:
square = number ** 2
print(square)
number += 1
6.4 中断关键字Break keyword
count = 0
while True: # this condition cannot possibly be false
print(count)
count += 1
if count >= 5:
break # exit loop if count >= 5
zoo = ["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
6.5 继续关键字Continue keywordcontinue关键字用于跳过当前执行循环的循环中的其余代码,并返回到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)
7.函数
7.1定义函数
def hello_world(): # function named my_function
print("Hello, World!")
for i in range(5):
hello_world() # call function defined above 5 times
print('I want to be a function')
print('I want to be a function')
print('I want to be a function')
def fun():
print('I want to be a function')
for i in range(3):
fun()
7.2参数与调用参数(parameters and call arguments)
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.
def square(x):
print(x ** 2)
square(4)
square(8)
square(15)
square(23)
square(42)
7.3 返回值(return value)
def sum_two_numbers(a, b):
return a + b # return result to the function caller
c = 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 result
print(fib(10))
函数可以使用关键字return返回一个值给调用者。您可以使用返回的值将其分配给一个变量,或者将其打印出来。在斐波那契数列中,前两个数是1和1,后面的数是前两个数的和。编写一个函数,该函数返回到n的斐波那契数列数的列表。
#append() 方法用于在列表末尾添加新的对象。语法:list.append ( obj )
参数:obj--添加到列表末尾的对象。返回值:该方法无返回值,但会修改原来的列表。
7.4 默认参数(Default parameter)
def multiply_by(a, b=2):
return a * b
print(multiply_by(3, 47))
print(multiply_by(3)) # call function using default value for b parameter
def hello(subject, name='dudu'):
print("Hello %s! My name is %s" % (subject, name))
hello("PyCharm", "Jane") # call 'hello' function with "PyCharm as a subject parameter and "Jane" as a name
hello("PyCharm") # call 'hello' function with "PyCharm as a subject parameter and default value for the name
8.类和对象
8.1类的定义(Definition)
对象将变量和函数组合成一个实体。对象从类中获取变量和函数。类本质上是创建对象的模板。您可以将对象看作是包含数据和函数的单个数据结构。对象的函数称为方法。
class MyClass:
variable = 4
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" function
8.2变量访问控制(variable access)
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_object
print(my_object.variable2)
print(my_object1.variable2)
my_object.foo() # call method foo() of object my_object
print(my_object.variable1)
8.3变量访问控制(variable access)
class Car:
color = ""
def description(self):
description_string = "This is a %s car." % self.color # we'll explain self parameter later in task 4
return description_string
car1 = Car()
car2 = Car()
car1.color = "blue"
car2.color = "red"
print(car1.description())
print(car2.description())
8.4 Self explanation
是时候解释前面任务中使用的self参数了。self参数是Python约定。self是传递给任何类方法的第一个参数。Python将使用self参数来引用正在创建的对象。
实现添加方法。它应该增加到当前字段的值。
class Complex:
def create(self, real_part, imag_part):
self.r = real_part
self.i = imag_part
class Calculator:
current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
8.5 Special__init__method
__init__函数用于初始化它创建的对象。__init__是“初始化”的缩写。__init__()总是至少有一个参数,self,指的是被创建的对象。函数的作用是:设置类创建的每个对象。
将参数添加到Car类,这样我们就可以用特定的颜色创建它。
class Square:
def __init__(self): # special method __init__
self.sides = 4
square = Square()
print(square.sides)
class Car:
def __init__(self, color):
self.color = color
car = Car("blue") # Note: you should not pass self parameter explicitly, only color parameter
print(car.color)
9.模块和包
9.1导入模块
Python中的模块只是Python文件。包含Python定义和语句的py扩展。当你想在一些程序中使用你的函数而不把它的定义复制到每个程序中时,模块是很方便的。模块是从其他模块导入的,使用import关键字和没有扩展名的文件名。第一次将模块加载到运行的Python脚本中,它是通过在模块中执行一次代码来初始化的。
导入模块my_module并使用hello_world函数。
"""
This module contains Calculator class
"""
class Calculator:
def __init__(self):
self.current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
""" documentation string for module my_module
This module contains hello_world function
"""
def hello_world(name):
print("Hello, World! My name is %s" % name)
import calculator
calc = calculator.Calculator() # create new instance of Calculator class defined in calculator module
calc.add(2)
print(calc.get_current())
import my_module
my_module.hello_world('dudu')
9.2内建模块(Builtin modules)
Python附带了一个标准模块库。请记住,您可以在一个点(.)之后使用Ctrl + Space来探索模块的可用方法。
使用导入的内置模块datetime打印当前日期。
import datetime
print(datetime.datetime.today())
9.2 from importOne form of the import statement imports names
from
a
module directly into the importing module's symbol table. This way you can use the imported name directly without the module_name
prefix.
import语句的一种形式是从模块直接导入模块的符号表。通过这种方式,您可以直接使用导入的名称,而无需使用module_name前缀。
从my_module导入hello_world函数。检查与上面导入方法的区别。
"""
This module contains Calculator class
"""
class Calculator:
def __init__(self):
self.current = 0
def add(self, amount):
self.current += amount
def get_current(self):
return self.current
""" documentation string for module my_module
This module contains hello_world function
"""
def hello_world(name):
print("Hello, World! My name is %s" % name)
from calculator import Calculator
calc = Calculator() # here we can use Calculator class directly without prefix calculator.
calc.add(2)
print(calc.get_current())
from my_module import hello_world
print(hello_world()) # Note: hello_world function used without prefix
上面的方法:
import calculator
calc = calculator.Calculator() # create new instance of Calculator class defined in calculator module
calc.add(2)
print(calc.get_current())
import my_module
my_module.hello_world('dudu')
10.文件输入/输出(File input/output)
10.1读取文件(Read file)
input.txt内容如下:
I am a temporary file. Maybe someday, I'll become a real file.
input1.txt内容如下:
My first line My second line My third linePython有许多内置函数,可以从计算机上的文件中读取和写入信息。打开的函数用来打开一个文件。该文件可以在读取模式中打开(使用“r”作为第二个参数)或在写模式中(使用“w”作为第二个参数)。open函数返回file对象。您需要将其存储为稍后关闭该文件。
打印“input.txt”的内容。打印“input1.txt”的第一行。然后关闭该文件。
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 argument
for line in f.readlines(): # read lines
print(line)
f.close() # It's important to close the file to free up any system resources.
f1 = open("input1.txt", "r")
print(f1.readline())
f1.close()
10.2写文件(write to file)
output.txt的内容:
This is output file.如果您使用“w”(write)作为第二个参数打开一个文件,将会创建一个新的空文件。注意,如果存在同名的另一个文件,它将被删除。如果您想向现有文件添加一些内容,您应该使用“a”(附加)修饰符。
将动物园列表中的元素添加到“output.txt”。
zoo = ['lion', "elephant", 'monkey']
if __name__ == "__main__":
f = open("output.txt", 'a')
for i in zoo:
f.write(i)
f.close()