Author: SUNNY BHAVEEN CHANDRA
For more information -
[1] Python notes- https://c17hawke.github.io/Python/
[2] Python YouTube Playlist- https://youtube.com/playlist?list=PLrdaCCBhU_hnxIzB7EJlY-pfYOMGRycAK
Variables 🔤¶
- In programming languages, a variable is a name used to identify a value.
- Developers use variables to make their code more readable and understandable, like using names in natural language.
- Technically speaking, variables in Python are values that can change during the execution of a program.
- A variable is used to store a value that may change as needed.
- In Python, there is no need to explicitly declare a variable. As soon as you assign a value to it, the variable is considered declared.
Define a Variable 🔍-¶
In Python, a variable is defined by assigning a value to it. Unlike some other programming languages, there is no need to declare a variable before assigning a value to it.
In [1]:
Copied!
# let x be 100
x = 100
print(x)
# let x be 100
x = 100
print(x)
100
In [2]:
Copied!
x = 5
print("Twice of a num", x * 2)
x = 5
print("Twice of a num", x * 2)
Twice of a num 10
In [3]:
Copied!
lecture = "Introduction to python"
print("This is a lecture of:", lecture)
lecture = "Introduction to python"
print("This is a lecture of:", lecture)
This is a lecture of: Introduction to python
NOTE: f-string way to write above statement - (Most frequently used)
In [4]:
Copied!
print(f"This is a lecture of: {lecture}") # do not forget f in the beginning
print(f"This is a lecture of: {lecture}") # do not forget f in the beginning
This is a lecture of: Introduction to python
In [5]:
Copied!
name = "Sunny"
print(f"My name is: {name}")
age = 52
print(f"My age is: {age}")
print(f"My name is {name} and My age is {age} years")
name = "Sunny"
print(f"My name is: {name}")
age = 52
print(f"My age is: {age}")
print(f"My name is {name} and My age is {age} years")
My name is: Sunny My age is: 52 My name is Sunny and My age is 52 years
In [6]:
Copied!
# write a table of a no. upto 10
x = 5
print(f"showing table of: {x}")
print(f"{x} x 1 = {x * 1}")
print(f"{x} x 2 = {x * 2}")
print(f"{x} x 3 = {x * 3}")
print(f"{x} x 4 = {x * 4}")
print(f"{x} x 5 = {x * 5}")
print(f"{x} x 6 = {x * 6}")
print(f"{x} x 7 = {x * 7}")
print(f"{x} x 8 = {x * 8}")
print(f"{x} x 9 = {x * 9}")
print(f"{x} x 10 = {x * 10}")
# write a table of a no. upto 10
x = 5
print(f"showing table of: {x}")
print(f"{x} x 1 = {x * 1}")
print(f"{x} x 2 = {x * 2}")
print(f"{x} x 3 = {x * 3}")
print(f"{x} x 4 = {x * 4}")
print(f"{x} x 5 = {x * 5}")
print(f"{x} x 6 = {x * 6}")
print(f"{x} x 7 = {x * 7}")
print(f"{x} x 8 = {x * 8}")
print(f"{x} x 9 = {x * 9}")
print(f"{x} x 10 = {x * 10}")
showing table of: 5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
Rules for defining the variables in Python 📏-¶
- Variable names can contain letters, numbers, and underscores only (A-Z, a-z, 0-9, and _ ), but cannot start with a number.
In [7]:
Copied!
# Correct variable names as per above rule
my_variable = 10
my_variable_1 = 20
MyVariable_1 = 20
_variable = 200
# Correct variable names as per above rule
my_variable = 10
my_variable_1 = 20
MyVariable_1 = 20
_variable = 200
In [8]:
Copied!
# against the rule above
1_variable = 100 # This will raise a SyntaxError
# against the rule above
1_variable = 100 # This will raise a SyntaxError
Cell In[8], line 2 1_variable = 100 # This will raise a SyntaxError ^ SyntaxError: invalid decimal literal
In [9]:
Copied!
my_variable_@ = 20 # This will raise a SyntaxError
my_variable_@ = 20 # This will raise a SyntaxError
Cell In[9], line 1 my_variable_@ = 20 # This will raise a SyntaxError ^ SyntaxError: invalid syntax
- Variable names are case-sensitive.
In [10]:
Copied!
# These are two different variables
my_variable = 10
my_Variable = 20
print(my_variable)
print(my_Variable)
# These are two different variables
my_variable = 10
my_Variable = 20
print(my_variable)
print(my_Variable)
10 20
- Variable names cannot be the same as Python keywords or inbuilt function.
NOTE: Think of keywords as a vocabulary of python language.
In [11]:
Copied!
# You can check the list of Python keywords using the keyword module
import keyword
print(keyword.kwlist)
# You can check the list of Python keywords using the keyword module
import keyword
print(keyword.kwlist)
['False', 'None', 'True', '__peg_parser__', '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']
In [12]:
Copied!
# to print the builtins present in python
import builtins
print(dir(builtins))
# to print the builtins present in python
import builtins
print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
In [13]:
Copied!
# against the above rule
print = 12
print(print) # type error
# against the above rule
print = 12
print(print) # type error
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[13], line 3 1 # against the above rule 2 print = 12 ----> 3 print(print) # type error TypeError: 'int' object is not callable
In [14]:
Copied!
# Invalid variable name
for = 10 # This will raise a SyntaxError
# Invalid variable name
for = 10 # This will raise a SyntaxError
Cell In[14], line 2 for = 10 # This will raise a SyntaxError ^ SyntaxError: invalid syntax
In [15]:
Copied!
# ! WARNING: Only use in Jupyter notebooks -
del print # deleting the instance of print in jupyter notebook only
# ! WARNING: Only use in Jupyter notebooks -
del print # deleting the instance of print in jupyter notebook only
In [16]:
Copied!
p = 10
print(p) # Now it works
p = 10
print(p) # Now it works
10
Conventions 📝¶
- following is an example of declaring a hidden variable
In [17]:
Copied!
_variable = 200 # it gets grayed out as by some IDEs
_variable = 200 # it gets grayed out as by some IDEs
- Generally names of variables should start with small letters
In [18]:
Copied!
variable = 200
x_val = 100
variable = 200
x_val = 100
- Name of constants or the values that you do not wish to change in the program are constants
In [19]:
Copied!
PI = 3.14
radius = 3
area_of_circle = PI * radius * radius
# area_of_circle = PI * radius ** 2 # same as above
print(f"Area of circle with radius: {radius} is {area_of_circle} unit-square")
PI = 3.14
radius = 3
area_of_circle = PI * radius * radius
# area_of_circle = PI * radius ** 2 # same as above
print(f"Area of circle with radius: {radius} is {area_of_circle} unit-square")
Area of circle with radius: 3 is 28.259999999999998 unit-square
Features 🔍¶
- There is no need to declare a variable before assigning a value to it.
example in other languages like C or C++
int x = 2;
In [20]:
Copied!
# You can directly assign a value to a variable
x = 2
y = "sample text"
# You can directly assign a value to a variable
x = 2
y = "sample text"
In [21]:
Copied!
# advance - TYPE hinting
x: int = 2
y: str = "example text"
# advance - TYPE hinting
x: int = 2
y: str = "example text"
- You can assign values to multiple variables in one line.
In [22]:
Copied!
x, y, z = 10, 20, 30
print(x, y, z)
# This is equivalent to:
x = 10
y = 20
z = 30
print(x, y, z)
x, y, z = 10, 20, 30
print(x, y, z)
# This is equivalent to:
x = 10
y = 20
z = 30
print(x, y, z)
10 20 30 10 20 30
More real world examples 🌎¶
In [23]:
Copied!
length = 10
width = 20
area_of_rectangle = length * width
perimeter = 2 * (length + width)
print(f"for rectangle with length: {length} and width: {width}")
print(f"area of rectangle = {area_of_rectangle}")
print(f"Perimeter of rectangle = {perimeter}")
length = 10
width = 20
area_of_rectangle = length * width
perimeter = 2 * (length + width)
print(f"for rectangle with length: {length} and width: {width}")
print(f"area of rectangle = {area_of_rectangle}")
print(f"Perimeter of rectangle = {perimeter}")
for rectangle with length: 10 and width: 20 area of rectangle = 200 Perimeter of rectangle = 60
In [24]:
Copied!
# More real world examples -
cost_of_shirt = 600
units_to_purchase = 3
amount_payable = cost_of_shirt * units_to_purchase
print(f"Cost of 1 shirt: {cost_of_shirt}")
print(f"Units to purchase: {units_to_purchase}")
print(f"Amount payable (in INR): {amount_payable}")
# More real world examples -
cost_of_shirt = 600
units_to_purchase = 3
amount_payable = cost_of_shirt * units_to_purchase
print(f"Cost of 1 shirt: {cost_of_shirt}")
print(f"Units to purchase: {units_to_purchase}")
print(f"Amount payable (in INR): {amount_payable}")
Cost of 1 shirt: 600 Units to purchase: 3 Amount payable (in INR): 1800