*Memos:
- My post explains iterable unpacking in variable assignment.
-
My post explains
*
for iterable unpacking in variable assignment. -
My post explains
[]
and()
for variables in variable assignment. -
My post explains
[]
and()
for variables infor
statement. - My post explains shallow copy and deep copy.
You can assign a value to a variable as shown below:
v = 5
print(v) # 5
v = 10
print(v) # 10
You can assign a value 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
You can shorten the operation code as shown below:
v = 3
# Equivalent
v += 5 # v = v + 5
print(v) # 8
The name of a variable:
- can have letters(uppercase and lowercase), numbers and
_
. - cannot start with a number.
- cannot be a reserved word such as
True
,class
,def
, etc.
True_100 = 'abc'
tRuE_100 = 'abc'
_True100 = 'abc'
True100_ = '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 lowercase with _
(snake case) and uppercase with _
respectively as shown below. *_
is used to separate words(word_word
) or prevent conflicts between identifiers with a trailing underscore(something_
):
first_name = 'John'
v1 = 3
v_1 = 5
v1_ = 5
PI = 3.14
MAX_VALUE = 100
MAX_VALUE_ = 200
You can use a del statement to remove a variable itself as shown below:
v = 'Hello'
print(v) # Hello
del v
print(v) # NameError: name 'v' is not defined
You can access and change a string as shown below:
*str
type cannot be modified by accessing each character so use list() and join() to do that.
v = "Orange"
print(v, v[0], v[1], v[2], v[3], v[4], v[5]) # Orange O r a n g e
v = "Lemon"
print(v, v[0], v[1], v[2], v[3], v[4]) # Lemon L e m o n
v[2] = "M" # TypeError: 'str' object does not support item assignment
v = list(v) # Change `str` type to `list` type.
print(v, v[0], v[1], v[2], v[3], v[4]) # ['L', 'e', 'm', 'o', 'n'] L e m o n
v[2] = "M"
print(v, v[0], v[1], v[2], v[3], v[4]) # ['L', 'e', 'M', 'o', 'n'] L e M o n
v = ''.join(v) # Change `list` type to `str` type.
print(v, v[0], v[1], v[2], v[3], v[4]) # LeMon L e M o n
Top comments (0)