Lesson 3 of initial python

Keywords: Python less REST

Reference source: Vitu.AI

Today, let's look at the use of Boolean. Boolean types in Python are represented by two constants, True and False.

x = True
print(x)
print(type(x))

Unlike the example above, which assigns True to x, we usually don't put True and False directly in the code, but get the Boolean value through some operational comparison, that is, True and False.

Comparison + Boolean =?

operation describe
a == b a equal to b
a < b a less than b
a > b a greater than b
a <= b a less than or equal to b
a >= b a greater than or equal to b
a != b a not equal to b
def can_run_for_president(age):
    """Can someone of the given age run for president in the US?"""
    # The US Constitution says you must "have attained to the Age of thirty-five Years"
    return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))

Compared with python itself, comparative computing is a bit smarter. For example, you can judge two types of values: float and int.

3.0 == 3

But not so smart. For example, you can't judge the values of str and int.

'3' == 3

The comparison operation can be combined with the arithmetic operation we have seen to express almost infinite mathematical test range.

For example, we can determine whether a number is odd by checking whether the remainder after dividing it by 2 returns 1:

def is_odd(n):
    return (n % 2) == 1

print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))

When comparing, remember to use = = instead of =.
If you write n == 2, you ask for the value of n. If you write n = 2, you are assigning 2 to n.

Combination + Boolean =?

In Python, Boolean values can be used for or, and, and no operations. Unlike many languages, Python is not represented by symbols, but by English words, namely, or, and, and not.

Let's take another example:

def can_run_for_president(age, is_natural_born_citizen):
    """Can someone of the given age and citizenship status run for president in the US?"""
    # The US Constitution says you must be a natural born citizen *and* at least 35 years old
    return is_natural_born_citizen and (age >= 35)

print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))

Let's analyze one by one.

We set up an American citizen aged 35 and over to run for president.

Print (can "run" for "President (19, true)) is to ask if a 19-year-old American citizen can run for president. The answer is False.

Print (can "run" for "President (55, False)) is to ask whether a 55 year old non-U.S. citizen can run for president. The answer is False.

Print (can "run" for "President (55, True)) is to ask a 55 year old American citizen whether he can run for president. The answer is True.

Let's guess the output of the following line of code:

True or True and False

In python, operations have priority. In the above code, and takes precedence over or.

Specifically, in the above code, python will first judge the part of True and False to get the result of False. Then combined with the previous part, judge True or False to get the final result True.

We can remember the priority of the operation, or we can express it in parentheses, which is safer.
for instance:

prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

The code above looks like a mess.

In fact, I try to say that in the following three cases, today's weather is safe for me:

If I have an umbrella

If the rain is not too heavy, I happen to wear a pullover

And if it rains, but it's not a working day (you can stay at home during the holiday, whether it rains or not will not affect me)

But not only is my python code hard to read, but there is also a bug in the third case.

So we can solve these two problems by adding some brackets:

prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)

We can also use line breaks to make three situations more obvious:

prepared_for_weather = (
    have_umbrella 
    or ((rain_level < 5) and have_hood) 
    or (not (rain_level > 0 and is_workday))
)

Conditional statement + Boolean =?

Although Boolean value itself is very useful, but with conditional statements, that is, with the keywords if,elif and else, Boolean value plays a greater role.

for instance:

def inspect(x):
    if x == 0:
        print(x, "is zero")
    elif x > 0:
        print(x, "is positive")
    elif x < 0:
        print(x, "is negative")
    else:
        print(x, "is unlike anything I've ever seen...")

inspect(0)
inspect(-15)

Like other languages, python also uses if and else, while the only key word belonging to Python is elif, which is the abbreviation of "else if", which is used to express different situations of conditional judgment.

In these conditional clauses, elif and else are optional; we can include any number of elif statements.

We need to pay special attention to the use of colons (:) and spaces to represent individual blocks of code.

This is similar to what happens when we define functions. The function header ends with a colon (:), followed by a line indented with four spaces. All subsequent contractions belong to the function body until we encounter a line without indentation to end the definition of the function.

def f(x):
    if x > 0:
        print("Only printed when x is positive; x =", x)
        print("Also only printed when x is positive; x =", x)
    print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)

How to interpret the code above?

When we input f(1), because the condition of x > 0 is met, three lines of content will be printed respectively;

When we input f(0), because the condition of x > 0 is not met, only the third line will be printed;

Boolean conversion

We have learned before that int() is a function that converts values to integers, while float() is a function that converts values to floating-point numbers, that is, numbers with decimal places.

As you can imagine, python also has a function of bool(), which can change things into Boolean values.

# All numbers are considered True except 0
print(bool(1)) 
print(bool(0))
# All strings are considered True except the empty string ''
print(bool("asf")) 

# Usually empty sequences (strings, lists, and other types we haven't seen yet, such as tuples) are "fake" and the rest are "real")
print(bool(""))

In the conditional statement of if, we can also directly use non Boolean values, which python will silently regard as the corresponding Boolean values.

if 0:
    print(0)
elif "spam":
    print("spam")

In the above code, because 0 is False by default, the if judgment does not hold, and the elif judgment is automatically entered; and because "spam" is a non empty string, it is True by default, so the judgment holds, so the final output is "spam".

Expression of conditions

In python, it is common to assign different values to a variable in different situations through conditional statements.

def quiz_message(grade):
    if grade < 50:
        outcome = 'failed'
    else:
        outcome = 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(80)

In addition to the above expression, the conditional statement of if has a simple one line expression. Let's have a look.

def quiz_message(grade):
    outcome = 'failed' if grade < 50 else 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(45)

Original address: Lesson 3 of initial python

Posted by greenCountry on Sun, 08 Dec 2019 07:59:15 -0800