简明 Python 教程 -- 第6章 控制流

豆豆网   技术应用频道   2007年03月28日    社区交流

本文详细介绍简明 Python 教程 -- 第6章 控制流

  简介

  在到目前为止我们所见到的程序中,总是有一系列的语句,Python忠实地按照它们的顺序执行它们。如果你想要改变语句流的执行顺序,该怎么办呢?例如,你想要让程序做一些决定,根据不同的情况做不同的事情,例如根据时间打印“早上好”或者“晚上好”。

  你可能已经猜到了,这是通过控制流语句实现的。在Python中有三种控制流语句——if、for和while。

  if语句

  if语句用来检验一个条件, 如果 条件为真,我们运行一块语句(称为 if-块 ), 否则 我们处理另外一块语句(称为 else-块 )。 else 从句是可选的。

  使用if语句

  例6.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

  (源文件:code/if.py)

  输出

$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

责编:豆豆技术应用

正在加载评论...