linux下python学习笔记(六)

这篇介绍控制流,就是真正的python语句了。

 

在Python中有三种控制流语句——if、for和while。

1. if

#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
  print 'Congratulations, you guessed it.' # New block starts here
  print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
  print 'No, it is a little higher than that' # Another block
  # You can do whatever you want in a block ...
else:
  print 'No, it is a little lower than that'
  # you must have guess > number to reach here
print 'Done'
# This last statement is always executed, after the if statement is executed

这个程序很简单,在这个程序中raw_input()获取用户输入的数字。我们为raw_input函数提供一个字符串,这个字符串被打印在屏幕上,然后等待用户的输入。一旦我们输入一些东西,然后按回车键之后,函数返回输入。对于raw_input函数来说是一个字符串。我们通过int把这个字符串转换为整数,并把它存储在变量guess中。事实上,int是一个类。

注意我们这里使用了缩进层次表达语句块,而且if,else语句后面有个(:)。

今后会介绍字典。

 

2. while

#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'

注意如果while循环有一个else从句,它将在你退出while循环时执行。这你也可以看出,else是多余的。

 

3. for

for..in是循环语句,它在一序列的对象上递归,即逐一使用队列中的每个项目。

#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over'

我们使用内建的range函数生成这个数的序列。我们所做的只是提供两个数,range返回一个序列的数。这个序列从第一个数开始到第二个数
为止。例如,range(1,5)给出序列[1, 2, 3, 4]。默认地,range的步长为1。如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]。记住,range 向上 延伸到第二个数,即它不包含第二个数。

4. break

#!/usr/bin/python
# Filename: break.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'

输入字符串的长度通过内建的len函数取得。

 

5. continue

#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
# Do other kinds of processing here...

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值