程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python learning 3

編輯:Python

Conditional expression

In select and loop structures, the value of the conditional expression as long as it is not False, 0 (or 0.0, 0j, etc.), the empty value None, the empty list, the empty tuple, the empty set, the empty dictionary, the empty string, the emptyrange objects or other empty iterable objects are considered equivalent to True by the Python interpreter.

Logical operators and and or and relational operators have lazy evaluation characteristics, Only evaluate expressions that must be evaluated.

Take "and" as an example, for the expression "expression1 and expression2", if the value of "expression1" is "False" or other equivalent values, regardless of the value of "expression2"What is the value, the value of the entire expression is "False", at this time the value of "expression 2" does not affect the value of the entire expression, so it will not be calculated, thereby reducing unnecessary calculations andjudge.

Python also supports expressions of the form:

value1 if condition else value2

When the value of the conditional expression condition is equal to True, the value of the expression is value1, otherwise the value of the expression is value2.Complex expressions, including function calls and basic output statements, can also be used in value1 and value2.Expressions of this structure also feature lazy evaluation.

>> a = 5>>> print(6) if a>3 else print(5)6>>> print(6 if a>3 else 5)6>>> b = 6 if a>13 else 9>>> b9

Lazy Evaluation

#The math module has not been imported at this time>>> x = math. sqrt(9) if 5>3 else random.randint(1, 100)NameError: name 'math' is not defined>>> import math#The random module has not been imported at this time, but since the value of the conditional expression 5>3 is True, it can run normally>>> x = math.sqrt(9) if 5>3 else random.randint(1,100)#The random module has not been imported at this time. Since the value of the conditional expression 2>3 is False, the value of the second expression needs to be calculated, so an error occurs>>> x = math.sqrt(9) if 2>3 else random.randint(1, 100)NameError: name 'random' is not defined>>> import random>>> x = math.sqrt(9) if 2>3 else random.randint(1, 100)

Loop

while loop and for loop


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved