分支结构

1.if-else

1
2
3
4
5
6
7
8
9
10
11
12
a = 200
b = 66
print("A") if a > b else print("=") if a == b else print("B")

x = 1
y = 2
if x == y:
print("a = b")
elif x > y:
print("a > b")
else:
pass

2.while

1
2
3
4
5
6
7
8
x = 4
while x > 0:
print(x)
x -= 1
if x == 2:
break
elif x == 1:
continue

3.for

1
2
3
4
5
for x in "bananas":
print(x)

for x in range(3,50,6):
print(x)

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#初始化赋值
def add(x = 0 , y = 0):
print(x + y)

add(x,y)

#传参时赋值
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")

#未知参数
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Phoebe", "Jennifer", "Rory")

#lambda 匿名函数
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3) #返回值是一个函数
print(mytripler(11))

数组

类 and 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):#self也可以是其他名字,总之,代表一个指向自己的参数
print("Hello my name is " + self.name)

p1 = Person("Bill", 63)
p1.myfunc()

del p1
del Person

继承

1
2
3
4
5
6
7
8
9
#create
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

#super()函数自动调用父类的方法
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#有迭代方法的对象使用了该方法,创建了一个迭代器的对象
mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))

mystr = "banana"
for x in mystr:
print(x)
#实际上也是创建了一个迭代器

#给类写迭代器方法
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration #终止迭代

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import func as my_func
my_func.add(1,2)
#假设func.py中含有add函数

#导入
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "Bill",
"age": 63,
"country": "USA"
}
#then
from mymodule import person1
print (person1["age"])#此时就只是person1了,不用mymodule.person1

调试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
else:
print("fine")
finally:
f.close()

#引发异常
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

input输入

format

1
2
3
4
5
6
7
8
quantity = 3
itemno = 567
price = 52
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." #添加索引 格式化输入
print(myorder.format(quantity, itemno, price))

myorder = "I have a {carname}, it is a {model}."#如果在占位符中添加名称索引,名称必须在format中被初始化
print(myorder.format(carname = "Porsche", model = "911"))