您的位置:首页 > 编程语言 > Python开发

第三节 python控制语句

2018-03-27 15:33 302 查看

条件语句

if语句

if-else语句

if-elif-else语句

#if-else语句
#判断成绩优良
score = 80
if (score>0) and (score<=60):
print("不及格")
elif (score>60) and (score<=70):
print("及格")
elif (score>70) and (score<=90):
print("良好")
elif (score>90) and (score<=100):
print("优秀")
else:
print("成绩不在可控范围内")


循环语句

while语句

var = 0
while var<10:
print("hello world")
var+=1


while-else语句

count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")


for语句

#有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if(i!=k) and (i!=j) and (j!=k):
print(i,j,k)


for-else语句

sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")

#查询质数的例子

for n in range(2, 10):
for x in range(2, n):#循环 2-(n-1)
if n % x == 0:
print(n, '等于', x, '*', n//x)
break
else:
# 循环中没有找到元素
print(n, ' 是质数')


循环控制语句

break

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

continue

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

else

循环语句可以有 else 子句,它在循环正常终止时被执行,但循环被break终止时不执行。

函数

函数的定义

def 函数名(参数列表):
#函数体
return 返回值

#函数
def max(a,b):
if a>b:
return a
else:
return b

print(max(3,4))

#三元运算符
def min(a,b):
return a if a<b else b

print(min(5,9))


函数的参数

必需参数

#必需参数
def printHello(str):
print(str)

printHello("hello world") #其中参数是必需的,不传递参数就会出错


关键字参数

printHello(str="hello world")
#关键字参数,既可以在参数较多时不易混淆,同时,也可以不按照顺序传入参数


默认参数

#默认参数

def person(name,age,address="山东"):
print(name,age,address)

person("mike",23,"广东")
person("Jhon",34)  #如果不传递address参数,就会使用默认”山东“作为参数


不定长参数

#不定长参数
#*args 用元组存储
#** args  用字典存储
def getList(*args,**dicargs):
"函数注释,不定长参数实例"
print("元组")
for i in range(len(args)):
print("arg[",i,"]=",args[i])

print("字典")

for key in dicargs:
print(key,":",dicargs[key])

getList(1,2,3,name="mike",age=23,gender="男")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: