Tuesday, December 24, 2019

Command line arguments

argv is not Array it is a list. It is available sys Module 
The argument which are passing at the time of execution are called command line Arguments.

Eg: D:\Python_classes py test.py   10(command) 20(line) 30(arguments)

Within the python program this command line arguments are available in argv. Which is present in SYS module.


Test.py
10
20
30

Note: 
             argv[0]  represents Name of program. But not first command line argument.
             argv[1] represents first command line argument


Program : To check type of argv from sys 

import  argv
print(type(argv))

D:\Python_classes\py test.py

Write a program to display command line arguments 

from sys import argv
print(“The Number of Command Line Arguments:”, len(argv))
print(“The List of Command Line Arguments:”,argv)
print(“Command Line Arguments one by one:”)
for x in argv 
     print(x)

D:\Python_classes>py test.py 10 20 30 
The Number of Command Line Arguments: 4 
The List of Command Line Arguments: [’test.py’, ’10’,’20’,’30’]
Command Line Arguments one by one 
test.py
10
20
30



from sys import argv
sum=0
args=argv[1:]
for x in args :
 n=int(x)
sum=sum+n
print(”The Sum:”,sum)

D:\python_classes>py test.py 10 20 30 40 
The Sum: 100

Note1: Usually space is separator b/w command line arguments. If our command line arguments. If our command line argument itself contains space then we should enclose within double quotes(but not single quotes )

from  sys import argv 
print(argv[1])

D:\Python_classes>py test.py Karthik Bear 
Karthik 

D:\Python_classes>py test.py 'Karthik Bear’
‘Karthik 

D:\Python_classes>py test.py "Karthik Bear"
Karthik Bear 

Note2: within the python program command line arguments are available in the string form. Based on our requirement, we can convert into corresponding type by using type casting methods.

from  sys import argv
print(argv[1]+argv[2])
print(int(argv[1])+int(argv[2]))

D:\Python_classes>py test.py 10 20 
1020
30 

Note3:  If we are trying to access command line arguments with out of range index then we will get error.

  1. from sys import argv
  2. print(argv[100])

D:\Python_classes>py test.py 10 20 
IndexError: list index out of range.

Note : In python there is argparse module to parse command line arguments and display some help messages whenever end user enters  wrong inputs.

Input
raw_input 

Command line arguments 

Output statements 

We can print() function to display output 

Form1 : print() without any argument 
Just in prints new line character

Form2: 

print(String):
print(“Hello World”)
We can use escape characters also 
print(“Hello \n World”)
print(“Hello\tWorld”)
We can use repetition operator (*) in the string
print(10*”Hello”)
print(“Hello”*10)
We can use + operator also 
print(“Hello”+”World”)

Note: 

If both arguments are string type then  + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get error 
If both arguments are number type then + operator acts as arithmetic addition operator 

Note:

print(“Hello”+”World”)
print(“Hello”,”World”)

HelloWorld
Hello World 

Form3: print() with variable number of arguments 

> a,b,c=10,20,30 
> print(a,b,c,sep=‘,’)
> print(a,b,c,sep=‘:’)

D:\Python_classes>py test.py
10,20,30
10:20:30

Form4: print() with end attribute 

print(“Hello”)
print(“Good”)
print(“Morning”)

Output 

Hello 
Good 
Morning 

If we want output in the same line with space.

print(“Hello”,end=‘’)
print(“karthik”,end=‘’)
print(“world”)

output: Hello Karthik World 

Note: The default value for end attribute is \n, which is nothing but new line character.

Form5: print(object) statement

We can pass any object ( like list, tuple, set etc ) as argument to the print() statement

I=[10,20,30,40]
t=(10,20,30,40)
print(I)
Print(t)

Form6: print(String, variable list)

We can use print() statement with string and any number of arguments

s=“karthik”
a=48
s1=“Java”
s2=“Python”
print(“Hello”,s,”Your Age is”,a)
print(“You are teaching”,s1,”and”,s2)

Output 
Hello Karthik Your Age is 48 
You are teaching java and python 

Form-7: print (formatted string)

  1. %I —> int
  2. %d —> int
  3. %f —> float 
  4. %s —> String type 

Syntax: print(“formatted string” %(variable list))

a=10
b=20
c=30
print(“a value is %I” %a)
print(“b value is %d and  c value is %d” %(b,c))

Output

a value is 10
b value is 20 and c value is 30 

Eg2: 

s=“Karthik”
list=[10,20,30,40]
print(“Hello %s….. The list of items are  %s” %(s,list))

Output : 
Hello karthik…. The list of items are  [10,20,30,40]

Form-8: print() with replacement operator {} 

Eg: 

name = “Karthik”
salary = 10000
gf = “Sunny”
print(“Hello {0} your salary is {1} and Your Friend {2} is waiting”.format(name, salary,gf))
print(“Hello {x} your salary is {y} and Your Friend {z} is waiting”.format(x=name, y=salary,z=gf))

Output 

Hello Karthik your salary is 10000 and Your Friend Sunny is waiting 
Hello Karthik your salary is 10000 and Your Friend Sunny is waiting


















Friday, December 20, 2019

Input and output statements

Reading Dynamic input from the keyboard 

In python 2 the following 2 functions are available to read dynamic input from the keyboard 

  1. raw_input() 
  2. input()

raw_input() : This function always read the data from the keyboard in the form of string format. We have to convert that string type to our required type by sung the corresponding type casting methods.

Eg:  k = raw_input(“Enter First Number”) 
       print(type(x))  —> it will always print str  type only for any input type.

input() : input() function can be used to read data directly in our required format. We are not required to perform type casting.

 x = input(“Enter Value”)
type(x)

10 —> int
“Durga” —> str
10.5 —> float 
True —> bool 

Note

But in python3 we have only input() method and raw_input method is not available.
Python3 input() function behaviors exactly same as raw_input  method of python2 . ie. Every input value is treated as str type only 
Raw_input function of python2 is renamed as input() function in python3

>>>>>>> type(input(“Enter Value:”))
Enter value:10
<class  ‘str’>

Enter value:10.5
<class  ‘str’>

Enter value:True
<class  ‘str’>

Write a program to read 2 numbers from the keyboard and print sum 

x=input(“Enter First Number”)
y=input(“Enter Second Number”)
i = int(x)
j = int(y)
print(“The Sum:”, i+j)

Enter First Number: 100
Enter Second Number: 200
The Sum: 300

x=int(input("Enter First Number:”))
y=int(input(“Enter Second Number:”))
print(“The Sum:”,x+y)

Print(“The Sum:”,int(input(“Enter First Number:”))+int(input(“Enter Second Number:”)))

Write a program.to read employee data from the keyboard and print the data 

eno=int(input(“Enter Employee No:”))
ename=input(“Enter Employee Name:”)
esal=float(input(“Enter Employee  Salary:”))
eaddr=input(“Enter Employee Address:”)
married=bool(input(“Employee Married ? [True[False]:”))
print(“Employee No:”,eno)
print("Employee Name:”,ename)
print("Employee Salary:”,esal)
print("Employee Address:”,eaddr)
print(“Employee Married:”,married)

D:\Python_classes>py test.py

Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee  Salary:1000
Enter Employee Address:Mumbai
Employee Married ? [True[False]:True
Please confirm information 

Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee  Salary:1000.0
Enter Employee Address:Mumbai
Employee Married ? :True

How to read multiple values from the keyboard in a single line: 

a,b = [int(x) for x in input(“Enter 2 numbers:”).split()]
print(“Product is:”, a*b)

D:\Python _classes>py test.py
Enter 2 numbers: 10 20 
Product is : 200

Note: split() function can take space as separator by default . But we can pass anything as separator 

Write a program to read 2 float numbers from the keyboard with separator and print their sum ?

a,b,c= [float(x) for x in input(“Enter 3 float numbers :”).split(‘ , ‘)]
print(“The Sum is :”, a+b+c)

D:\Python_classes>py test.py
Enter 2 float numbers: 10.5,20.6,20.1
The Sum is 53.2 

eval(): 
eval function take a string and evaluate the result 

Eg: x=eval(“10+20+30”)
      print(x)
Output 60 

Eg: x=eval(input(“Enter Expression”))
       Enter Expression: 10+2*3/4
Output: 11.5 

Eval() can evaluate the input to list, tuple, set etc based the provided input

Eg: write a program to accept list from the keyboard on the display.

l = eval(input(“Enter List”))
print (type(i))
print(i)



Wednesday, December 18, 2019

python operator cont....

Assignment operators 

We can use assignment operator to assign value to the variable.
Eg: x = 10

We can combine assignment operator with some other operator to form compound assignment operator.

Following is the list of all possible compound assignment operators in python.

+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=

Eg:

x=10
x+=20
print(x) —> 30 

Eg:

x=10
x&=5
Print(x) —> 0

Ternary operator or conditional operator 

Syntax x = firstvalue if condition else secondValue

If condition is True then firstValue will be considered else secondValue will be considered.

Eg: 1 

> a,b=10,20
> x=30 If a<b else 40
> print(x) #30 

Eg2:  read two numbers from the keyboard and print minimum value.

> a=int(input(“Enter First Number:”))
> b=int(input(“Enter Second Number:”))
> min=a if a<b else b
> print(“Minimum Value:”,min)

Output 

Enter First Number :10
Enter Second Number:30
Minimum Value:10

Note: Nesting of Ternary Operator is Possible

Q: Program for Minimum of 3 numbers 

> a=int(input(“Enter First Number:”))
> b=int(input(“Enter Second Number:”))
> c=int(input(“Enter Third Number:”))
> min=a if a<b and a<c else b if b<c else c 
> print(“Minimum Value:”,min)

Q: Program for Maximum of 3 numbers 

> a=int(input(“Enter First Number:”))
> b=int(input(“Enter Second Number:”))
> c=int(input(“Enter Third Number:”))
> min=a if a>b and a>c else b if b>c else c 
> print(“Maximum Value:”,max)

Eg: 

> a=int(input(“Enter First Number:”))
> b=int(input(“Enter Second Number:”))
> print(“Both numbers are equal” if a==b else “First Number is less than second Number” if a<b else  “First Number Greater than Second Number”)

Output 

D; \python_classes>py test.py
Enter First Number:10
Enter Second Number:10
Both numbers are equal 

D; \python_classes>py test.py
Enter First Number:10
Enter Second Number:10
First Number is Less than Second Number 

D; \python_classes>py test.py
Enter First Number:10
Enter Second Number:10
First Number is Greater than Second Number 

Special operator 

Python defines the following 2 special operators 

  1. Identity operators 
  2. Membership operators

Identity operators : 

We can use identity operators for address comparison 
There are 2 identify operators are available :  1) is   2) is not 

> r1 is r2, returns True if both r1 and r2 pointing to the same object.
> r1 is not r2 returns True if both r1 and r2 are not pointing to the same object.

Eg:

> a=10
> b=10
> print(a is b) True
> x=True
> y=True
> print(x is y) True 

Eg: 

> a=“demo”
> b=“demo”
> print(id(a))
> print(id(b))
 > print(a is b)

Eg:

> list1=[“one”,”two”,”three”]
> list2=[“one”,”two”,”three”]
> print(id(list1))
> print(id(list2))
> print(list1 is list2) False
> print(list1 is not list2) True
> print(list1 == list2) True 

Note: we can use is operator for address comparison where as == operator for content comparison.

Membership operator 

We can use membership operators to check whether the given object present in the given collection ( it may be String, List, Set, Tuple OR Dict )

In —> Returns True if the given object present in the specified collection.
not in —> Returns True if the given object not present in the specified location.

Eg:

> x=“hello learning Python is very easy”
> print(‘h’ in x) True
> print(‘d’ in x) False 
> print(‘d’ not in x)  True
> print(‘Python’ in x) True 

Operator precedence 

If multiple operator present then which operator will be evaluated first is decided by operator precedence 

Eg:

> print(3+10*2) —> 23 
> print((3+10)*2) —> 26 

The following list describes operator precedence in Python 

  1. () —> parenthesis
  2. ** —> exponential operator 
  3. ~,-  —> Bitwise complement operator, unary minus operator 
  4. *, /, %, // —> mulitplication, division, modulo, floor division 
  5. +, - —> addition , substraction
  6. << , >> —> left and right shift 
  7. & —> Bitwise And 
  8. ^ - Bitwise X-OR
  9. | —> Bitwise OR
  10. >,>=,<,<=,==,!= —> relational or comparison operators 
  11. =, +=,-=,*= —> assignment operator 
  12. is, is not —> identity operator 
  13. in, not-in —> membership operator 
  14. not —> logical not 
  15. and —> logical and 
  16. or —> logical or

Mathematical functions ( math module ):

A module is collection of functions, variables and classes etc 
Math is a module that contains several functions to perform mathematical operations 
If we want to use any module in python, first we have to import that module
Import math 
Once we import a module then we can call any function of that module.

import math 
print(math.sqrt(16))
print(m.pi)

Output :

4.0
3.14444444

We can create alias name by using as keyword  Import math as m  
Once we create alias name, by using that we can access functions and variables of that module.

We can import a particular member of a module explicitly as follows 

Import math as m
print(m.sqrt(16))
print(m.pi)

We can import a particular member of a module explicitly as follows 

from math import sqrt 
from math import sqrt.pl

If we import a member explicitly then it is not required to use module name while accessing.

from math import sqrt.pi
print(sqrt(16))
print(pi)
print NameError: name (math.pi) ‘math’ is not defined.

Important functions of math module 

  1. celi(x)
  2. floor(x)
  3. pow(x,y)
  4. factorial(x)
  5. trunc(x)
  6. gcd(x,y)
  7. sin(x)
  8. cos(x)
  9. tan(x)

Important variables of math module 

pi3.14
e —> 2.71
inf —> infinity 
nan —> not a number 

Q: write a python program to find area of circle  pi*r**2 

from math import pi
r = 16
print(“Area of Circle is :”,pi*r**2)

Output : Area of Circle: 804.2477193 


Sunday, December 15, 2019

python operators


Operator is a symbol  that performs certain operations
Python provides the following set of operators 

Arthimetic operators 
Relational operator or comparison operators 
Logical operators 
Bitwise operators 
Assignment operators 
Special operators 

Arthimetic operators 

+ —> addition  - ---> subtraction  * —> multiplication  / —> division  % —> modulo operator  // —> floor division operator  

Eg: test.py 

a=10
b=2
print(‘a+b=‘,a+b)
print(‘a-b=',a-b)
print(‘a*b=‘,a*b)
print(‘a/b=‘,a/b)
print(‘a//b=‘,a//b)
print(‘a%b=‘,a%b)
print(‘a**b=‘,a**b)

Output 

Python test.py OR py test.py 

a+b = 12 
a-b = 8
a*b = 20
a/b = 5.0
a//b = 5 
a%b = 0
a**b = 100

a = 10.5
b=2

a+b = 12.5
a-b = 8.5
a*b = 21.5
a/b = 5.25
a//b = 5.0
a%b = 0.5
a**b = 110.25

Eg:

10/2 —> 5.0
10//2 —> 5
10.0/2 —> 5.0
10.0//2 —> 5.0 

Note:

/ operator always performs floating point arithmetic. Hence it will always returns float value.

But floor division  (//) can perform both floating point and integral arithmetic. If arguments are int type then result is int type. If at least one argument is float type then result is float type.

Note : 

We can use +,* operator for str type also.
If we want to use + operator for str type then compulsory both arguments should be str type only otherwise we will get error.

>>> “demo”+10
TypeError: must be str , not int
>>> “demo”+”10”
‘demo10’

If we use * operator for str type then compulsory one argument should be int and other argument should be str type.

2*”demo”
“demo”*2 
2.5*”demo”  —> TypeError: cannot multiply sequence by non-int of type ‘float’ 
“demo”*”demo” —> TypeError: can multiply sequence by non-int of type ’str’

+ —> string concatenation operator  * —> string multiplication operator 

Note : for any number x,
x/0 and x%0 always raises “ZeroDivisionError”

10/0
10.0/0

Relational operators :   >, >=, <, <=

a= 10
b= 2-
print(“a > b is “,a>b)
print(“a >= b is “,a>=b)
print(“a < b is “,a<b)
print(“a <= b is “,a<=b)

a > b Is False 
a >= b Is False 
a < b is True
a <= b is True

We can apply relational operators for str types also 

Eg 2:

a=“demo”
b=“demo”

print(“a > b is “,a>b)
print(“a >= b is “,a>=b)
print(“a < b is “,a<b)
print(“a <= b is “,a<=b)

a > b Is False 
a >= b Is True
a < b is False
a <= b is True

Eg: 

print(True>True)  False 
print(True>=True) True
print(10>True) True
print(False > True) False

print(10>’demo’)
   TyoeError: ‘>’ not supported between instances of ‘int’ and ’str’


a=10
b=20
If(a>b):
   print(“a is greater than b”)
else:
   print(“a is not greater than b”)

Output : a is not greater than b

Note: chaining of relational operators is possible. In the chaining, if all compassions returns True then only result is True. If aleast one comparison returns false then the result is false.

10<20 —> True
10<20<30 —> True
10<20<30<40 —> True
10<20<30<40>50 —> False 

Equality operator 

We can apply these operators for any type even for incompatible types also.

>>> 10==20
False 
>>> 10!=20
True
>>>  10==True
False
>>>  False==False 
True
>>> “demo”==“demo”
True
>>> 10==“demo”
False

Note: chaining concept is applicable for equality operators. If at least one comparison returns false then the result is False. Otherwise the result is True.

>>> 10==20==30==40
False
>>> 10=10=10=10
True

Logical operators: and , or, not 

We can apply for all types

For boolean types behavior 

And  —> if both arguments are True then only result is True
or —> if atleast one argument is True then result is True
not —> complement 

True and False —> False 
True or False —> True 
Not Fasle  —> True 

For non-boolean types behavior 

0 means False 
non-zero means True 
empty string is always treated as False

x and y:

If x is evaluates to false return x otherwise return y 

Eg:

10 and 20
0 and 20 

If first argument is zero then result is zero otherwise result is y

x or y 

If x evaluates to True then result is x otherwise result is y 

10 or 20 —> 10
0 or 20 —> 20 

Not x 

If x is evaluates to False then result is true otherwise false 

not 10 —> false 
not 0 —> true 

Eg: 

“demo” and “demob”  ==>  demob
“”  and “demo” ==> “”
“demo” and “” ==> “”
“” or “demo” ==> “demo”
“demo” or “” ==>  “demo”
not “” ==> True
not “demo” ==> False

Bitwise operators 

We can apply these operators bitwise 
These operators are applicable only for int and boolean types.
By mistake if we are trying to apply for any other type then we will get error.
&, |, ^, -, <<, >>
print(4&5) —> valid 
print(10.5 & 5.6)
—> TypeError: unsupported operand type(s) for &: ‘float’ and ‘float’
print(True & True) —> valid 
& —> if both bits are 1 then only result is 1 otherwise result is 0
| —> if at least one bit is 1 then result is 1 otherwise result is 0
^ —> if bits are different then only result is 1 otherwise result is 0  - —> bitwise complement operator 
1 —> 0 & 0 —> 1 
<< —> bitwise left shift 
>> —> bitwise right shift 

print(4&5)  —> 4
print(4 | 5) —> 5
print(4^5) —> 1 


Operator 
 Description
If both bits are 1 then only results is 1 otherwise result is 0
If atleast one bit is 1 then result is 1 otherwise result is 0 
If bits are different then only result Is 1 otherwise result is 0 
"
Bitwise complement operator i.e means 0 and 0 means 1 
>> 
Bitwise left shift operator 


<<
Bitwise right shift operator

Bitwise complement operator ( ~ ) 

We have to apply  complement for total bits 

Eg :  print(~5) = -6 

Note : 

The most significant bit acts as sign bit. 0 value represents  +ve number where as 1 represents -ve value.
Positive numbers will be represented directly in the memory where as -ve numbers will be represented indirectly in 2’s complement form.

Shift operators 

<< left shift operator 
After shifting the empty cells we have to fill with zero 

print(10<<2)  —> 40 


0 ( cross mark ) 
0 (cross mark )
0
0
1
0
1
0





0
1
0
1
0
0
0




Right shift operator 

After shifting the empty cells we have to fill with sign bit ( 0 for +ve and 1 for -ve )

print(10>>2) —> 2 


0
0
0
0
1
0
1 ( cross mark ) 
0 (cross mark )






0
0
0
0
0
0
1
0





We can apply bitwise operators for boolean types also : 














Python Escape characters

In string literals we can use escape characters  to associate a special meaning 

>>> s=“demo\ndemob”
>>> print(s)
demo
demob
>>> s=“demo\ndemob”
>>> print(s)
demo demob
>>> s=“This is “symbol”
  File “<stdin>”, line 1 
     s=“This is “ symbol”
                       ^
SyntaxError: invalid syntax 
>>> s=“This is \” symbol”
>>> print(s)
This is “ symbol

The following are various important escape characters in python 

\n —> New line 
\t —> horizontal tab
\r —> carriage return 
\b —> back space
\f —> form feed 
\v —> vertical tab 
\’ —> single quote 
\” —> double quote
\\ —> back slash symbol 

Constants 

Constants concept is not applicable in python 
But it is convention to use only uppercase characters if we don’t want to change value 
MAX_VALUE = 10
It is just convention but we can change the value.


Wednesday, December 11, 2019

Python TypeCasting

We can convert one type value to another type. This conversation is called Typecasting or Type coercion.

The following are various inbuilt functions for type casting.

  1. int()
  2. float()
  3. complex()
  4. bool()
  5. str()

int()

We can use this function to convert values from other types to int

  1. >>> int(123.987)
  2. 123
  3. >>> int(10+5j)
  4. TypeError: can’t convert complex to int
  5. >>> int(True)
  6. >>> int(False)
  7. 0
  8. >>> int(“10”)
  9. 10
  10. >>> int(“10.5”)
  11. ValueError: invalid literal for int() with base 10: ’10.5'
  12. >>> int(“ten”)
  13. ValueError: invalid literal for int() with base 10: ’ten'
  14. >>> int(“0B1111”)
  15. ValueError: invalid literal for int() with base 10: ‘0B1111'

Note:

  1. We can convert from any type to int except complex type 
     2. If we want to convert str type to int type, compulsary str should contain only integral value and should be specified in base-10 

float()

We can use float() function to convert other type values to float type.

  1. >>> float(10)
  2. 10.0
  3. >>> float(10+5j)
  4. TypeError: can’t convert complex to that 
  5. >>> float(True)
  6. 1.0
  7. >>> float(False)
  8. 0.0
  9. >>> float(“10”)
  10. 10.0
  11. >>> float(“10.5)
  12. 10.5
  13. >>> float(“ten”)
  14. ValueError: could not convert string to float: ’ten'
  15. >>> float(“0B1111”)
  16. ValueError: could not convert string to float: ‘0B1111’ 

Note:

  1. We can convert any type value to float type except complex type.
  2. Whenever we are trying to convert str type to float type compulsary str should be either integral or floating point literal and should be specified only in base-10.

Complex():

  1. We can use complex() function to convert other types to complex type.

Form-1 complex(x)
We can use this function to convert x into complex number with real part x and imaginary part 0.

Eg:

  1. complex(10)==>10+0j
  2. complex(10.5)===>10.5+0j
  3. complex(True)==>1+0j
  4. complex(False)==>0j
  5. complex(“10”)==>10+0j
  6. complex(“10.5”)==>10.5+0j
  7. complex(“ten”)
  8.  ValueError: complex() arg is a malformed string 

Form-2 complex(x,y) 

We can use this method to convert x and y into complex number such that x will be real part and y will be imaginary part.

Eg:     complex(10, -2)  —> 10-2j 
          complex(True, False) —> 1+0j

bool()
We can use this function to convert other type values to bool type.

  1. bool(0) —> False
  2. bool(1) —> True
  3. bool(10) —> True
  4. bool(10.5) —> True
  5. bool(0.178) —> True
  6. bool(0.0) —> False
  7. bool(10-2j) —> True
  8. bool(0+1.5j) —> True
  9. bool(0+0j) —> False
  10. bool(“True”) —> True
  11. bool(“False”) —> True
  12. bool(“”) —> False 

bool(x) 

If X is int datatype
  1. 0 means false 
  2. Non-zero means true

If X is float datatype 
  1. If total number value is zero then the result is false otherwise the result is true 

If X is Complex datatype 
  1. If both real and imaginary parts are zero .i.e 0+0j then the result is false otherwise the result is true 

If X is str datatype 

  1. If x is empty string then the result is false otherwise the result is true

str():

We can use this method to convert other type values to str type.

  1. >>> str(10)
  2. ’10'
  3. >>> str(10.5)
  4. ’10.5'
  5. >>> str(10+5j)
  6. ‘(10+5j)'
  7. >>> str(True)
  8. ’True'

Fundamental Data types vs Immuntability:

  1. All fundamental data types are immutable. i.e once we creates an object, we cannot perform any changes in that object. If we are trying to change then with those changes a new object will be created. This non-changeable behavior is called immutability.
  1. In python if a new object is required, then PVM. Won’t create object immediately. First it will check is any object available with the required content or not. If available then existing object will be reused. If it is not available then only a new object will be created. The advantage of this approach is memory utilization and performance will be improved.

     3. But the problem in this approach is, several references pointing to the same object, by using one reference if we are allowed to change the content in the existing object then the remaining references will be effected. To prevent this immutability concept is required. According to this once creates an object we are not allowed to change content. If we are trying to change with those changes a new object will be created.


>>> a = 10
>>> b = 10
>>> a = b 
True
>>> id(a) 
1572353952
>>> id(b)
1572353952
>>>
>>> a=10+5j
>>> b=10+5j
>>> a is b 
False 
>>> id(a)
15980256
>>> id(b)
15979944
>>> a=True
>>> b=True
>>> a Is b
True
>>> id(a) 
1572172624
>>> id(b)
1572172624 
>>> a=‘durga’
>>> b=‘durga’

>>> a is b
True
>>> id(a) 
16378848
>>> id(b)
16378848


Bytes data type:

Bytes data type represents a group of byte numbers just like an array

x = [10,20,30,40]
     b = bytes[x]
     type(b)  —> bytes
     print(b[0]) —> 10
     print(b[-1]) —> 40
     >>> for i in b : print(i)

10
20
30
40 

Conclusion 1: The only allowed values for byte data type are 0 to 256. By mistakes if we are trying to provide any other values then we will get value error.

Conclusion 2: once we creates bytes data type value, we cannot change its values, otherwise we will get TypeError.

Eg: 

>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: ‘bytes’ object does not support item assignment

Byte array data type:

Byte array Is exactly same as bytes data type except that its elements can be modified.

x=[10,20,30,40]
b = bytearray(x)
for i in b : print(i)
10
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40 

Eg:2

>>> x=[10,256]
>>> b= byte array(x)
valueError: byte must be in range(0, 256)

List Data Type:
If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type.

Insertion order is preserved 
Heterogeneous objects are allowed
Duplicates are allowed 
Growable in nature
Values should be enclosed within square brackets

Eg: 

list=[10,10.5,’durga’,True,10] 
   print(list) # [10,10.5,’durga’,True,10]

Eg: 

list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[ 20, 30]
>>> list[0]=100
>>> for i in list:print(i)
100
20
30
40

List in growable in nature. i.e based on  our requirement we can increase or decrease the size.

>>> list=[10,20,30]
>>> list.append(“durga”)
>>> list
[10,20,30, ‘durga’]
>>> list.remov(20)
>>> list
[10,30, ‘durga’]
>>> list2=list*2
>>> list2
[10,30, ‘durga’, 10,30, ‘durga’]

Note: An ordered, mutable, heterogenous collection of elements is nothing but list, where duplicates also allowed.

Tuple Data Type:

Tuple data type is exactly same as list data type except that is immutable i.e we cannot change value.
Tuple elements can be represented within parenthesis.

t=(10,20,30,40)
type(t)
<class ’tuple’>
t[0]=100
typeError: ’tuple’ object does not support item assignment
>>> t.append(“durga”)
AttributeError: : ‘tuple' object has no attribute ‘append’
>>> t.removal(10)
AttributeError: ’tuple’ object has no attribute ‘remove’

Note: tuple is the read only version of list.

Range data type

Range data type represents a sequence of numbers.
The elements present in range data type are not modifiable i.e range data type is immutable.

Eg:

r = range(10)
for i in r : print(i) —> 0 to 9 

Form-2: range(10,20)
Generate numbers from 10 to 19 

Eg: 

r = range(10,20)
for i in r : print(i) —> 10 to 19

Form3: range(10, 20, 2)
2 means increment value 

Eg: 
r = range(10,20,2)
for i in r : print(i) —> 10,12,14,16,18 

We can access elements present in the range data type by using index 

Eg: 
r = range(10,20)
r[0] —> 10
r[15] —> indexError : range object index out of range

We cannot modify the values of range data type.

Eg:

r[0] = 100
TypeError : ‘range’ object does not support 

We cannot create a list of values with range  data type.

Eg: 

>>> I = list(range(10)))
>>> I
[0,1,2,3,4,5,6,7,8,9]

Set Data type 

If we want to represent a group if values without duplicates where order is not important then we should go for set Data Type.

Insertion order is not preserved 
Duplicates are not allowed 
Heterogeneous objects are allowed 
Index concept is not appilable 
It is mutable collection
Growable in nature

Eg: 

s={100,0,10,200,10,’durga’}
s# {0,100,’durga’, 200,10}
s[0] —> TypeError: ’set’ object does not support indexing 

Set is growable in nature, based on our requirement we can increase or decrease the size.

>>> s.add(60)
>>> s
(0,100, ‘durga’, 200, 10, 60)
>>> s.remove(100)
>>> s
(0, ‘durga’, 200, 10, 60)

Frozen set data type

It is exactly same as set except that it is immutable;e.
Hence we cannot use add or remove functions.

>>> s={10,20,30,40}
>>>  fs=frozenset(s)
>>>  type(fs)
frozenset({40,10, 20,30})
>>> for i in fs:print(i)
40
10
20
30

>>> fs.add(70)
AttributeError: ‘frozenset’ object has no attribute ‘add’
>>> fs.remove(10)
AttributeError: ‘frozenset’ object has no attribute ‘remove’

dict data type

If we want to represent a group of values as key-value pairs then we should go for dict data type.

Eg: d = {101:’durga’,102:’ravi’,103:’shiva’}

Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value.

>>> d={101:’durga’,102:’ravi’,103:’shiva’}
>>> d[101]=’sunny’
>>> d
(101:’sunny’, 102:’ravi’, 103:’shiva’}

We can create empty dictionary as follows 
d={}
We can add key-value pairs as follows 
d[‘a’]=‘apple’
d[‘b’]=‘banana’
print(d)

Note:  dict is mutable and the order won’t be preserved 

In general we can use bytes and byte array data types to represent binary information like images, video files etc 
In python2 long data type is available. But in python3 it is not available and we can represent long values also by using int type only.
In python there is no char datatype, hence we can represent char values also by using str type.


Datatype  Description  Is immutable ? Example
Int 
We can use to
Represent the whole/integral numbers 
Immutable 
>>> a=10
>>> type(a)
<class ‘int’>
Float  We can use to represent the decimal/floating point numbers  Immutable 
>>> b=10.5
>>> type(b)
<class ‘float’>

Complex  We can use to represent the complex numbers  Immutable 
>>> c=10+5j
>>> type(c)
<class ‘complex’>
>>> c.real
10.0
>>> c.imag
5.0
Bool We can use to represent the logical values ( only allowed values are true and false ). Immutable 
>>> flag=True
>>> flag=false 
>>> type(flag)
<class ‘bool’>
Str To represent the sequence of characters Immutable 
>>>s=‘durga’
>>>type(s)
<class ’str’>
>>>s=“durga”
>>>s=‘’’Durga Software solutions… Ameerpet’’'
>>> type(s)
<class ’str’>




Bytesarray To represent a sequence of byte values from 0-255  mutable  
>>> list[10,20,30]
>>> b=bytearray(list)
>>> type(ba)
<class ‘bytearray’>
bytes To represent a sequence of byte values from 0-255 immutable 
>>> list[1,2,3,4]
>>> b=bytes[list]
>>> type(b)
<class ‘bytes’>

Range  To represent a range of values  Immutable 
>>> r=range(10)
>>> r1=range(0,10)
>>> r2=range(0,10,2)
List  To represent an ordered collection of objects  Mutable 
>>> I=[10,11,12,13,14,15]
>>> type(I)
<class ‘list’>
Tuple  To represent an ordered collection of objects  Immutable 
>>> t=(1,2,3,4,5)
>>> type(t)
<class ’tuple’>
Set  To represent an unordered collection of unique objects  mutable 
>>> s={1,2,3,4,5,6}
>>> type(s)
<class ’set’>



frozenset To represent an unordered collection of unique objects  Immutable 
>>> s={11,2,3,’Durga’,100,’Ramu’}
>>> fs=frozenset(s)
>>> type(fs)
<class  ‘frozen set’>

dict To represent a group of key value pairs  Mutable 
>>>
d = {101:’durga’, 102:’rams’, 103:’hard’}
type(d)
<class ‘dict’>


None Data type:

None means nothing or No value associated
If the value is not available then to handle such type of cases, None introduced.
It is something like null value in java.

Eg:

def m1():
  a=10

Print(m1())
   None





    Monday, December 9, 2019

    python data types

    Data type represents the type of data present inside a variable.
    In python we are not required  to specify the type explicitly. Based on value provided, the type will be assigned automatically. Hence python is dynamically typed language.

    Python contains following inbuilt data types 
    Int 
    Float 
    Complex 
    Bool
    Str
    Bytes
    Bytearray
    Range
    List
    Tuple
    Set 
    Frozenset 
    Dict 
    None

    Note : python contains several inbuilt functions

    1. type() : to check the type of variable 
    2. id() : to get address of object 
    3. print() : to print the value 


    In python everything is an object. 

    1. Int Data Type : we can use int data type to represent whole numbers ( integral values ) 
    E.g : a = 10 
            type(a) #int

    Note : 
    In python2 we have long data type to represent very large integral values.
    But in python3 there is no long type explicitly and we can represent long values also by using int type only.

    We can represent int values in the following ways 

    1. Decimal form 
    2. Binary form 
    3. Octal form 
    4. Hexa decimal form 

    1. Decimal form ( Base-10)

     It is the default number system in python 
    The allowed digits are : 0 to 9 
    E.g. : a = 10 

    1. Binary form ( Base-2)

    The allowed digits are : 0 & 1 
    Literal value should be prefixed with 0b or 0B

    E.g:  a= 0B1111 a=0B123 a=b111

    1. Octal form 

    The allowed digits are : 0 to 9, a-f ( both lower and upper cases are allowed )
    Literal value should be prefixed with  0x or 0X 

    Eg: a = 0XFACE a = 0XBeef a = 0XBeer 

    Note: Being a programmer we can specify literal values in decimal, binary, octal and hexadecimal forms. But PVM  will always provide values only in decimal form.

    a=10        print(a)10
    b=0o10   print(b)8
    c=0X10   print(c)16
    d=0B10  print(d)2 

    Base conversions 

    Python provide the following in-built functions for base conversions 

    1. bin():
    We can use bin() to convert from any base to binary 

    1. >>> bin(15)
          2.  ‘0b1111’
    1. >>> bin(0o11)
    2. ‘0b1001'
    3. >>> bin(0X10)
    4. ‘0b10000'

    1. oct():
    We can use oct() to convert from any base to octal 

    1. >>> oct(10)
          2. ‘0o12’
    1. >>> oct(0B1111)
    2. ‘0o17'
    3. >>> oct(0x123)
    4. ‘0o443'

    1. hex();
    We can use hex() to convert from any base to hex decimal 

    1. >>> hex(100)
    2. ‘0x64'
    3. >>> hex(0B111111)
    4. ‘0x3f'
    5. >>> hex(0o12345)
    6. ‘0x14e5'

    1. Float Data Type:

    We can use float data type to represent floating point values ( decimal values )
    E.g: f = 1.234 
          type(f) float 

    We can also represent floating point values by using exponential form 
    ( Scientific Notation )
    Eg: f = 1.2e3 —> instead of ‘e’ we can use  ‘E’ 
         Print(f) 1200.0 

    The main advantage of exponential form is we can represent big values in less memory.

    Note : we can represent int values in decimal , binary octal and hex decimal forms. But we can represent float values only by using decimal form.

    1. >>>f=0B11.01
    2.  File “<stdin>”, line 1
    3.   f=0B11.01
    4.          ^
    5. SyntaxError: invalid syntax

    6. >>> f=0o123.456
    7. SyntaxError: invalid syntax 

    8. >>>f=0X123.456
    9. SyntaxError: invalid syntax 

    1. Complex data type 
    A complex number of the form 

    a  ( Real part ) + b ( imaginary part ) j  ( j2 = -1 ) 

    ‘a’ and ‘b’ contain integers or floating point values.

    Eg: 
    3 + 5j
    10 + 5.5j
    0.5 + 0.1j

    In the real part if we use int value then we can specify that either by decimal, octal, binary or hex decimal form.
    But imaginary part should be specified only by using decimal form.

    1. >>> a=0B11+5j
    2. >>> a
    3. (3+5j)
    4. >>>a=3+0B11j
    5.  SyntaxError: invalid syntax 

    Even we can perform operations on complex type values.

    1. >>> a=10+1.5j
    2. >>> b=20+2.5j
    3. >>> c=a+b 
    4. >>> print(c)
    5.  (30+4j)
    6. >>> type(c) 
    7. <class ‘complex’>

    Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary part 

    c = 10.5+3.6j

    c.real —> 10.5 
    c.imag —> 3.6 

    We can use complex type generally in scientific applications and electrical engineering applications.

    1. Bool datatype 

    We can use this data type to represent boolean values.
    The only allowed values for this data type are : 
    True and False 
    Internally python represents True as 1 and False 0 

    b = True 
    type(b) —> bool 

    Eg:

    a = 10
    b = 20 
    c = a<b
    print(c) —> True 

    True+True —> 2 
    True-False —> 1 

    1. str Data type

    Str represents string data type.
    A string is a sequence of characters  enclosed within single quotes or double quotes.

    s1=‘durga’
    s1=“durga”

    By using single quotes or double quotes we cannot represent multi line string literals.

    s1=“durga
    soft”

    For this requirement we should go for triple single quotes(‘’’)  or triple double quotes(“””)

    s1 = '’’durga
    soft’’'

    s1 = “””durga
    soft”””

    We can also use triple quotes to use single quote  or double quotes  in our string.
    ‘’’ This is “ character’’'
    ‘ This i “ Character’

    We can embed one string in another string 
    ‘’’ This “Python class very helpful” for java students’’'

    Slicing of Strings:

    1. Slice means a piece  2) []operator is called slice operator, which can be used to retrieve parts of string
    2. In python strings follows zero based index 
    3. The index can be either +ve or -ve 
    4. +ve index means forward direction from left to right 
    5. -ve index means backward direction from right to left 


    -5 
    -4 
    -3 
    -2 
    -1 


    d
    u
    r
    g
    a


    0
    1
    2
    3
    4



    1. >>> s=“durga"
    2. >>> s[0]
    3. ‘d'
    4. >>> s[1]
    5. ‘u'
    6. >>> s[-1]
    7. ‘a'
    8. >>> s[40]

    IndexError: string index out of range

    1. >>> s[1:40]
    2. ‘urga'
    3. >>> s[1:]
    4. ‘urga'
    5. >>> s[:4]
    6. ‘durg'
    7. >>> s[:]
    8. ‘durga'
    9. >>>

    10. >>> s*3 
    11. ‘durgadurgadurga'

    12. >>> len(s)
    13. 5

    Note:

    In python the following data types are considered as fundamental data types 

    Int
    Float 
    Complex 
    bool
    Str

    In python, we can represent char values also by using str type and explictly char type is not available.

    1  >>> c=‘a’
    2  >>> type(c)
    3  <class ’str’>

    Long data type is available in Python2 but not in Python3. In Python3 long values also we can represent by using int type only.

    In python we can present char value also by using str type and explicitly char type is not available.