(Python )控制流语句if、for、while

时间:2023-11-18 13:17:44

这一节,我们将学习Python的控制流语句,主要包括if、for、while、break、continue 和pass语句


1. If语句


  • if语句也许是我们最熟悉的语句。其使用方法如下:

x=input("please input an integer:")

if  x<0:

print 'x<0'

elif x==0:

print 'x=0'

elif x>0:

print 'x>0'

else:

print ' x is not an number'

运行结果:

>>>

please input an integer:10

x>0


2.for 循环语句


  • Python的for循环和其他语言有一些不同。 Python的for循环可以遍历任何序列,如列表和字符串。

words=['hello','hao are you',10,'ha']

for w in words:

print w

运行结果:

>>>

hello

hao are you

10

ha

  • 用户还可以根据自己的需要定义循环的始末位置以及每次循环迭代步长。

words=['hello','hao are you',10,'ha',1,2,3,4,5]

for w in words[1:6:2]:

print w

运行结果:

>>>

hao are you

ha

2

  • 如果想对一个数字序列进行循环,我们可以使用range()函数来产生数字序列

for i in range(1,10,2):

print i

运行结果:

>>>

1

3

5

7

9


3.while循环语句


  • 当while的条件判断为True时,就会执行循环体中的语句。 这个条件可以是一个数字、字符串或者一个列表,只要这个字符串或列表的长度不为0,则条件为True。非0的数字也是True

a=5

while a>0:

print a

a=a-1

运行结果:

>>>

5

4

3

2

1

  • while的循环条件可以是一个数字、字符串或者一个列表,只要这个字符串或列表的长度不为0,则条件为True。非0的数字为True

lists=["hello",1,2,3]

while lists:

print lists[0]

lists.pop()

运行结果:

>>>

hello

hello

hello

hello


4. break和continue语句


  • break结束整个当前循环体

for i in range(5):

if i==2:

break

else:

print i

运行结果:

>>>

0

1

  • continue结束当前语句以及该语句循环体内之后的语句,继续执行下一次循环。

for i in range(5):

if i==2:

continue

else:

print i

运行结果:

>>>

0

1

3

4


5.pass语句


  • pass语句不会做任何事情,该语句可以用来预留代码位置

for i in range(4):

pass


6.补充知识点


  • 循环语句(while 或者for)后,可以跟上else语句,该语句在循环结束后执行:

for i in range(5):

print i

else:

print " for...else"

运行结果:

>>>
0
1
2
3
4
for...else

  • 需要注意的是,当循环被break语句终止后,else语句不会被执行:

for i in range(5):

if i==2:

break

else:

print i

else:

print " for...else"

运行结果:

>>>
0
1