Variables are used to store data in computer memory
type()
functionid()
functionVariables: While working with a programming language such as Python, information is stored in variables. You can think of variables as containers for storing data. The data stored within a variable is called its value.
name_of_instructor = "Arif Butt"
name_of_instructor
type(name_of_instructor)
str
no_of_lectures = [32.5, 66]
no_of_lectures
typeq
list
Tab
key to autocomplete the variable's name. Try typing nam
in a code cell below and press Tab
to autocomplete to name_of_instructor
.Dot
, then press Tab
to get a list of all the attributes and methods of that objectIn programming languages, identifiers are names used to identify a variable, function, or other entities in a program. Variable names can be short (a
, x
, y
, etc.) or descriptive ( my_favorite_color
, profit_margin
, the_3_musketeers
, etc.). However, you must follow these rules while naming Python variables:
_
. It cannot begin with a number.a
-z
, A
-Z
, 0
-9
, and _
).a_variable
, A_Variable
, and A_VARIABLE
are all different variables.Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. A reserved keyword may not be used as an identifier. Here is a list of the Python keywords.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help('keyword')
in the cell belowhelp('True')
Help on bool object: class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | self != 0 | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __format__(self, format_spec, /) | Default object formatter. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __round__(...) | Rounding an Integral returns itself. | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | as_integer_ratio(self, /) | Return integer ratio. | | Return a pair of integers, whose ratio is exactly equal to the original int | and with a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | to_bytes(self, /, length, byteorder, *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from int: | | from_bytes(bytes, byteorder, *, signed=False) from builtins.type | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number
# True is a keyword, can't be used as variable name
#True = 100
# A variable name cannot start with a special character or digit
var1 = 25
#1var = 530
#@i = 980
a = range(10)
type(a)
#Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"
print ('a = ',a,' b = ',b,' c = ',c)
# to check the type of variable
name = "Arif Butt"
print("name is of ", type(name))
x = 234
print("x is of ", type(x))
y = 5.321
print("y is of ", type(y))
name is of <class 'str'> x is of <class 'int'> y is of <class 'float'>
id()
function returns the identity of an objectx = 234
y = 5.321
id(x), id(y)
(4447430624, 140474726550384)
a = 10
b = 10
id(a), id(b)
(4447423456, 4447423456)
- Both the variables
a
andb
have same ID, i.e., both a and b are pointing to same memory location.- Variables in Python are not actual objects, rather are references to objects that are present in memory.
- So both the variables a and b are refering to same object 10 in memory and thus having the same ID.
var1 = "Data Science"
id(var1)
140474713366768
var1 = "Arif Butt"
id(var1)
140474713404016
Note that the string object "Data Science" has become an orphaned object, as no variable is refering to it now. This is because the reference
var1
is now pointing/referring to a new object "Arif Butt". All orphan objects are reaped by Python garbage collector.
dir()
, and del
Keyword¶dir()
function, when called without an argument, return the names in the current scope.print(dir())
['In', 'Out', '_', '_1', '_10', '_2', '_3', '_4', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'b', 'exit', 'get_ipython', 'name', 'name_of_instructor', 'no_of_lectures', 'quit', 'var1', 'x', 'y']
newvar = 10
print("newvar=", newvar)
newvar= 10
print(dir())
['In', 'Out', '_', '_1', '_10', '_2', '_3', '_4', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'b', 'exit', 'get_ipython', 'name', 'name_of_instructor', 'newvar', 'no_of_lectures', 'quit', 'var1', 'x', 'y']
del var1
print(dir())
['In', 'Out', '_', '_1', '_10', '_2', '_3', '_4', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'b', 'exit', 'get_ipython', 'name', 'name_of_instructor', 'newvar', 'no_of_lectures', 'quit', 'x', 'y']
var1
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_27018/2376987541.py in <module> ----> 1 var1 NameError: name 'var1' is not defined
import math
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Try answering the following questions to test your understanding of the topics covered in this notebook:
a_variable
, A_Variable
, and A_VARIABLE
represent the same variable or different ones?