Variables in Python
In [ ]: - Variables are used to store values in python
- use the assignment operator (=) to store a value in a variable
example :
a = 10
num1 = 23
In [ ]: a + b
a - b
In [1]: a = 10
print(a)
10
In [2]: print(a)
10
In [3]: a = 100
print(a)
100
In [4]: print(a)
100
Rules for Naming Variables in Python
In [ ]: 1. A variable name must be start with a letters (a-z, A-Z) or an underscore (_)
2. A variable name can include letters (a-z, A-Z) , digits (0-9) and an undersco
i.e alphanumeric with underscore
3. spaces are not allowed in variable names
4. Variable names are case sensitive
5. Variable names cannot be any of python's reserved keywords (35)
reserved keywords are
'False','None','True','and','as','assert','async','await','break','class',
'continue','def','del','elif','else','except','finally','for','from','global',
'if','import','in','is','lambda','nonlocal','not','or',
'pass','raise','return','try','while','with','yield'
6. It's best to avoid using built-in function names (161)
print, sum, min, max
7. Special characters (except (_)) are not allowed
In [22]: "velocity" in dir(builtins)
Out[22]: False
In [24]: "float" in dir(builtins)
Out[24]: True
In [23]: import builtins
print(len(dir(builtins)))
print(dir(builtins))
161
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExc
eptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarnin
g', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'Connection
RefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsi
s', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'Fals
e', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarnin
g', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationErro
r', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardI
nterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'Non
e', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'Ov
erflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupErro
r', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'Runti
meWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarnin
g', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warnin
g', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__deb
ug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec_
_', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint',
'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'co
pyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate',
'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipytho
n', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'm
ax', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 's
lice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']
In [16]: import keyword
len([Link])
Out[16]: 35
In [ ]: True / False
not
and
or
con
In [11]: _num12344$ = 10
print(_num12344$)
Cell In[11], line 1
_num12344$ = 10
^
SyntaxError: invalid syntax
In [10]: _num12344 = 10
print(_num12344)
10
In [6]: _ = 10
print(_)
10
In [7]: num1 = 19
print(num1)
19
In [8]: _num1 = 190
print(_num1)
190
In [9]: 1num = 10
print(1num)
Cell In[9], line 1
1num = 10
^
SyntaxError: invalid decimal literal
Types of Variable Assignment in Python
In [ ]: 1. single value to single variable:
a = 23
2. multiple values to multiple variables
a,b,c = 2,3,4
3. same value to multiple variables
a = b = c = 10
4. multiple values with comma seperated to single variable then datatype of that
In [26]: a = b = c = 101
print(a)
print(b)
print(c)
101
101
101
In [27]: a = 100
print(a)
100
In [28]: a
Out[28]: 100
In [29]: a
Out[29]: 100
In [30]: a
Out[30]: 100
In [32]: a
Out[32]: 100
del keyword
In [ ]: the del keyword is used to delete variables from memory
- Once deleted, the variable can no longer be used
example :
a = 10
del a
print(a) # NameError: name 'a' is not defined
In [33]: del a
In [34]: print(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[34], line 1
----> 1 print(a)
NameError: name 'a' is not defined
In [35]: a = 2,3,4,5,6,7,8,9
print(a)
(2, 3, 4)
In [36]: type(a)
Out[36]: tuple
In [41]: a = 2,3,4,5,6
print(a)
type(a)
(2, 3, 4, 5, 6)
Out[41]: tuple
In [42]: b = (2,3,4,5,6)
print(b)
type(b) #
(2, 3, 4, 5, 6)
Out[42]: tuple
In [46]: a = 24646,464664
type(a)
Out[46]: tuple
In [45]: a = 24646464664
type(a)
Out[45]: int
In [43]: a = 2
type(a)
Out[43]: int
In [47]: a = 2,
print(a)
type(a)
(2,)
Out[47]: tuple
In [ ]:
In [38]: a = [2,3,4,5,6]
type(a)
Out[38]: list
In [39]: a = {2,3,4,5,6}
type(a)
Out[39]: set
In [ ]: a = 10 # valid
1a = 10 # invalid
a3 = 10 # valid
a3# = 10 # invalid
= = 120 # invalid
__a = 10 # valid
100 = 100 # invalid
a100 = 12 # valid
In [49]: a100 = 12
print(a100)
12
In [ ]: