Python if条件/while循环语句

Python if条件语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

if ...else 结构

if(表达式):
  语句1
else:
  语句2

 

实例:

#!/usr/bin/python
age = 19
if age >= 18:
   print("you are old enough.")
else:
   print("You are too young.")

 

if...elif..else结构

if(表达式1):

   语句1

elif(表达式2:):

   语句2

...

elif(表达式n):

   语句n

else:

    语句m

 

实例:

#!/usr/bin/python

age = 12
if age < 4:
   print("your admission cost is $0")
elif age < 18:
   print("your admission cost is $5")
else:
   print("your admission cost is $10")

 

 

Python while语句

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件:

    执行语句...

 

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件为false时,循环结束。

 

实例

#!/usr/bin/python

prompt = "\nTell me something, and i will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = ""                       ##定义一个空字符,让python首次执行为了代码时有可供检查的东西
while message != 'quit':       ##当message的值为quit时,才会停止循环
       message = input(prompt)
       print(message)


执行测试

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program.ss
ss

Tell me something, and i will repeat it back to you:
Enter 'quit' to end the program.quit
quit

 

 

使用break退出循环
如果需要立即退出while循环不再运行循环余下的代码,也不管条件测试的结果如何,可使用break语句,break语句用于控制程序流程,控制哪些代码执行,哪些代码不执行

 

实例
#!/usr/bin/python

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':              ##当输入的为quit时,中断循环
        break
    else:
        print("You have visited " + city.title() + "!" )

 

执行:

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)new york
You have visited New York!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.)beijing
You have visited Beijing!

 

 

在循环中使用continue ,continue 用于跳过该次循环


#!/usr/bin/python

current_number = 0
while current_number < 10:
      current_number += 1
      if current_number % 2 == 0:      ##当前数字如果被2整除,跳出此次循环
          continue

      print(current_number)

 

转载于:https://www.cnblogs.com/kubernets/p/8721385.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值