01.basics Understanding and Data Types, Variables & Operators - Jupyter Notebook
01.basics Understanding and Data Types, Variables & Operators - Jupyter Notebook
6. Functions
1. Function with arguments In Python
2. All builtin functions
3. Lambda Functions(map, filter & reduce)
7. Object-Oriented Approach
1. Class, Object & Method.
2. Inheritance in python
3. Polymorphism in python
4. Encapsulation in python
5. Data Abstraction in python
6. Data Hiding & Object Printing
7. Constructors Destructors in Python
8. Garbage Collection in Python
8. Exception Handling
1. Python Exception Handling
2. User-defined Exception
3. Built-in Exception
4. Python Try Except
What is programming...?
Programming is a way for us to tell computers what to do. Computer is a very dumb machine
and it only does what we tell it to do. Hence, we learn programming and tell computers to do
what we are very slow at - computation. If I ask you to calculate 5+6, you will immediately say
11. How about 23453453 X 56456?
What is Python?
Features of Python
What is IDE..?
Hello World
Comments :
A comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execution of a specific part
of code while testing.
Single-Line Comments:
Example - 1 :
In [2]: 1 # this is comment so this will note execute
2 print("This is actual code")
Example - 2 :
In [5]: 1 print("This is actual code")# this is comment so this will note execute
Example - 3 :
Multi-Line Comments:
To write multi-line comments you can use ‘#’ at each line or you can use the multiline string.
p is greater than 5.
p is greater than 5.
Escape Sequences :
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
Input In [24]
txt = "Ramu is the Number "ONE" Person in the world"
^
SyntaxError: invalid syntax
\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
It's ok
In [29]: 1 txt = "This will insert one \\ (backslash)."
2 print(txt)
Print Statement :
The syntax of a print statement looks something like this:
print(object(s), sep=separator, end=end, file=file, flush=flush)
1. object(s): Any object, and as many as you like. Will be converted to string before printed
2. sep='separator': Specify how to separate the objects, if there is more than one. Default is
''
3. end='end': Specify what to print at the end. Default is '\n' (line feed)
4. file: An object with a write method. Default is sys.stdout
Parameters 2 to 4 are optional
In [33]: 1 print("Python")
Python
Rakesh 45 67
END Argument
1
2
3
4
In [36]: 1 # we can use end to make then one line with space seperation
2 for i in range(1,5):
3 print(i,end=" ")
1 2 3 4
1 % 2 % 3 % 4 %
SEP Argument
In [39]: 1 #sep argument is used to seperate the elements with in print function
2 print("rakesh",a,67,sep=" --> ")
In [3]: 1 print(1,2,3,4,end="-->")
1 2 3 4-->
In [5]: 1 print(1,2,3,4,sep="-->")
1-->2-->3-->4
0-->1-->2-->3-->4-->
0
1
2
3
4
In [8]: 1 for i in range(5):
2 print(i,i+1,sep="-->")
0-->1
1-->2
2-->3
3-->4
4-->5
In [41]: 1 f = open("sample.txt","w")
2 for i in [1,2,3,4]:
3 print(i,file=f)
4 f.close()
Flush:
The flush parameter in Python's print function controls whether the output is immediately
flushed or buffered. By default, the print() function buffers the output, which means that it may
not be immediately displayed on the screen or written to a file. However, you can force the
output to be flushed immediately by setting the flush parameter to True.
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
In [2]: 1 a = "Python"
2 b = 200
Variables do not need to be declared with any particular type, and can even change variable
type after they have been set.
In [3]: 1 a = 100 # This is int type
2 b = "Python" # this is STR type
3 print(a,b)
100 Python
Example
In [5]: 1 x = 5
2 y = "John"
3 print(type(x))
4 print(type(y))
<class 'int'>
<class 'str'>
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
<class 'str'>
<class 'int'>
<class 'float'>
Example
In [8]: 1 a = "John"
2 # is the same as
3 b = 'John'
4 print(a)
5 print(b)
John
John
Case-Sensitive
Variable names are case-sensitive.
In [9]: 1 a = 4
2 A = "Sally"
3 #A will not overwrite a
4 print(a)
5 print(A)
4
Sally
Input In [1]
2Variable = 56
^
SyntaxError: invalid syntax
In [3]: 1 Variable@ = 45
Input In [3]
Variable@ = 45
^
SyntaxError: invalid syntax
Input In [2]
variable name =87
^
SyntaxError: invalid syntax
In [12]: 1 def1 = 10
2 def = 10
Input In [12]
def = 10
^
SyntaxError: invalid syntax
In [10]: 1 class = 10
Input In [10]
class = 10
^
SyntaxError: invalid syntax
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
Snake Case
Each word is separated by an underscore character:
Pascal Case
Each word starts with a capital letter:
10 20 30
Note: Make sure the number of variables matches the number of values, or else you will get
an error.
In [32]: 1 a,b = 10,20,30
2 print(a,b,c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [32], in <cell line: 1>()
----> 1 a,b = 10,20,30
2 print(a,b,c)
In [34]: 1 a = b = c = 34
2 print(a,b,c)
34 34 34
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
1 2 3
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [36], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y = lst
3 print(x,y)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [37], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y,z,xy = lst
3 print(x,y)
Output Variables
The Python print() function is often used to output variables.
Python is easy
In [39]: 1 a = "Python"
2 b = "is"
3 c = "easy"
4 print(a, b, c)
Python is easy
Python is easy
Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
30
In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:
In [42]: 1 a = 40
2 b = "Python"
3 print(a+b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [42], in <cell line: 3>()
1 a = 40
2 b = "Python"
----> 3 print(a+b)
The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:
In [43]: 1 a = 20
2 b = 30.07
3 c = 34+8j
4 d = "Python"
5 print(a,b,c,d)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.
Global variables can be used by everyone, both inside of functions and outside.
In [64]: 1 a = 10
2 def Sample():
3 print(a+20)
4 Sample()
30
If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as it
was, global and with the original value.
In [3]: 1 a = 10
2 def Sample():
3 a = "Python is king"
4 print(a)
5 Sample()
6 print(a)
Python is king
10
Let's see this way. in local variable if we try to access global variable before creat it.
In [5]: 1 a = 10
2 def Sample():
3 print(a)
4 a = "Python is king"
5 print(a)
6 print(a)
7 Sample()
10
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Input In [5], in <cell line: 7>()
5 print(a)
6 print(a)
----> 7 Sample()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [69], in <cell line: 5>()
3 Var = "This is local keyword"
4 Sample()
----> 5 print(Var)
Also, use the global keyword if you want to change a global variable inside a function.
To change the value of a global variable inside a function, refer to the variable by using the
global keyword:
In [76]: 1 x = 5222
2 print(type(x))
<class 'int'>
1
<class 'int'>
2
<class 'int'>
3
<class 'int'>
False
False
False
False
False
False
False
False
False
In [52]: 1 print(bool(1))
2 print(bool("Python"))
3 print(bool(2.8))
4 print(bool([1,2,4]))
5 print(bool(23+56j))
True
True
True
True
True
1.0
<class 'float'>
2.8
<class 'float'>
3.0
<class 'float'>
In [56]: 1 print(float(complex(34,45j)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [56], in <cell line: 1>()
----> 1 print(float(complex(34,45j)))
In [57]: 1 print(float([1,2,4]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [57], in <cell line: 1>()
----> 1 print(float([1,2,4]))
s1
<class 'str'>
2
<class 'str'>
3.0
<class 'str'>
In [62]: 1 print(str([1,2,4]))
2 print(type(str([1,2,4])))
[1, 2, 4]
<class 'str'>
In [64]: 1 print(str((1,2,4,5)))
2 print(type(str((1,2,4,5))))
(1, 2, 4, 5)
<class 'str'>
05. list() ==> It is used to convert any data type to a list type.
In [65]: 1 print(list(34))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [65], in <cell line: 1>()
----> 1 print(list(34))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [66], in <cell line: 1>()
----> 1 print(list(34.7))
In [74]: 1 print(list(True))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [74], in <cell line: 1>()
----> 1 print(list(True))
In [90]: 1 print(list("3445"))
2 print(list("Python"))
3 print(list((1,2,4,5)))
4 print(list({1:2,3:4}))
5 print(list({1,2,2,3,3,4,5}))
In [89]: 1 print(tuple("3445"))
2 print(tuple("Python"))
3 print(tuple([1,2,4,5]))
4 print(tuple({1:2,3:4}))
5 print(tuple({1,2,2,3,3,4,5}))
In [92]: 1 print(set("3445"))
2 print(set("Python"))
3 print(set([1,2,4,5]))
4 print(set({1:2,3:4}))
5 print(set((1,2,2,3,3,4,5)))
{1: 2, 2: 3, 3: 4}
{1: 2, 2: 3, 3: 4}
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [99], in <cell line: 2>()
1 #list of list with more then 2 elements
----> 2 print(dict([[1,2,5],[2,3],[3,4]]))
{1: 2, 2: 3, 3: 4}
{1: 2, 2: 3, 3: 4}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [103], in <cell line: 2>()
1 # set of sets
----> 2 print(dict({{1,2},{1,3},{3,4}}))
In [106]: 1 print(ord("a"))
2 print(ord("A"))
97
65
In [109]: 1 print(chr(97))
2 print(chr(65))
a
A
11.complex ==> This function converts real numbers to complex
number
In [111]: 1 a=1
2 print(type(a))
3 print(a)
4 b=complex(a)
5 print(type(b))
6 print(b)
<class 'int'>
1
<class 'complex'>
(1+0j)
In [113]: 1 a=complex(1,2)
2 b=complex(2,3)
3 c=a+b;print(c)
4 d=a-b;print(d)
(3+5j)
(-1-1j)
In [119]: 1 print(complex(20))
2 print(complex(10.5))
3 print(complex(True))
4 print(complex(False))
5 print(complex("10"))
6 print(complex("10.5"))
7 print(complex(1,-2))
8 print(complex(1,-0))
(20+0j)
(10.5+0j)
(1+0j)
0j
(10+0j)
(10.5+0j)
(1-2j)
(1+0j)
In [121]: 1 print(complex(True,True))
2 print(complex(True,False))
3 print(complex(False,False))
4 print(complex(False,True))
(1+1j)
(1+0j)
0j
1j
1.7 All about Operators..?.?
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic
operations. In this article, we will look into different types of Python operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
7. Ternary Operator
8. Bitwise Operators
% Modulus: returns the remainder when the first operand is divided by the second x%y
Addition of 10 and 2 is 12
Subtraction of 10 and 2 is 8
Multiplication of 10 and 2 is 20
float Division of 10 and 2 is 5.0
floor Division of 10 and 2 is 5
Modulus of 10 and 2 is 0
Power of 10 and 2 is 100
Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number
or number at the left is divided by the second number or number at the right and returns the
quotient.
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:
1.0
5.0
-5.0
10.0
The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
In [37]: 1 print(10//3) #3
2 print (-3//2) #-2
3 print (5.0//2) #2
4 print (-5.0//2) #-2
5 print(7//3) #3
6 print(7/3) #3
3
-2
2.0
-3.0
2
2.3333333333333335
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits
4
34
234
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
>= Greater than or equal to : True if the left operand is greater than or equal to the right x >= y
<= Less than or equal to : True if the left operand is less than or equal to the right x <= y
In python, the comparison operators have lower precedence than the arithmetic operators. All
False
True
False
True
False
True
and Logical AND: True if both the operands are true x and y
1. Logical not
2. logical and
3. logical or
False
True
False
True
False
In [59]: 1 x = 24
2 y = 20
3 list = [10, 20, 30, 40, 50]
4
5 if (x not in list):
6 print("x is NOT present in given list")
7 else:
8 print("x is present in given list")
9 if (y in list):
10 print("y is present in given list")
11 else:
12 print("y is NOT present in given list")
In [65]: 1 x = 10
2 y = 10
3 z = x
4 print(x is y)
5 print(x is z)
6 print(x is not y)
7 print(id(x))
8 print(id(y))
9 print(id(z))
True
True
False
2770717928016
2770717928016
2770717928016
[1, 2, 3]
True
True
[1, 2, 3]
False
True
It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.
In [63]: 1 x = 10
2 y = 20
3 min1 = x if x<y else y
4 print(min1)
10
| Bitwise OR x|y
~ Bitwise NOT ~x
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
0
14
-11
14
2
40
0 0 0
0 1 0
1 0 0
1 1 1
Example:
a=10;b=20
ANALYSIS
In [23]: 1 a=10;b=20
2 print(bin(a))
3 print(bin(b))
0b1010
0b10100
In [24]: 1 print(a&b)
bitwise OR ( | )
It takes two bit patterns of equal length.
The result in each position is 0 if both bits are 0,
while otherwise the result is 1 (Any One 1 the Result is 1)
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
Example :
a = 9;b = 65
ANALYSIS
We declared 2 integers a and b, The binary form of
09 = 00001001 ==> for 1 Byte ==> 8 bits
65 = 01000001 ==> for 1 Byte ==> 8 bits
00001001 & 01000001 01001001 R l i 3
In [25]: 1 a = 9
2 b = 65
3 print(bin(a))
4 print(bin(b))
5 print(0b01001001)
0b1001
0b1000001
73
In [22]: 1 print(a|b)
73
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
Example:
a = 9;b = 65
ANALYSIS
In [29]: 1 print(bin(9))
2 print(bin(65))
3 print(0b01001000)
0b1001
0b1000001
72
Bitwise complement ( ~ ) :
a = 10 # 10=1010
a << 2; # 40=101000==>Add Two digits right side
a = 10 #10=1010
a >> 2; #2=10==>Remove two digits right side
a<b<c
In Python, there is a better way to write this using the Comparison operator Chaining. The
chaining of operators can be written as follows:
if a < b < c :
{.....}
According to associativity and precedence in Python, all comparison operations in Python have
the same priority, which is lower than that of any arithmetic, shifting, or bitwise operation. Also
unlike C, expressions like a < b < c have an interpretation that is conventional in mathematics.
List of comparison operators in Python:
In [10]: 1 a = 200
2 b = 300
3 c = 40
4
5 if a>b and a>c:
6 print(a)
7 elif b>a and b>c:
8 print(b)
9 elif c>a and c>b:
10 print(c)
300
In [11]: 1 if b<a>c:
2 print(a)
3 elif a<b>c:
4 print(b)
5 elif a<c>b:
6 print(c)
7 else:
8 print("Nothing to do")
300
1) Using %
2) Using {}
Using %:
The formatting using % is similar to that of ‘printf’ in C programming language.
%d ==> integer
%f ==> float
%s ==> string
%x ==> hexadecimal
%o ==> octal
Syntax:
Using {}:
We can format strings with variable values by using replacement operator {} and format()
method.
Syntax:
{} .format(value)