3  变量

3.1 全局变量

在函数外部定义一个全局变量,在函数内部使用global关键字声明该变量为全局变量,然后在函数内部对其进行赋值。这样其他所有函数就可以直接访问该全局变量。

my_variable = None  # 在函数外部定义全局变量

def func1():
    global my_variable  # 在函数内部声明为全局变量
    my_variable = 10


def func2():
    print(my_variable)  # 在其他函数中访问全局变量

func1()
func2() 
10
错误使用方法

在函数外部用global

实例:结构化病历模板在函数外部使用global username,导致系统不能正确显示已制作模板。

3.2 可判断为False变量

在Python中,以下值被判断为 False

  1. False: 布尔型,表示假。
  2. None: 表示空值或者缺失值。
  3. 0(包括 0, 0.0, 0j): 表示零值的整数、浮点数和复数。
  4. 空序列和空集合:包括空字符串 ''、空列表 []、空元组 ()、空字典 {}、空集合 set()
  5. 其他“空”对象:例如空的用户自定义类的实例。

除了上述值之外,所有其他值都被判断为 True。这种规则在条件语句、布尔运算和其他上下文中都适用。

# 1. `False`:
if False:
    print("This won't be printed")


# 2. `None`:

value = None
if not value:
    print("value is None")


# 3. `0`:

number = 0
if not number:
    print("number is zero")


# 4. 空序列和空集合:

empty_list = []
if not empty_list:
    print("empty_list is empty")

empty_string = ''
if not empty_string:
    print("empty_string is empty")

empty_tuple = ()
if not empty_tuple:
    print("empty_tuple is empty")

empty_dict = {}
if not empty_dict:
    print("empty_dict is empty")

empty_set = set()
if not empty_set:
    print("empty_set is empty")


# 5. 其他“空”对象:

class EmptyClass:
    pass

empty_instance = EmptyClass()
if not empty_instance:
    print("empty_instance is empty")
value is None
number is zero
empty_list is empty
empty_string is empty
empty_tuple is empty
empty_dict is empty
empty_set is empty