Conditional Judgment in Python

Conditional judgment

The reason why computers can do a lot of automation tasks, because it can make their own conditions to judge.

For example, enter the user age, according to age to print different content, in the Python program, with the if statement to achieve:

age = 20
if age >= 18:
    print('your age is', age)
    print('adult')

According to Python’s indentation rule, if the if statement is True, the indented two lines of the print statement are executed, otherwise nothing is done.

You can also add a else statement, if that if the judge is False, do not perform the contents of the if, to the implementation of the else:

age = 3
if age >= 18:
    print('your age is', age)
    print('adult')
else:
    print('your age is', age)
    print('teenager')

Be careful not to write a colon.

Of course, the above judgment is very rough, you can use elif to do more detailed judgments:

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

elif is the abbreviation of else if, there can be multiple elif, so the complete form of the if statement is:

if <conditional judgment 1>:
<Execution 1>
elif <conditional judgment 2>:
<Execution 2>
elif <conditional judgment 3>:
<Executive 3>
else:
<Executive 4>

if the statement is true, it is from the top down to judge, if a judge is True, the judge corresponding to the implementation of the statement. It will ignore the remaining elif and else, so please test and explain why The following program prints the teenager:

age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

If the judgment conditions can also be abbreviated, such as writing:

if x:
    print('True')

As long as x is a non-zero value, non-empty string, non-empty list, etc., to determine True, otherwise False.

Again

Finally look at a conditional judgment. Many students will use input () to read the user’s input, so you can enter their own, the program runs more interesting:

birth = input('birth: ')
if birth < 2000:
    print('before 00')
else:
    print('after 00')

Input 1982, the results being given:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

This is because the input () return to the data type is str, str can not be directly compared with the integer, you must first str into an integer. Python provides the int () function to do this:

s = input('birth: ')
birth = int(s)
if birth < 2000:
    print('before 00')
else:
    print('after 00')

Run again, you can get the correct results. But if you enter abc? Will get an error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

The original int () function found a string is not a legitimate number will be error, the program will quit.