Home >Backend Development >Python Tutorial >讲解Python中if语句的嵌套用法

讲解Python中if语句的嵌套用法

WBOY
WBOYOriginal
2016-06-06 11:16:201429browse

 可能有这样一种情况,当你想检查其他条件后一个条件解析为真。在这种情况下,可以使用嵌套的if结构。

在嵌套的 if 语句结构,可以在一个 if... elif... else 结构里面可有另外一个 if... elif... else 结构。
语法:

嵌套 if...elif...else 结构的语法可以是:

if expression1:
  statement(s)
  if expression2:
   statement(s)
  elif expression3:
   statement(s)
  else
   statement(s)
elif expression4:
  statement(s)
else:
  statement(s)

限,欢迎指正。转载请务必注明出处。

可能有这样一种情况,当你想检查其他条件后一个条件解析为真。在这种情况下,可以使用嵌套的if结构。

在嵌套的 if 语句结构,可以在一个 if... elif... else 结构里面可有另外一个 if... elif... else 结构。
语法:

嵌套 if...elif...else 结构的语法可以是:

if expression1:
  statement(s)
  if expression2:
   statement(s)
  elif expression3:
   statement(s)
  else
   statement(s)
elif expression4:
  statement(s)
else:
  statement(s)

例如:

#!/usr/bin/python

var = 100
if var < 200:
  print "Expression value is less than 200"
  if var == 150:
   print "Which is 150"
  elif var == 100:
   print "Which is 100"
  elif var == 50:
   print "Which is 50"
elif var < 50:
  print "Expression value is less than 50"
else:
  print "Could not find true expression"

print "Good bye!"

当执行上面的代码,它会产生以下结果:

Expression value is less than 200
Which is 100
Good bye!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn