python语法入门

详细教程可以参考:https://docs.python.org/3/tutorial/index.htmlhttps://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
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值