晓夏

YoungCheung

Zhang Sir's technical way

Python循环语句和循环控制语句

浏览量:823

一、循环语句

1、while语句用于重复执行,只要表达式为true:

#!/usr/bin/python

count = 0
while (count < 9 ):
    print("The count is %s" %(count))
    count = count + 1

print("Good bye!")

输出结果:

The count is 0
The count is 1
The count is 2
The count is 3
The count is 4
The count is 5
The count is 6
The count is 7
The count is 8
Good bye!

 2、if语句

        Perhaps the most well-known statement type is the if statement. For example:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 12
>>> if x <=0:
...     print('Negative changed to zero')
... elif x == 1:
...     print('Zero')
... elif x >= 1:
...     print('Single')
... else:
...     print('More')
... 
Single

3.for循环

        The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

        在forPython中的语句和你和C或Pascal中的略有不同。而不是总迭代数算术级数(如Pascal)或由用户来定义迭代步骤和中止条件(如C)的能力,Python的for任意序列的物品语句迭代(列表或字符串),按照它们在序列中出现的顺序。例如(不是双关语):

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w,len(w))
... 
cat 3
window 6
defenestrate 12

        If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

        如果你需要修改你迭代,而循环中(例如复制选择项),建议您先制作一个副本的顺序。对序列进行迭代不会隐式地进行复制。切片符号使这特别方便:

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]:
...     if len(w) > 6:
...         words.insert(0,w)
... 
>>> 
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

        With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

        使用,该示例将尝试创建一个无限列表,一遍又一遍地插入。for w in words:defenestrate

二、控制语句

1、break

示例1:

for letter in 'Python':
   if letter == 'h':
      break
   print('Current Letter :', letter)

输出结果:

Current Letter : P
Current Letter : y
Current Letter : t

示例2

var = 10   
while var > 0:              
   print('Current variable value :', var)
   var = var -1
   if var == 5:
      break

输出结果:

Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6

2.continue

示例1:

>>> for letter in 'Python':
...    if letter == 'h':
...       continue
...    print('当前字母 :', letter)

输出结果:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n

示例2:

>>> var = 10
>>> while var > 0:              
...    var = var -1
...    if var == 5:
...       continue
...    print('当前变量值 :', var)

输出结果:

当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0

补充:pass

        pass语句什么也不做。它可以在语法需要语句但程序不需要操作时使用。例如:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)...

        这通常用于创建最少的类:

>>> class  MyEmptyClass :
...     pass 
...

        另一个地方pass可以用作一个函数或条件体的占位符,当你在编写新代码,允许你继续思考一个更抽象的水平。将pass被自动忽略:

>>> def  initlog (* args):
...     pass    #记住实现这个!
... ...

游戏:猜年龄

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "YoungCheung"
Age=22
start_count=0
end_count=5
while start_count<end_count:
    user_input=int(input('请您猜个数字:'))
    if user_input>22:
        print("您输入的年龄太大,请输入小的年龄")
    elif user_input==22:
        print("恭喜你,猜对了!!")
        break
    else:
        if start_count<end_count-1:
            print("您输入的年龄太小,请输入大的年龄")
    start_count +=1
else:
    print("你是傻逼啊,猜%s次都猜不对"%(end_count))


神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。