*Memo:
- My post explains the unpacking with an assignment statement (1).
- My post explains a global statement and nonlocal statement.
- My post explains an identifier.
- My post explains naming convention.
- My post explains a function (1).
A value can be assigned to a variable as shown below:
v = 5 print(v) # 5 v = 10 print(v) # 10
A value can be assigned to one or more variables at once as shown below:
# Equivalent v1 = v2 = v3 = 5 # v1 = 5 # v2 = v1 # v3 = v2 print(v1, v2, v3) # 5, 5, 5 v2 = 10 print(v1, v2, v3) # 5, 10, 5
The calculation code can be shortened as shown below:
v = 7 # Equivalent v += 9 # v = v + 9 print(v) # 16 # Equivalent v -= 2 # v = v - 2 print(v) # 14 # Equivalent v *= 10 # v = v * 10 print(v) # 140 # Equivalent v /= 3 # v = v / 3 print(v) # 46.666666666666664 # Equivalent v //= 6 # v = v // 6 print(v) # 7.0 # Equivalent v %= 4 # v = v % 4 print(v) # 3.0
A del statement can be used to remove one or more variables themselves as shown below:
v1 = 'Hello' v2 = 'World' print(v1, v2) # Hello World del v1, v2 print(v1) # NameError: name 'v1' is not defined print(v2) # NameError: name 'v2' is not defined
The name of a variable:
- can have letters,
_
and the digits except for the 1st character. - can be a reserved soft keyword.
- cannot start with a digit.
- cannot be a reserved keyword.
True_100 = 'abc' tRuE_100 = 'abc' _True100 = 'abc' True100_ = 'abc' match = 'abc' case = 'abc' type = 'abc' _ = 'abc' # No error True-100 = 'abc' 100_True = 'abc' True = 'abc' class = 'abc' def = 'abc' # Error
The naming convention for a variable and constant is lower_snake_case and UPPER_SNAKE_CASE respectively as shown below:
var = 'abc' my_var = 'abc' my_first_var = 'abc'
PI = 3.141592653589793 E = 2.718281828459045 MIN_NUM = 0 MAX_NUM = 100 MY_MIN_NUM = 0 MY_MAX_NUM = 100
The variable with a single trailing underscore(abc_
) can be used to prevent identifier conflicts when using the identifiers which already exist as shown below:
var_ = 'ok' VAR_ = 'ok' func_ = 'ok' len_ = 'ok' list_ = 'ok' int_ = 'ok' True_ = 'ok' def_ = 'ok' class_ = 'ok'
Top comments (0)