文章目录
python的分支(条件)语句
if语句
x=int(input("please input the value of x: "))
y=int(input("please input the value of y: "))
if x>y:
print('x>y')
输出:
please input the value of x: 122
please input the value of y: 3
x>y
and 和or构造条件
x=128
y=21
z=131
if (x>=y)and(x<z):
print("yes,z>x>y")
if (x>y)or(x>z):
print("one of the conditions is true")
输出:yes,z>x>y
one of the conditions is true
if else多路分支语句
x=int(input("please input the value of x: "))
y=int(input("please input the value of y: "))
z=int(input("please input the value of z: "))
if (x>=y)and(x>=z):
print('x')
elif (x>=y)and(x<=z):
print('z')
else:
print('y')
输出:
please input the value of x: 23
please input the value of y: 345
please input the value of z: 5
y
python的循环语句
while循环
n=int(input("please input the number:"))
i=1
result=1
while i<n+1:
result*=i
i+=1
print(result)
输出:
please input the number:6
720
for循环
for i in 'hi peter':
print(i)
输出:
h
i
p
e
t
e
r
内置函数range
函数range返回一个数字序列,默认起始值为0,增量为1,以一个指定的数字结束。
for i in range(3):
print(i)
输出:
0
1
2
break和continue语句
需要提前结束循环用break
不想要某一次的循环,接下来的循环操作还要继续执行用continue
i=1
while i<11:
print(i)
if i>=5:
break
i+=1
输出:
1
2
3
4
5
i=2
while i<11:
i+=3
if i==5:
continue
print(i)
输出:
8
11
python的函数
函数就是给一串动作起名字
函数可以有一个或者多个输入,但只有一个输出
定义函数语法格式:
def 函数名(参数清单):
函数主体部分
return [表达式]
定义调用函数:
def paly():
print("走出去")
print("晒太阳")
print("玩耍")
paly()
函数也是对象
函数不需要大括号,但需要前面有四个空格
(Python中没有标识程序块开始和结束的关键字,是用缩进标识一个程序块
注释单行前面加#
注释多行,选中按ctrl+/或者用三引号将注释部分括起来(可以是’或者"))
函数参数
可以将任何数据类型的参数传递给一个函数
(数字、字符串、列表、字典等)
命名规则和变量一样
可以是一个或者多个(逗号隔开)
函数体里面像变量一样的使用参数
调用函数时,传入对应个数的参数(实参)关键字参数调用
def foo2(a,b):
print((a*3+b*5)/23)
foo2(3,4)
foo2(a=3,b=4)
foo2(3,b=4)
foo2(a=3,4) 不正确
函数返回值
- return关键字——可以使用return语句退出函数并返回一个值,如果return语句之后没有参数,就返回None
- 返回对象可以赋值给变量,也可以直接使用
eg:无返回值
def fun():
print("666")
m=fun()
print(m)
print(type(m))
输出:
666
None
<class ‘NoneType’>
eg:有返回值
def fun():
print("666")
return 777
m=fun()
print(m)
print(type(m))
输出:
666
777
<class ‘int’>
使用函数实现阶乘:
def factorial(n):
i=1
fac=1
while i<=n:
fac*=i
i+=1
return fac
print("3! = "+str(factorial(3)))
print("23! = "+str(factorial(23)))
输出:
3! = 6
23! = 25852016738884976640000
pass语句
是一个空语句,一般用作占位语句
变量的范围
- 局部(本地)作用域
- 封闭作用域
- 全局作用域
- 内置作用域
a=12 #全局作用域
def fun1():
b=23 #封闭作用域(包括在fun1和fun2函数中)
def fun2():
c=34 #局部(本地)作用域
局部(本地)变量和全局变量
- 定义在函数内部的变量拥有一个局部作用域(本地变量),只能在被声明的函数内部访问。
- 定义在函数外部的变量拥有一个全局作用域(全局变量),能在整个程序范围内访问。
- 调用函数时,所有在函数内声明的变量名称都将被加到本地作用域中。
递归算法和计算机堆栈
- 函数调用自身即为递归
- 一般来说递归需要有自己的边界条件、递归前进段(调用自己)和递归返回段 。边界条件不满足时,递归前进(调用自己),满足时,递归返回。
- 一般递归结构需要一个堆栈的内存结构。堆栈是个先进后出的内存结构
- 当每次递归调用时,计算机将把当前的变量都压入堆栈,一组放在之前那组之上。返回时,最后压入栈的变量开始返回,后进先出。
def factorial(n):
if (n>1):
fac=n * factorial(n-1)
print(str(n)+"!="+str(fac))
else:
fac=1
print(str(n)+"!="+str(fac))
return fac
print("please input the number:")
a=int(input())
factorial(a)
输出:
please input the number:
6
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720