`
knightseal
  • 浏览: 6673 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

python学习笔记3.1.3x 之if 语句以及while语句

阅读更多

标准的If 语句如下用法:

 

if expression
   if_suite

 

说明:如果表达式的值非0或者布尔值为Ture,则代码组if_suite被执行;否则就去执行下一条。

if_suite 表示一个子代码块 可以是一条或者多条语句组成

python的条件表达式不需要括号括起来

#! /usr/bin/python
#coding=utf8
x=int(input('请输入一个数字:'))
if x < 0:
    
    print('Negative changed to zero')
elif x==0:
    print('0')

else :
    print('大于0')

 

标注的while语句和if语句类似

while expression
        while_suite

 

while_suite会连续不断的循环执行,直到表达式的值为0或者是False,接着python会执行下一句代码

#!/usr/bin/python
#coding=utf8
a=0
while a < 3:
    print('循环%d'% a)
    a +=1

 

这个结果为

ActivePython 3.1.3.5 (ActiveState Software Inc.) based on
Python 3.1.3 (r313:86834, Dec  3 2010, 13:32:40) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
循环0
循环1
循环2
>>>

 

因为a初始值为0,满足a<3 ,所有while语句会继续执行,当我们设定 a每次循环+1 当第四次a的值为4 ,4<3 为false

所以循环停止

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics