Friday, December 27, 2019

How to switch to different azure subscritption using powershell GET approach

Mac setup

Steps for Mac OS ( 10.2 or newer )

Install brew
Install Powershell Core ( brew cask install powershell )
Update brew and powershell ( brew update  ; brew cask install powershell ).
Install Azure Module ( pwsh  ps> Install-Module -Name Az -AllowClobber )
Install PSPKI ( for New-SelfSignedCertificateEx )
ps> Install-Module -Name PSPKI
ps> Import-Module -Name PSPKI

How to connect to the azure subscription using the Az powershell module ?

Install-Module -Name Az -AllowClobber

Then issue command:

Connect-AzAccount

[ WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code FS5V4TL99 to authenticate. ] 

New-AzResourceGroup -Name $resourcegroupname -Location $location

How to test the connectivity with that subscription ?

Get-AzVirtualBetworkGateway -Name <name of VPN gateway>  -ResourceGroupName <Resource group>

when you switch the subscription, need to follow these steps 

Uninstall-AzureRm

Install-Module -Name Az -AllowClobber


Then issue command:
Connect-AzAccount
New-AzResourceGroup -Name $resourcegroupname -Location $location

Thursday, December 26, 2019

String data type


The most commonly used object in any project and in any programming language is String only. Hence we should aware complete information about string data type.

What is string ?
Any sequence of characters within either single quotes or double quotes is considered as a string.

Syntax:

s = ‘karthik’
s = “karthik”

Note: In most of other languages like C, C++, Java a single character with in single quotes is treated as char data type value. But in python we are not having char datatype. Hence it is treated as String only.

Eg: 

>>> ch = ‘a’
>>> type(ch)
<class ’str’>

How to define multi-line string literals ?
We can define multi-line string literals by using triple single or double quotes 

Eg:
>>> s = ‘’’karthik
testing
solutions’'' 

We can also use triple quotes to use single quotes or double quotes as symbol  inside string literal

s = ’This is ’single quote symbol’ —> invalid
s = ’This is \’ single quote symbol’ —> valid 
s = “This is ’single quote symbol” —> valid 
s = ’This is “ double quotes symbol’ —> valid 
s = ’The “Python Notes” by ‘karthik’ is very helpful’ —> invalid 
s = “The “Python Notes” by ‘karthik’ is very helpful” —> invalid 
s = ’The \”Python Notes\” by \’karthik\’ is very helpful’ —> valid 
s = ‘’’The  “Python Notes” by ‘durga’ is very helpful’’’ —> valid 

How to Access characters of a string ?

We can access characters of a string by using the following ways.
By using index 
By using slice operator 

Accessing characters by using index:

Python supports both +ve and -ve index 

+ve index means left to right ( forward direction )
-ve index means right to left ( backward direction )

Eg:  s = ‘karthik’

>>> s=‘karth’
>>> s[0]
‘k’
>>> s[4]
h’
>>> s[-1]
‘h’
>>> s[10]
indexError: string index out of range 

Note: if we are trying to access characters of a string with out of range index then we will get error saying: IndexError

Write a program to accept some string from the keyboard and display its characters by index wise ( both positive and negative index) 

test.py

s=input(“Enter some string:”)
i=0
for x in s:
print(“The character present at positive index {} and at negative index {} is {}” .format(I,i-len(s),x))
i=i+1

Output: 
D:\python_classes>py test.py

Enter Some String:karth

The character present at positive index 0 and at negative index -5 is k
The character present at positive index 1 and at negative index -4 is a
The character present at positive index 2 and at negative index -3 is r
The character present at positive index 3 and at negative index -2 is t
The character present at positive index 4 and at negative index -1 is h

Accessing characters by using slice operator: 

Syntax: s[bEginindex:endindex:step]

Begin Index: From where we have to consider slice (substring)
End Index: we have to terminate the slice (substring) at endindex-1
Step: Incremented Value

Note: 

If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string.
The default value for step is 1 

>>> s=“Learning Python is very very easy!!!”
>>> s[1:7:1]
‘earnin’
>>> s[1:7]
‘earnin’
>>> s[1:7:2]
‘eri’
>>> s[:7]
‘Learnin’
>>> s[7:]
‘g Python is very very easy!!!’
>>> s[::]
‘Learning Python is very very easy!!!’
>>> s[:]
‘Learning Python is very very easy!!!’
>>> s[::-1]
‘!!!ysae yrev yrev si nohtyp gninraeL’

Behavior of slice operator:

s[bEgin:end:step]
Step value can be either +ve or -ve 
If +ve then it should be forward direction(left to right) and we have to consider bEgin to end -1 
If -ve then it should be backward direction(right to left) and we have to consider bEgin to end +1 

Note:

In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.

In forward direction:

default value for bEgin: 0
default value for end: length of string
default value for step: +1 

In Backward Direction :

default value for bEgin: -1 
default value for end: -(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and end index.

Slice operator case study  

S = ‘abcdefghij’
s[1:6:2]  —> ‘bdf’
s[::1] —>  ‘abcdefghij’
s[::-1] —> ‘jihgfedcba’
S[3:7:-1] —> ‘'
s[7:4:-1] —> ‘hgf’
s[0:10000:1] —> ‘abcdefghij’
s[-4:1:-1] —> ‘gfedc’
s[-4:1:-2] —> ‘gec’
s[5:0:1] —> ‘'
s[9:0:0] —> ValueError: slice step cannot be zero 
s[0:-10:-1]  —> ‘'
s[0:-11:-1] —> ‘a’
s[0:0:1] —> ‘'
s[0:-9:-2] —> ‘'
s[-5:-9:-2] —> ‘fd’
s[10:-1:-1] —> ‘'
s[10000:2:-1] —> ‘jihgfed’

Note: Slice operator never raises IndexError

Mathematical operations for string:

We can apply the following mathematical operators for strings.

Operators for concatenation 
Operators for repetition 

print(“karth”+”ik”) —> karthik 
print(“karthik”*2) —> karthikkarthik 

Note:
To use + operator for strings, compulsory both arguments should be str type.
To use * operator for strings , compulsory one argument should be str and other argument should be int

len() in-built function 

We can use len() function to find the number of characters present in the string.

Eg: 

s = ‘kaushik’
print(len(s))  —> 5 

Write a program to access each character of sting in forward and backward direction using while loop ?

s = “Learning Python is very easy!!!”
n = len(s) 
i = 0
print(“Forward direction”)
while I<n:
print(s[I], end=‘ ‘)
i +=1
print(“Backward direction”)
i = -1
while i >=-n:
print(s[I],end=‘ ‘)
i = i-1
  
Alternative ways 

s = “Learning Python is very easy !!!”
print(“Forward direction”)
for i in s:
print(I,end=‘ ‘)
print(“Forward direction”)
for I in s[::]:
print(I,end=‘ ‘)

print(“Backward direction”)
for I in s[::-1]:
print(I,end=‘ ‘)

Checking Membership:

We can check whether the character or string is the member of another string or not by using in and not in operators

s = ‘karth’
print(‘k’ in s) —> True 
print(‘2’ in s) —> False 

s = input(“Enter main string:”)
subs = input(“Enter sub string:”)
if subs in s:
   print(subs, “is found in main string”)
else:
   print(subs, “is not found in main string”)

Output:

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:karth
karth is found in main string

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:python
karth is not found in main string

Comparison of strings:

We can use comparison operators  (<,<=,>,>=)  and equality operators  (==, !=) for strings.
Comparison will be performed based on alphabetical order 

s1=input(“Enter first string:”)
s2=input(“Enter Second string:”)
if s1==s2:
print(“Both strings are equal”)
elif s1<s2:
print(“First String is less than Second String”)
else:
print(“First String is greater than Second String”)

Output:

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:karth
Both strings are equal 

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:ravi
Both strings is less than Second String

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:anil
Both strings is greater than Second String

Removing Spaces from the string:

We can use the following 3 methods 

rstrip()  —> To remove spaces at right hand side 
lstrip() —> To remove spaces at left hand side
strip() —> To remove spaces both sides 

city=input(“Enter your city Name:”)
scity=city.strip()
If scity==‘Hyderabad’:
print(“Hello Hyderabad..Adab”)
elif scity==‘Chennai’:
print(“Hello Madrasi…Vanakkam”)
elif scity==“Bangalore”:
print(“Hello kannadiga..shubhodaya”)
else:
print(“your entered city is invalid”)

Finding Substrings:

We can use the following 4 methods 

For Forward direction:

  1. Find()
  2. index()

For Backward direction:

  1. rfind()
  2. rindex()

find():

s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get  -1.

s=“learning Python is very easy”
print(s.find(“Python”)) #9
print(s.find(“Java”)) #-1
print(s.find(“r”))#3
print(s.rfind(“r”))#21

Note: By default find() method  can search total string. We can also specify the boundaries to search.

s.find(substring, bEgin,end)
It will always search from bEgin index to end -1 index.

s=“karthravipavanshiva”
print(s.find(‘a’))#4
print(s.find(‘a’,7,15))#10
print(s.find(‘z’,7,15))#-1

index():

Index() method is exactly same as find()  method except that if the specified substring is not available then we will get valueerror

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
try:
n=s.index(subs)
except  ValueError:
print(“substring not found”)
else:
print(“substring found”)

Output
 
D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:python 
substring found 

D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:java
Substring not  found 

Program to display all positions of substring in a given main string 

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print(“Found at position”,pos)
flag=True
If flag==False:
print(“Not Found”)

Output 

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:bb
Found at position 1 

Counting substring in the given string:

We can find the number of occurrences of substring present in the given string by using count() method 

  1. s.count(substring) —> it will search through out the string 
  2. s.count(substring, bEgin, end) —> it will search from bEgin index to end -1 index.

s=“abcabcabcabcadda”
print(s.count(‘a’))
print(s.count(‘ab’))
print(s.count(‘a’,3,7))

Output 

6
4
2

Replacing a string with another string:

s.replace(old string, newstring)
Inside s, every occurrence of old string will be replaced with new string.

Eg1

s = “Learning Python is very difficult”
s1 = s.replace(“difficult”, “easy”)
print(s1)

Output :  Learning Python is very easy

Eg2: All occurrences will be replaced

s = “abababaabaaba”
s1 = s.replace(“a”, “b”)
print(s1)

Output : bbbbbbbbbbbbbb

String objects are immutable then how we can change the content by using replace() method 

Once we creates string object, we cannot change the content. This non-changeable behavior is nothing but immutability. If we are trying to change the content by using any method, then with those changes a new object will be created and changes won’t be happened in existing object.

Hence the replace() method also a new object got created but existing object won’t be changed.

Eg:

s = “abab”
s1 = s.replace(“a”,”b”)
print(s,”is available at :”,id(s))
print(s1,”is available at:”,id(s1))

Output:

abab is available at : 4568672 
bbbb is available at : 4568704 

In the above example, original object is available and we can see new object which was created because of replace() method.

Splitting of Strings:

We can split the given string according to specified separator by using split() method.

l=s.split(separator)

The default separator is space, the return type of split() method is list.

s=“karth software solutions”
l=s.split()
for x in l:
print(x)

Output:

karth
software
solutions

s=“22-02-2018”
l=s.split(‘-‘)
for x in l:
print(x)

Output 

22
02
2018

Joining of strings:

We can join a group of strings ( list or tuple ) wrt the given separator 

s = (’sunny’,bunny’,’chinny’)
s = ‘-‘.join(t)
print(s)

Output: sunny-bunny-chinny

Eg-2:

l = [‘hyderabad’,’singapore’,’london’,’dubai’]
s = ‘:’.join(l)
print(s)

Output : hyderabad:singapore:london:dubai

Changing case of string:

 We can change case of a string by using the following 4 methods.

upper() —> to convert all characters to upper case 
lower() —> to convert all characters to lower case 
swapcase —> converts all lower case characters to upper case and all upper case characters to Lower case.
title() —>  to convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
capitaize()  —> only first character will be converted to upper case and all remaining characters can be converted to Lower case

s = ‘learning python is very easy’
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

Output:

LEARNING PYTHON IS VERY EASY 
Learning python is very east 
LEARNING pYTHON IS VERY eASY 
Learning Python Is Very Easy
Learning python is very easy 

Checking starting and ending part of the string:

Python contains the following  methods for this purpose:

  1. s.startwith(substring)
  2. s.endswith(substring)

s= ‘learning Python is very easy’
print(s.startswith(‘learning’))
print(s.endswith(‘learning’))
print(s.endswith(‘easy’))

Output 

True
False
True

To check type of characters present in a string 

Python contains the following methods for this purpose.

isalnum(): Returns True if all characters are alphanumeric( a to z, A to Z, 0 to 9)
isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
isdigit(): Returns True if all characters are digits only( 0 to 9)
islower(): Returns True if all characters are lower case alphabet symbols
Isupper(): Returns True if all characters are upper case alphabet symbols
istitle(): Returns True if string is in title case.
isspace(): Returns True if string contains inly spaces 

Eg:

print(‘Karth786’.isalnum()) —> True
print(‘Karth786’.isalpha()) —> False
print(‘Karth’.isalpha()) —> True
print(‘Karth’.isdigit()) —> False
print(‘786786’.isdigit()) —> True
print(‘abc’.islower()) —> True
print(‘Abc’.islower()) —> False
print(‘abc123’.islower()) —> True
print(‘ABC’.isupper()) —> True
print(‘Learning python is Easy’.istitle()) —> False 
print(‘Learning Python is Easy’.istitle()) —> True
print(‘  ‘.isspace()) —> True

Program 

s=input(“Enter any character:”)
if s.isalnum():
print(“Alpha Numeric Character”)
if s.isalpha():
print(“Alphabet character”)
if s.islower():
print(“Lower case alphabet character”)
else:
print(“Upper case alphabet character”)
else:
print(“it is a digit”)
elif s.isspace():
print(“it is space character”)
else:
print(“Non Space Special Character”)

D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character 
It is a digit

D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character 
Alphabet Character 
Lower case alphabet character 

D:\python_classes>py test.py
Enter any character:$
Non Space Special Character 

D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character 
Alphabet Character 
Lower case alphabet character 

Formatting the Strings:

We can format the strings with variable values by using replacement operator {} and format() method 

name = ‘karth’
salary = 10000
age  = 48 
print(“ {} ’s salary is {} and his age is {}”.format(name, salary,age))
print(“{0} ’s salary is {1} and his age is {2}”.format(name, salary,age))
print(“{x} ’s salary is {y} and his age is {z}”.format(z=age,y=salary,x=name))

Output 

karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 

Important Programs regarding String Concept 

Q1 write a program to reverse the given string 

Input: karth
Output: htrak

1st way:
s = input(“Enter Some String:”)
print(s[::-1])

2nd way:
s = input(“Enter Some String:”)
print(“.join(reversed(s)))

3rd way:

s = input(“Enter Some String:”)
i=len(s)-1
target=‘'
while i>=0:
target=target+s[i]
i=i+1
print(target)

Q2 Program to reverse order of words 

Input: Learning Python is vert Easy
Output: Easy Very is Python Learning 

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[I])
i=I-1
output=‘ ‘.join(l1)
print(output)

Output: Enter Some String:Learning Python is very easy!!
             easy!!! Very is Python Learning 

Program to reverse internal content of each word 

Input: Karth Software Solutions
Output: htrak erawtfos snoituloS

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[I][::-1])
i=i+1
output=‘ ‘.join(l1)
print(output)

Write a program to print characters at odd position and even position for the given string ?

1st way:

s =input(“Enter Some String:”)
print(“Characters at Even Position:”,s[0::2])
print(“Characters at Odd Position:”,s[1::2])

2nd way:

s=input(“Enter Some String:”)
i=0
print(“Characters at Even Position:”)
while I<len(s):
print(s[I],end=‘,’)
i=i+2 
print()
print(“Characters at Odd Position:”)
i=1
while I<len(s):
print(s[I],end=‘,’)
i=I+2

Program to Merge Characters of 2 Strings into a Single String by talking Characters alternatively 

Input: s1 = “ravi”
          s2 = “reja”

Output: rtaevjia

s1=input(“Enter First String:”)
s2=input(“Enter Second String:”)
output=‘'
i,j=0,0
while I<len(s1) or j<len(s2)
if i<len(s1):
output=output+s1[I]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

Output:

Enter First String:karth
Enter Second String:ravisoft
kraarvgiasoft

Write a program to sort the characters of the string and first alphabet symbols followed by numeric values 

Input: B4A1D3 
Output: ABD134 

s=input(“Enter Some String:”)
s1=s2=output=‘'
for x in s:
If x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)

Write a program for the following requirement 

Input: a4b3c2 
Output: aaaabbbcc

s=input(“Enter Some String:”)
output=‘'
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)

Note:
chr(unicode) —> The corresponding character 
ord(character) —> The corresponding unicode value

Write a program to perform the following activity 

Input: a4k3b2 
Output: aeknbd

s=input(“Enter Some String”)
output=‘'
for x in s:
If x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x)
print(output)

Write a program to remove duplicate characters from the given input string ?

Input: ABCDABBCDABBBCCCDDEEEF
Ouput: ABCDEF 

s = input(“Enter Some String:”)
l=[]
for x in s:
If x not in l:
l.append(x)
output=“.join(l)
print(output)

Write a program to find the number of occurrences of each character present in the given string ?

s=input(“Enter the Some String:”)
d={}
for x in s:
If x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print(“{} = {} Times”.format(k,v))

Write a program to perform the following task ?

Input: 'one two three four five six seven’
Output: ‘one owt three ruof five xis seven’

s = input(‘Enter Some String:’)
l = s.split()
l1 = []
i = 0
while I<len(l):
if I%2==0:
l1.append(l[I])
else
l1.append(l[I][::-1])
i=I+1
output=‘ ‘.join(l1)
print(‘Original String:’,s)
print(‘output String:’,output)

Output:

D:\python_classes>py test.py 
Enter Some String: one two three four five six seven 
Original String: one two three four five six seven 
output String: one owt three ruof five xis seven

Formatting the strings:

We can format the strings with variable values try using replacement operator {} and format () method 
The main objective of format() method to format string into meaningful output form.

Case 1 : Basic formatting for default, positional and keyword arguments 

name = ‘karth’
salary = 10000
age = 48 
print(“{} ’s salary is {} and his age is {}”.format(name, salary,age))
print(“{0} ’s salary is {1} and his age is {2}”.format(name, salary,age))
print(“{x} ’s salary is {y} and his age is {z}”.format(z=age,y=salary,x=name))

Output

karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 

Case 2: formatting numbers 


d —> Decimal IntEger
f  —> fixed point number ( float ).The default precision is 6
b —> Binary format 
o  —> octal format 
x   —> hexa decimal format ( Lower case )
X   —> hexa decimal format ( Upper case )

Eg: 

print(“The intEger number is: {}”.format(123))
print(“The intEger number is : {:d}”.format(123))
print(“The intEger number is : {:5d}”.format(123))
print(“The intEger number is : {:05d}”.format(123))

Output:

The intEger number is: 123 
The intEger number is: 123 
The intEger number is: 123 
The intEger number is: 00123 

EG:2 

print(“The float number is: {}”.format(123.4567))
print(“The float number is: {:f}”.format(123.4567))
print(“The float number is: {:8.3f}”.format(123.4567))
print(“The float number is: {:8.3f}”.format(123.45))
print(“The float number is: {:8.3f}”.format(786786123.45))

Output:
The float number is: 123.4567
The float number is:  123.456700
The float number is:  123.457
The float number is:   0123.457
The float number is:   0123.450
The float number is:   786786123.450

Note:

{:08.3f}
Total positions should be minimum 8.
After decimal point exactly 3 digits are allowed. If it is less then 0s will be placed in the last positions 
If total number is <8 positions then 0 will be placed in MSBs
If total number is  >8 positions then all integrated; digits will be considered
The extra digits we can take only 0

Note: for numbers default alignment is right alignment (>)

Eg-3: Print decimal value in binary , octal and hexadecimal form 

print(“Binary Form:{0:b}”.format(153))
print(“Octal Form:{0:o}”.format(153))
print(“Hexa decimal Form:{0:x}”.format(154))
print(“Hexa decimal Form:{0:X}”.format(154))

Output 

Binary Form: 10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A

Note :
 we can represent only int values in binary, octal and hexadecimal and it is not possible for float values.
{:5d} it takes intEger argument and assigns a minimum width of 5
{:8.3f} it takes a float argument and assigns a minimum width of 8 including  “.”  And after decimal point exactly 3 digits are allowed with round operation if required.
{:05d} The blank places can be filled with 0. In this place only 0 allowed 

Case3 : Number formatting for signed numbers

> while displaying positive numbers, If we want to include + then we have to write  {:+d} and {:+f}
> using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically.

print(“int value with sign:{:+d}”.format(123))
print(“int value with sign:{:+d}”.format(-123))
print(“int value with sign:{:+f}”.format(123.456))
print(“int value with sign:{:+f}”.format(-123.456))

Output:

int value with sign:+123 
int value with sign:-123 
float value with sign:+123.456000
float value with sign:-123.456000

Case-4 : Number formatting with alignment 

<,>, ^ and = are used for alignment
<  —> left alignment to the remaining space
^  —> center alignment to the remaining space
> —> right alignment to the remaining space
= —> forces the signed (+) (-) to the left most position 

Note: default  alignment for numbers is right alignment.

Eg: 

print(“{:5d}”.format(12))
print(“{:<5d}”.format(12))
print(“{:<05d}”.format(12))
print(“{:>5d}”.format(12))
print(“{:>05d}”.format(12))
print(“{:^5d}”.format(12))
print(“{:=5d}”.format(12))
print(“{:^10.3f}”.format(12.23456))
print(“{:=8.3f}”.format(-12.23456))

Output 

12
12
12000
12
00012
12
-12
12.235
-12.235

Case-5: string formatting with format()
Similar to numbers, we can format string values also with format() method 

s.format(string)

print(“{:5d}”.format(12))
print(“{:5}”.format(“rat”))
print(“{:>5}”.format(“rat”))
print(“{:<5}”.format(“rat”))
print(“{:^5}”.format(“rat”))
print(“{:*^5}”.format(“rat”)) # instead of * we can use any character(like +,$,a etc)

Output 

12
rat
rat
rat
rat
*rat*

Note: for numbers default alignment is right where as for strings default alignment is left 

Case-6 : Truncating strings with format() method 

print(“{:.3}”.format(“karthsoftware”))
print(“{:5.3}”.format(“karthsoftware”))
print(“{:>5.3}”.format(“karthsoftware”))
print(“{:^5.3}”.format(“karthsoftware”))
print(“{:*^5.3}”.format(“karthsoftware”))

Output

kar
kar
kar
kar
*kar*

Case-7 : formatting dictionary members using format()

person={‘age’:48,’name’:’karth’}
print(“{name}’s age is: {age}”.format(**person))

Output: karth’s  age is:48 

Case-8 : formatting class members using format() 

class Person:
age=48
name=“kashu”
print(“{p.name}’s age is :{p.age}”.format(p=Person()))

Output : karth’s age is :48 

class Person:
def_init_(self, name,age):
self.name=name
self.age=age
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘karth’,48)))
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘Ravi’,48)))

Note: Here person object is passed as keyword argument. We can access by using its reference variable in the template string.

 Class-9:  Dynamic formatting using format() 

string=“{:{fill}{align}{width}}”
print{string.format(‘cat’,fill=‘*’,align=‘^’,width=5))
print(string.format(‘cat’,fill=‘*’,align=‘^’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘<’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘>’,width=6))

Output:

*cat*
*cat**
cat***
***cat

Class-10: Dynamic float format template

num=“{:{align}{width}.{precision}f}”
print(num.format(123.236,align=‘<‘,width=8,precision=2))
print(num.format(123.236,align=‘>‘,width=8,precision=2))

Output:

123.24
123.24

Case-11: formatting date values 

import datetime
#datetime formatting 
date=datetime.datetime.now()
print(“it’s now:{:%d/%m/%Y  %H:%M:%S}”.format(date))

Output: it’s now: 09/03/2018 12:36:26

Case-12: Formatting complex numbers 

complexNumbers=1+2j
print(“Real Part:{0.real} and Imaginary Part:{0.imag}”.format(complexNumber))


Output: Real Part: 1.0 and Imaginary Part: 2.0 





Wednesday, December 25, 2019

Flow control statements

Flow control describes the order in which statements will be executed at runtime


                                                                   Control Flow 


Conditional Statements

If
If-elif
If-elif-else 


Transfer Statements 

break
continue
pass


Iterative Statements 

For 
While 

Conditional statements 

  1. If 
If condition: statement 

OR 

If condition 
     statement-1 
     statement-2
     statement-3 

If condition is true then statements will be executed 

Eg:

name=input(“Enter Name:”)
if name==“Karthik” :
print(“Hello Karthik Good Morning”)
print(“How are you!!!”)

D:\Python_classes> py test.py 
Enter Name:karthik
Hello karthik Good Morning 
How are you!!!

D:\Python_classes>py test.py
Enter Name: Karthik
How are you!!!

  1. If-else:

If condition:
     Action-1
else:
     Action-2 

If condition is true then Action-1 will be executed otherwise Action-2 will be executed.

name=input(“Enter Name:”)
if name==“karthik” :
print(“Hello Karthik Good Morning”)
else:
print(“Hello Guest Good Morning”)
print(“How are you!!!”)

D:\python_classes>py test.py
Enter Name:karthik
Hello Karthik Good Morning 
How are you!!!

D:\python_classes>py test.py 
Enter Name:kaush
Hello Guest Good Morning 
How are you!!!

if-elfif-else

if condition1:
       Action-1
elfif condition2:
         Action-2
elfif condition3:
         Action-3
elfif condition4:
         Action-4

else:
      Default Action 

Based condition the corresponding action will be executed.

brand=input(“Enter your favorite choco:”)
if brand==“Cadbury”
print(“It is rich brand”)
elif brand==“kitkat”:
print(“it is not that much sweet”)
elif brand==“ross”
print(“other brands are not recommended”)

D:\python_classes>py test.py
Enter Your  Favorite Brand:choco
It is rich brand

D:\python_classes>py test.py
Enter Your  Favorite Brand:kitkat
it is not that much sweet

D:\python_classes>py test.py
Enter Your  Favorite Brand:ross
other brands are not recommended

Note: 

Else part is always optional. Hence the following are various possible syntaxes 

if
If-else
If-elfif-else
If-elfif

There is no switch statement in python 

Write a program to find biggest of given 2 numbers from the command prompt ?

n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
if n1>n2:
print(“Biggest Number is:”,n1)
else:
print(“Biggest Number is:”,n2)

D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:20
Biggest Number: 20 


Write a program to find biggest of given 3 numbers from the command prompt ?

n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
n3=int(input(“Enter Third Number:”))
if n1>n2 and n1>n3:
print(“Biggest Number is:”,n1)
elif n2>n3
print(“Biggest Number is:”,n2)
else:
print(“Biggest Number is:”,n3)


D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:30
Enter Second Number:20
Biggest Number: 30 

Write a program to check whether the given number is in between 1 and 100 ?

n=int(input(“Enter Number:”))
if n>=1 and n<=10 
print(“The number”,n,”is in between 1 to 10”)
else:
print(“The number”,n,”is not  in between 1 to 10”)

Iterative statements 

If we want to execute a group of statements multiple times then we should go for iterative statements 

Python supports 2 types of iterative statements 

For loop and while loop 

If you want to execute some action for every element present in some sequence ( it may be string or collection ) then we should go for for loop 

Syntax : for x in sequence 
               Body 

Where sequence can be string or any collection 
Body will be executed for every element present in the sequence

Eg: to print characters present in the given string

s=“karthik saru”
for x in s 
print(x)

Output 

K
a
r
T
h
I
K
s
a
r
u

Eg:2 to print characters present in string index wise 

s=input(“Enter some string:”)
I=0
for x in s:
print(“The character present at “,I,”index is :”,x)
i=I+1

D:\Python_classes>py test.py

Enter some string: karthik saru

The character present at 0 index is: k
The character present at 1 index is: a
The character present at 2 index is: r 
The character present at 3 index is: t 
The character present at 4 index is: h 
The character present at 5 index is: i 
The character present at 6 index is: k 
The character present at 7 index is: 
The character present at 8 index is: s
The character present at 9 index is: a
The character present at 10 index is: r
The character present at 11 index is: u

Eg3: To print Hello 10 times 

for x in range(10):
print(“Hello”)

Eg4: To display numbers from 0 to 10 
for x in range(11):
print(x)

Eg5: To display odd numbers from 0 to 20 

for x in range(21)
if(x%2!=0):
print(x)

Eg6: To display numbers from 10 to 1 in descending order 

for x in range(10,0,-1)
print(x)

Eg7: To print sum of numbers present  inside first 

list=eval(input(“Enter List:”))
sum=0;
for x in list:
sum=sum+x;
print(“The Sum=“,sum)

D:\Python_classes>test.py 
Enter List:(10,20,30,40)
The Sum=100

D:\Python_classes>py test.py 
Enter List:[45,67]
The Sum= 112 

  1. While Loop 

If we want to execute a group of statements iteratively until some condition false, then  we should go for while loop 

Syntax: while condition:
             body


Eg: To print numbers from 1 to 10 by using while loop 

x = 1 
while x <=10:
print(x)
x = x+1 

Eg: To display the sum of first n numbers

n=int(input(“Enter number:”))
sum=0
i=1
while i<n:
sum=sum+i
i=i+1
print(“The sum of first”,n,”numbers is:”,sum)

Eg: write a program to prompt user to enter some name until entering karthik 

name=“”
while name!=“karthik”:
name=input(“Enter Name:”)
print(“Thanks for confirmation”)

Infinite loops 

i=0;
while True :
i=I+1;
print(“Hello”,i)

Nested loops:
 
Sometimes we can take a loop inside another loop, which are also knowns as nested loops.

for i in range(4):
 for j in range(4):
print(“I=“,I,”  j=“,j)

I=0 j=0
I=0 j=1
I=0 j=2
I=0 j=3
I=1 j=0
I=1 j=1
I=1 j=2
I=1 j=3
I=2 j=0
I=2 j=1
I=2 j=3
I=2 j=4
I=3 j=0
I=3 j=1
I=3 j=2
I=3 j=3 

Write a program to display  *’s in Right angled triangled form  ?
*
**
***
****
*****
******
*******

n =int(input(“Enter number of rows:”))
for i in range(1,n+1):
for j in range(1,i+1):
print(“*”,end=“”)
print()

Alternative way 

n=int(input(“Enter number of rows:”))
for i in range(1,n+1):
print(“*”*i)

Write a program to display  *’s in pyramid style ( Also known as Equivalent triangle )

                                                    *
                                                   * *
                                                  * * *
                                                  * * * *
                                                  * * * * *
                                                  * * * * * *
                                                  * * * * * * *

n = int(input(“Enter number of rows:”))
for i in range(1,n+1):
print(“ “ * (n-i),end=“”)
print(“* “*I)

Transfer statements 

break:

We can use break statement inside loops to break loop execution based on some condition 

for i in range(10):
if I ==7:
print(“Processing Is enough…plz break”)
break
print(i)

 D:\python_classes>py test.py

0
1
2
3
4
5
6
processing is enough…plz break

Eg:

cart=[10,20,600,60,70]
for item in cart:
If item>500:
print(“To place this order insurance must be required”)
break
print(item)

D:\Python_classes>py test.py
10
20
To place this order insurance must be required

Continue 
 
We can use continue statement to skip current iteration and continue next iteration.

Eg1: To print odd numbers in the range of 0 to 9 

for I in range(10):
if I%2==0:
continue
print(i)

D:\Python_classes>py test.py

1
3
5
7
9

Eg2: 

cart=[10,20,500,700,50,60]
for item in cart:
If item>=500:
print(“We cannot process this item:”,item)
continue
print(item)

D:\Python_classes>py test.py
10
20
We cannot process this item:500
We cannot process this item:700
50
60

Eg3:

numbers=[10,20,0,5,0,30]
for n in numbers 
If n==0:
print(“Hey how we can divide with zero..just skipping”)
continue
print(“100/{} = {}”.format(n, 100/n))

Output 

100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero….just skipping
100/5 = 20.0
Hey how we can divide with zero….just skipping
100/30 = 3.333333

Loops with else block 

Inside loop execution, if break statement not executed, then only else part will be executed
Else means loop with break 

cart=[10,20,30,40,50]
for item in cart:
If item>=500:
print(“We cannot process this order”)
break
print(item)
else:
print(“Congrats…all items processed successfully”)

Output

10
20
30
40
50
Congrats…all items processed successfully

Eg: 

cart=[10,20,600,30,40,50]
for item in cart:
If item>=500
print(“We cannot process this order”)
break 
print(item)
else:
print(“Congrats…all items processed successfully”)

Output 

D:\Python_classes>py test.py 
10
20
We cannot process this order 

What is the difference between for loop and while loop in python ?

We can use loops to repeat code execution 
Repeat code for every item in sequence  —> for loop 
Repeat code as long as condition is true —> while loop 

How to exit from the loop ? By using break statement 
How to skip some iterations inside loop ? By using continue statement 
When else part will be executed wrt loops ? If loop executed without break 

Pass statement 

Pass is a keyword in python 
In our programming syntactically if block is required which won’t do anything then we can define that empty block will pass keyword.

pass
  •     It Is an empty statement 
  • It is null statement 
  • It won’t do anything 

Eg: if True
SyntaxError: unexpected EOF while parsing 
If True: pass —> valid 

def m1():

SyntaxError: unexpected EOF while parsing 
def m1(): pass 

Use case of pass 

Sometimes in the parent class we have to declare a function with empty    body and child class responsible to provide proper implementation. Such type of empty body we can define by using pass keyword. ( it is something like abstract method in java).

for I in range(100)
if I%9==0
print(i)
else:pass 

D:\Python_classes>py test.py
0
9
18
27
36
45
54
63
72
81
90
99

del statement:

del is a keyword in python 
After using a variable, it is highly recommended to delete that variable if it is no longer required, so that the corresponding object is eligible for garbage collection.

We can delete variable by using del keyword.

x = 10
print(x)
del x 

After deleting a variable we cannot access that variable otherwise we will get NameError

x = 10
del x 
print(x)

NameError: name ‘x’ is not defined 

Note: we can delete variables which are pointing to immutable objects. But we cannot delete the elements present inside immutable object.

s = “karthik”
print(s)
del s —> valid 
del s[0] —> TypeError: ’str’ object does not support item deletion

Difference b/w del and None 

In the case del, the variable will be removed and we cannot accsss that variable(unbind operation)

s = “karthik”
del s 
print(s) —> NameError: name ’s’ is not defined.

But in the case of None assignment the variable won’t be removed but the corresponding object is eligible for garbage collection ( re bind operation), Hence after assigning with none value, we can access that variable.

s = “karthik”
s = None
print(s) —> None





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