Python learning: if statement and pythonif statement
Example:
age = 20if age >= 18 : print 'Adult'elif age < 18 : print 'Nonage'
A computer can perform a lot of automated tasks because it can perform conditional judgment on its own.
For example, input the user's age and print different content according to the age. In the Python program, useif
Statement implementation:
age = 20if age >= 18: print 'your age is', age print 'adult'
According to the indentation rules of Python, ifif
Statement judgment isTrue
And the Indented print statement is executed. Otherwise, nothing is done.
You can alsoif
Addelse
Statement, which means that ifif
YesFalse
, Do not executeif
Toelse
Executed:
age = 3if age >= 18: print 'your age is', age print 'adult'else: print 'your age is', age print 'teenager'
Do not write less colons.:
.
Of course, the above judgment is very rough and can be used completely.elif
Make a more detailed judgment:
age = 3if age >= 18: print 'adult'elif age >= 6: print 'teenager'else: print 'kid'
elif
Yeselse if
Can have multipleelif
, Soif
The complete statement form is:
If <condition judgment 1>: <execution 1> elif <condition Judgment 2>: <execution 2> elif <condition judgment 3 >:< execution 3> else: <execution 4>
if
Statement execution has the following characteristics: it is judged from top to bottom, if it isTrue
, Ignore the remainingelif
Andelse
So, test and explain why the following program printsteenager
:
age = 20if age >= 6: print 'teenager'elif age >= 18: print 'adult'else: print 'kid'
if
The judgment condition can also be abbreviated, for example, write:
if x: print 'True'
As longx
It is a non-zero value, non-empty string, non-empty list, etc.True
OtherwiseFalse
.