python学习之while语句
2010-08-19 13:13
387 查看
while语句在一个条件为真的情况下,
当输入23时,程序执行done,结束,否则一直在循环(当然输入非整数时语法错误,程序会跳出的)。
运行结果:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The whileloop is over.
Done
//这里要说明的是python语言对空格要求的很严格,必须是对应的,否则语法是不正确的。例如上面例子中
……
if
……
编写成
if
运行结果:
File "while.py", line 12
running =False# this causes the whileloop to stop
^
SyntaxError: invalid syntax
这一点不像其他语言那么灵活的。
while语句允许你重复执行一块语句。直接看例子:
#!/usr/bin/python # Filename: while.py
number =
23
running =
True
while
running:
guess =
int
(
raw_input
(
'Enter an integer : '
))
if
guess == number:
'Congratulations, you guessed it.'
running =
False
# this causes the whileloop to stop
elif
guess < number:
'No, it is a little higher than that'
else
:
'No, it is a little lower than that'
else
:
'The whileloop is over.'
# Do anything else you want to do here
'Done'
当输入23时,程序执行done,结束,否则一直在循环(当然输入非整数时语法错误,程序会跳出的)。
运行结果:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The whileloop is over.
Done
//这里要说明的是python语言对空格要求的很严格,必须是对应的,否则语法是不正确的。例如上面例子中
……
if
guess == number:
'Congratulations, you guessed it.'
running =
False
# this causes the whileloop to stop
elif
guess < number:
……
编写成
if
guess == number:
'Congratulations, you guessed it.'
running =
False
# this causes the whileloop to stop
elif
guess < number:
运行结果:
File "while.py", line 12
running =False# this causes the whileloop to stop
^
SyntaxError: invalid syntax
这一点不像其他语言那么灵活的。
相关文章推荐
- 学习笔记☞ python 基础(python3)【三】(转义字符,字符串,while循环,break语句,列表)
- python 学习 if语句while语句
- python基础学习(3)—while循环语句
- Python新手学习基础之循环语句——While循环
- python控制流语句if、while、for、break、contnue的学习———ubuntu下python的学习(2)
- python学习2——if语句、elif、if嵌套、while循环、while嵌套
- python学习小结2:if和while控制语句
- Python基础,基本类型(整型,浮点数等)数据结构(List,dic(Map),Set,Tuple),控制语句(if,for,while,continue or break):来自学习资料
- Python学习笔记五:while语句
- python 学习while语句中的break&continue
- python 学习(五) While 循环语句
- Python新手学习基础之循环语句——While循环
- python学习小结2:if和while控制语句
- Python学习--控制语句:if, while, for, break, continue
- Python学习笔记——输入语句和while循环
- python学习之while语句
- python基础学习(五)while循环语句
- Python新手学习基础之循环语句——While循环
- python学习之语句:循环语句(for,while)
- Python新手学习基础之条件语句——While循环