算数运算
2 + 2
4
50 - 5 * 6
20
8 / 5 # 浮点数除法
1.6
8 // 5 # 整数除法
1
字符串
'"I\'m ZRen," he said.'
'"I\'m ZRen," he said.'
print('"I\'m ZRen," he said.')
"I'm ZRen," he said.
s = 'First word.\nSecond word.'
s
'First word.\nSecond word.'
print(s)
First word. Second word.
'School' ' of' ' Software'# 字符串拼接,限于常量,注意空格
'School of Software'
'b' + 2 * 'an' + 'a' # 字符串重复
'banana'
programming = 'Programming'
programming[0] # 下标
'P'
programming[-1]
'g'
programming[5]
'a'
programming[:2] # 切片
'Pr'
programming[4:]
'ramming'
programming[-2:]
'ng'
programming[:2] + programming[2:]
'Programming'
列表
square = [1, 4, 9, 16, 25]
square
[1, 4, 9, 16, 25]
square[0]
1
square[-1]
25
square[-3:]
[9, 16, 25]
square[:]
[1, 4, 9, 16, 25]
square + square
[1, 4, 9, 16, 25, 1, 4, 9, 16, 25]
square * 3
[1, 4, 9, 16, 25, 1, 4, 9, 16, 25, 1, 4, 9, 16, 25]
square[2] = 0 # 列表元素可变
square
[1, 4, 0, 16, 25]
square.append(-1)
square
[1, 4, 0, 16, 25, -1]
len(square) # 返回列表长度
6
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b] # 列表嵌套
c
[[1, 2, 3], [4, 5, 6]]
c[0][1]
2
x = 20
if x < 0:
x = 0
print("negative value of x")
elif x == 0:
print("zero")
elif x == 1:
print("single")
else:
print("More")
More
words = ['Java', 'C++', 'Ruby']
for w in words:
print(w, len(w))
Java 4 C++ 3 Ruby 4
for i in range(5):
print(i)
0 1 2 3 4
函数
def foo():
print("hello world")
def add(x, y):
return x + y
print(add(3, 4))
7
foo()
hello world
import turtle
def square(length):
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
square(10)
def tree(len, n):
if n <= 0:
return
else:
turtle.forward(len)
turtle.left(45)
tree(len * 0.5, n - 1)
turtle.right(90)
tree(len * 0.5, n - 1)
turtle.left(45)
turtle.backward(len)
turtle.speed(0)
tree(200, 9)
def snowflake(length, threshold):
if length < threshold:
turtle.forward(length)
else:
length = length / 3
#segment 1
snowflake(length, threshold)
turtle.left(60)
#segment 2
snowflake(length, threshold)
turtle.right(120)
#segment 3
snowflake(length, threshold)
turtle.left(60)
#segment 4
snowflake(length, threshold)
for i in range(3):
snowflake(300, 10)
turtle.right(120)
def triangle(length, threshold):
if length < threshold:
return
else:
for i in range(3):
turtle.forward(length)
triangle(length/2, threshold)
turtle.backward(length)
turtle.left(120)
triangle(100, 1)