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 
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. 1 
  7. >>> int(False)
  8. 0
  9. >>> int(“10”)
  10. 10
  11. >>> int(“10.5”)
  12. ValueError: invalid literal for int() with base 10: ’10.5'
  13. >>> int(“ten”)
  14. ValueError: invalid literal for int() with base 10: ’ten'
  15. >>> int(“0B1111”)
  16. 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.



    python reserve words

    In python some words are reserved to represent some meaning or functionality.
    Such types of words are called reserve words.

    There are 33 reserved words available in python.

    True, False , None 
    and, or, not, is 
    if, elif, else
    while, for, break, continue, return, in, yield 
    try, except, finally, raise, assert
    import, from, as, class, def, pass, global, nonlocal, lambda, del, with 

    Note:

    All reserved words in python contain only alphabet symbols.

    Except the following 3 reserved words, all contain only lower case alphabet symbols.

    True 
    False 
    None

    Eg: a=true ( wrong )  a=True ( right ) 

    >>> Import keyword 
    >>> keyword.kwlist
    [‘False’, ’None’, ’True’, ‘and’, ‘as’, ‘assert’, ‘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’]


    Python Identifier

    A Name in python program is called identifier.
    It can be class name or function name or module name or variable name.

    a = 10

    Rules to define identifiers in python :  

    The  only allowed characters in python are 

    1. Alphabet symbols ( either lower case or upper case )
    2. Digits(0 to 9)
    3. Underscore symbol(_)

    By mistake if we are using any other symbol like $ then we will get syntax error.

    cash = 10 ( right )
    ca$h = 20 ( wrong )

    1. Identifier should not starts with digit 
               123total ( wrong )
                total123 ( right )

         3. Identifiers are case sensitive. Of course python language is case sensitive language.
             total=10
             TOTAL=999
             print(total) #10
             print(TOTAL) #999

    Identifier 

    Alphabet symbols ( Either upper case or lower case )
    If identifier is start with underscore(_) then it indicates it is private.
    Identifier should not start with digits
    Identifier are case sensitive 
    We cannot use reserve words as identifiers ( Eg: def = 10 ( wrong ) )
    There is no length limit for the python identifiers. But not recommended to use too lengthy identifiers.
    Dollar ( $ ) symbol is not allowed in python.

    Which of the following are valid python identifiers ?

    123total ( wrong )
    total123 ( right )
    java2share ( right )
    ca$h ( wrong )
    _abc_abc_ ( right )
    def ( wrong )
    if ( wrong ) 

    Note:

    If identifier starts with _symbol then it indicates that it is private.
    If identifier starts with _(Two under score symbols) indicating that strongly private identifier
    If the identifier starts and ends with two underscore symbols then the identifier is language defined special name, which is also known as magic methods.


    Eg : _add_ 

    Sunday, December 8, 2019