python3的循环和条件控制
2016-07-19 18:59
531 查看
python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块python中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else
在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块
3、在Python中没有switch – case语句
python中的循环语句有 for 和 while
python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
for循环的一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
python中while语句的一般形式:
while 判断条件:
语句
同样需要注意冒号和缩进另外,在python中没有do..while循环
test.py
执行结果
在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块
3、在Python中没有switch – case语句
python中的循环语句有 for 和 while
python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
for循环的一般格式如下:
for <variable> in <sequence>:
<statements>
else:
<statements>
python中while语句的一般形式:
while 判断条件:
语句
同样需要注意冒号和缩进另外,在python中没有do..while循环
test.py
#!/usr/bin/python3 #1到100的和 n=100 sum=0 counter=1 while counter<=n: sum=sum+counter counter+=1 else: print(counter,"循环已结束") print("1到 %d 的和为 %d" % (n,sum)) lang=["php","java","js","android","python","sql"] for x in lang: if(x=="php"): print("这里是php") elif(x=="java"): print("这里是java") elif(x=='python'): print("python这break,sql不会显示") break; else: print(x) print("完成循环!") 执行结果 [root@localhost pythonCode]# python3 test.py 101 循环已结束 1到 100 的和为 5050 这里是php 这里是java js android python这break 完成循环!
执行结果
[root@localhost pythonCode]# python3 test.py 101 循环已结束 1到 100 的和为 5050 这里是php 这里是java js android python这break 完成循环!
相关文章推荐
- python多线程(1)--单线程和多线程
- EM算法与高斯混合聚类
- python3的运算符
- caffe的python接口学习(5):生成deploy文件
- Python高阶函数:filter、map、reduce、lambda
- Python查询数据库时间类型列
- python -- 计算数学题--用程序解决问题1
- python学习笔记(面向对象)
- python3的字符串
- Python array,list,dataframe索引切片操作 2016年07月19日——智浪文档
- python练习——水仙花数
- Python-属性(property)
- python_gui之tk
- How can I pretty-print JSON in python?
- python 元组 字符串 字典 列表嵌套练习题1
- Python-描述符
- Python爬虫----网页下载器和urllib2模块及对应的实例
- Python 模块学习:os模块
- Python 查看 微信被删除好友
- python中的@