First example:
Age = 20if Age >=: print ' adult ' elif age < 18:
Computers can do a lot of automated tasks, because it can make their own conditions to judge.
For example, enter the age of the user, print different content according to age, in the Python program, with the if
statement implementation:
age = 20if age >= 18: print ‘your age is‘, age print ‘adult‘
According to the indentation rules of Python, if the if
statement is judged True
, the indented two lines of the print statement are executed, otherwise, nothing is done.
can also giveif
Add aelse
Statement, meaning that ifif
Judgment isFalse
, do not performif
The content, go to theelse
Carried out:
age = 3if age >= 18: print ‘your age is‘, age print ‘adult‘else: print ‘your age is‘, age print ‘teenager‘
Be careful not to write a colon less :
.
Of course, the above judgment is very sketchy, can be used to elif
do more detailed judgment:
age = 3if age >= 18: print ‘adult‘elif age >= 6: print ‘teenager‘else: print ‘kid‘
elif
Iselse if
The abbreviation, can have more than oneelif
Soif
The complete form of the statement is:
if <条件判断1>: <执行1>elif <条件判断2>: <执行2>elif <条件判断3>: <执行3>else: <执行4>
if
Statement execution has a feature, which is judged from the top down, if in a certain judgment isTrue
, after executing the statement of the judgment, it ignores the remainingelif
Andelse
, so, please test and explain why the following program prints theteenager
:
age = 20if age >= 6: print ‘teenager‘elif age >= 18: print ‘adult‘else: print ‘kid‘
if
The judging conditions can also be abbreviated, such as writing:
if x:print ' True '
As long as a non- x
0 value, a non-empty string, a non-empty list, etc., it is judged True
, otherwise False
.
Python Learning: If statement