程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Python 常用语句

发布于2019-08-05 11:09     阅读(898)     评论(0)     点赞(2)     收藏(0)


 

条件语句

a=input("请输入数字a的值:\n")
a=int(a)   #从控制台接收到的都是字符串类型,需要转换

if a==0:  #也可以写成if(a==0):
    print("a=0")
elif a>0:  #注意是elif
    print("a>0")
else:
    print("a<0")

 

 

 

循环语句

1、while语句

i=1
sum=0
while i<=100:  #冒号
    sum+=i
    i=i+1  #注意python中没有++、--运算符
print(sum)

 

 

2、for语句

python中for语句和其他编程语言的for语句大不相同。python中for语句:

for var in eleSet: 
    statements

eleSet指的是元素集,可以是字符串、列表、元组、集合、字典,也可以是range()函数创建的某个数字区间。

 

使用for语句遍历字符串、列表、元组、集合、字典:

for ele in "hello":  #遍历字符串的每个字符
    print(ele)

for ele in [1,2,3]:  #遍历列表、元组、集合中的每个元素
    print(ele)

dict
={"name":"张三","age":10,"score":90}
#遍历字典——方式1 for item in dict.items(): #item是元组,(key,value)的形式 print(item) #输出一个键值对 print(item[0],":",item[1]) #输出key:value

#遍历字典——方式2
for key in dict.keys():
    print(key,":",dict.get(key))

 

 

使用for语句遍历某个数字区间:

for i in range(10):  #遍历[0,10)
    print(i)

for i in range(20,30):  #遍历[20,30)
    print(i)

for i in range(50,100,10):  #遍历50,60,70,80,90,[50,100)上,步长为10
    print(i)
"""
range()函数用于产生数列:
range([min,]max[,step]) 数字区间是[min,max),max是必须的。缺省min时,默认为0,缺省step时,默认为1。 step支持负数,即负增长。 """

 

 

产生指定数字区间上的元素集:

myList=list(range(10))  #强制类型转换,列表
print(myList)  #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

myTuple=tuple(range(10))  #元组
print(myTuple)  #(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

mySet=set(range(10))  #集合
print(mySet)  #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

myDict=dict.fromkeys(range(10))  #字典
print(myDict)  #{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}

 

 

使用for语句+索引遍历字符串、列表、元组:

myList=["百度","腾旭","阿里"]
for i in range(len(myList)):
    print(i,"\t",myList[i])

"""
0      百度
1      腾旭
2      阿里
"""

 

 

else语句可以和while语句/for语句配合使用,当整个while/for循环执行完毕后,会执行else语句。

i=1
while i<5:
    print(i)
    i=i+1
else:
    print("i=5")  #整个循环执行完毕时,会自动执行else语句块
print("while over")


for i in range(5):
    print(i)
else:
    print("for over")
print("application over")

 

 

continue语句:结束当前本次循环

break语句:结束当前循环

这2个语句只能写在循环体中,不能写在else语句块中。

i=1
while i<5:
    i=i+1
    if(i==2):
        continue
    print(i)
else:
    print("over")

 

 

如果循环被break终止了,则else语句不会被执行:

i=1
while i<5:
    i=i+1
    if(i==5):
        break
else:
    print("else running...")   #如果循环被break终止,else语句块会被跳过。只要循环中执行了break,else语句块就不再执行。
print("over")  #over

 

 

 

 

pass语句

pass语句是一个空语句,即什么都不做。

command=input("请输入指令:\n")
if command=="nothing":
    pass   #什么都不做
elif command=="exit":
    exit()  #退出程序
else:
    print("无法识别的指令")

 

 

 

 

说明

  • python中没有switch语句、do...while语句。
  • python使用缩进来标识语句块。
  • 如果语句块只有一条语句,可以写在同一行:
if True:print(True)

 



所属网站分类: 技术文章 > 博客

作者:喜洋洋与红太狼

链接:https://www.pythonheidong.com/blog/article/4226/caab2fa0db11d41b8a25/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)