Python Language Lesson: if statement
An if statement is needed to make decisions based on variable values:if x > 0:
appuifw.note(u"x is positive!")
else:
appuifw.note(u"x is negative or zero.")
The Boolean expression after the word ‘ if’ is called the condition.
If the condition is true (in this case, if the value of the variable
x is bigger than 0), then the indented statement in the next line
(here, appuifw.note(u"x is positive!") ) is executed. If the
condition is false, the statement in the else branch is executed (here,
appuifw.note(u"x is negative or zero.") ). Note that you
can reverse the outcome of the condition, by putting the not keyword
in front of the condition.
The most important comparison operators are ==, !=, < and >, for
equality, inequality, less than and greater than. Note that if you want
to test whether a variable is not false, zero, None or an empty string or
list, you can use the following shorthand:
if x:
appuifw.note(u"x is not empty")
You can test many conditions in sequence:
if x > 0:
appuifw.note(u"x is positive!")
elif x == 0:
appuifw.note(u"x is zero.")
else:
appuifw.note(u"x is negative.")
No comments:
Post a Comment