Docsity

Python: Checking PAN Number Validity and String Operations, Slides of Object Oriented Programming

Partial preview of the text

Download Python: Checking PAN Number Validity and String Operations and more Slides Object Oriented Programming in PDF only on Docsity!

Strings in Python

Check Validity of a PAN

In any of the country's official documents, the PAN

number is listed as follows

< alphabet> < alphabet > < alphabet >

< alphabet > < alphabet >

Your task is to figure out if the PAN number is valid or

not. A valid PAN number will have all its letters in

uppercase and digits in the same order as listed

above.

Pseudocode READ PAN If length of PAN is not ten then print “Invalid” and exit FOR x=0 to if PAN[x] is not a character THEN PRINT ‘invalid’ BREAK; END IF END FOR FOR x=5 to 9 if PAN[x] is not a digit THEN PRINT ‘invalid’ BREAK; END IF END FOR IF PAN[9] is not a character THEN PRINT ‘invalid’ END IF PRINT ‘valid’

Test Case 1 abcde1234r Valid

Test Case 3 abcd01234r Invalid

Strings 

Immutable sequence of characters

A string literal uses quotes

'Hello' or "Hello“ or ‘’’Hello’’’

For strings, + means “concatenate”

When a string contains numbers, it is still a string

We can convert numbers in a string into a number

using int()

String Operations

String Operations

Escape Sequences 

Represent Special Characters

>>> s = 'a\nb\tc'

>>> s 'a\nb\tc'

>>> print(s)

a

b c

>>> len(s)

Escape Sequences

Length of a String  —a binary 1 and 2 (coded in octal), followed by a binary 3 (coded in hexadecimal): >>> s = '\001\002\x03' >>> s '\x01\x02\x03' >>> len(s)  3

Backslash in Strings  if Python does not recognize the character after a \ as being a valid escape code, it simply keeps the backslash in the resulting string: >>> x = "C:\py\code" 

Keeps \ literally (and displays it as \)

>>> x 'C:\py\code' >>> len(x) 10

Check this

s = "C:\new\text.dat“

>>>s

print(s)

s1 = r"C:\new\text.dat“

>>>s

print(s1)

s2 = "C:\new\text.dat“

print(s2)

>>>s

Opening a File

 myfile = open('C:\new\text.dat', 'w') - Error  myfile = open(r'C:\new\text.dat', 'w')  Alternatively two backslashes may be used  myfile = open('C:\new\text.dat', 'w')  >>> path = r'C:\new\text.dat'  >>> print(path) # User-friendly format C:\new text.dat  >>> len(path) 15