详细教程可以参考:https://docs.python.org/3/tutorial/index.html和https://docs.python.org/zh-tw/3/tutorial/index.html
变量定义:
不需要说明类型
x = 7
y = x * 3
name = "Chris"
输出
函数不需要主函数,可以直接运行
# 换行输出
print x
print y
# 不换行输出
print x,
print y,
判断语句
x = 7
if x > 5:
print("x is bigger than 5")
else:
print("x is less than or equal 5")
定义递归函数
注释:用#或者三个连续引号
'''
阶乘函数
'''
def factorial(x):
if x == 0:
return 1
return x * factorial(x-1)
# We call a function like this:
factorial(5)
例题:求n个人的班级每个人生日不相同的概率
def birthday_paradox(n):
return (factorial(365)/factorial(365-n))/(pow(365,n))
注意:除法是小数除法,整除要用"//"
循环语句
def factorial_while(x):
total = 1
while x > 0:
total = total * x
x = x - 1
return total
注意:x--不可以每次减一,--x是合法语句,但是它的意思是x取负数再取负数
range会从0开始,所以我们用i+1作为乘数防止结果为0
def factorial_for(x):
total = 1
for i in range(x):
total = total * (i + 1)
return total