DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Variable assignment in Python

Buy Me a Coffee

*Memo:

A value can be assigned to a variable as shown below:

v = 5

print(v)
# 5

v = 10

print(v)
# 10 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
PI = 3.14
MAX_VALUE = 100
MAX_VALUE_ = 200
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)