Detailed explanation and application scenarios of Python basic types (3) -- Boolean value

background

For many Python beginners, it is very difficult to understand the structure and function of each of our data.
Therefore, it is very necessary to understand the structure, expression, usage and application of each basic type in our program.

This article strives to explain the relevant information of the basic type Boolean in simple and clear language

introduce

Boolean is a subtype of the numeric type, called bool in python , with 0 for true and 1 for false, and in python with True and False

In order to let readers understand the relationship between True, False and 1 and 0 more vividly, we can enter the following code results

print(True + 1)
print(False + 1)

# 输出:
# 2
# 1

All objects in python can judge boolean values

use

We can bool(obj)judge the Boolean value of an object by , and we can also judge by the operator symbols greater than , equal to , less than , greater than or equal to , and less than or equal to . As shown in the code below

print(12)
print(bool(0))
print(bool(1))
print(type(12))

# 输出:
# False
# False
# True
# <class 'bool'>

We often use boolean values ​​in conditional judgments to control the execution flow of our code.

For example: Xiaoming buys fruit for 10 yuan per catty. If you buy less than 5 catties including 5 catties, the original price will be calculated, and if you buy more than 5 catties, you will get a 20% discount. How much does Xiao Ming need to pay for fruit of any weight?

We can easily make the following formula in mathematics:
define x as fruit weight define x as fruit weightDefine x as fruit weight
y = { 5 × 10 + ( x − 5 ) × 10 × 0.8 , x < 5 5 × 10 , x > 5 y = \begin{cases} 5 \times 10 + (x - 5) \times 10 \times 0.8 , & x < 5 \\ 5 \times 10, & x > 5 \end{cases}y={ 5×10+(x5)×10×0.8,5×10,x5x5

And we convert the above formula into a python code as shown in the following code

x = eval(input("请输入购买的重量"))
y = 0
if x >= 5:
  y = 5 * 10 + (8 - 5) * 10 * 0.8
else:
  y = 5 * 10

Guess you like

Origin blog.csdn.net/a914541185/article/details/124510084