Python学习之路day03——009while循环语句

一、while循环语句

for循环用于针对集合中的每个元素的代码块,而while循环不断地运行,直到指定的条件不满足为止。

1、while循环书写

current_number = 1
while current_number <= 5:
       print(current_number)
       current_number += 1

2、让用户自主选择合适退出

# -*- coding: gb2312 -*-
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ''
while message != 'quit':
        message = input(prompt)
        print(message)

3、使用标志

active = True
while active:
    message = input(prompt)
    if message == 'quit':
         active = False
    else:
         print(message)

4、break关键字的使用

break关键字在所有的循环语句中都可以使用,for循环,if——else中,while循环中都可以使用。

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
     city = input(prompt)
    if city == 'quit':
         break

    else:
         print("I'd love to go to " + city.title() + "!") 
5、continue 关键字的使用

current_number = 0
while current_number < 10:
      current_number += 1
      if current_number % 2 == 0:
           continue
      print(current_number)

结果:1 3 5 7 9 

注意:continue表示的意思,忽略循环语句中continue后面的代码,继续返回循环开头执行循环。

6、while循环书写过程中一定要注意条件的现在,不能让程序形成死循环,这样会消耗系统大量的内存。

 

猜你喜欢

转载自www.cnblogs.com/jokerwang/p/9257316.html