QEX-SPEPTD-M5
Python:- Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics.
Features of python:-
• Easy to learn & analyze.
• Dynamically typed language.
• Interpreted language.
• Platform indpendent.
• Open source language.
• High-level programming language(easy to understand).
• 7+ crores of library functions.
• More efficient because no. of instructions are very less.
Key words:-
Keywords are the universal standard words whose
task is pre-defined by the developers
• We can access the functionality of a key-word in our program but we can’t modify the original task of
a keyword.
• To get the list of all the keywords we can make use of the syntax:
import keyword
[Link]
['False', 'None', 'True', 'and', 'as', 'assert',
'async', 'await', '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']
• In the above keywords list there are 3 special keywords which starts with uppercase alphabets,they
are 'False', 'None', 'True'
• We can assign 'False', 'None', 'True' as values by
creating variables,but we can’t use other keywords as values.
• All the key-words will be displayed in orange color.
Variables:-
Variable is a name given to a
memory location where we are going to store the value.
Or
Variable is a named memory block
where the value is stored.
The syntax used to create the
variable is:
var_name=value
Memory allocation for variable creation.
• As soon as control see a variable creation process, it will divide the memory into variable space and
value space
• Control will pick the value and it will store into value space, address will be given and that will get
stored with respect to variable name in variable space.
• Variable space is a memory
where we are going to store the address of value and value space is a
place where we are going to store variable value.
id() :-
Id
is a function which is used to get the address of a value stored inside the
memory.
Syntax:- id(var_name/value)
• Multiple Variable Creation:-
It
is a phenomenon of creating multiple variables in a single line.
Syntax:-
var1,var2,var3,var4,....,varn = val1,val2,val3,val4......,valn
Where,
Val1 will get stored into
variable 1,
Val2 will get stored into
variable 2,
Val3 will get stored into
variable 3,
Val4 will get stored into
variable 4,
.
.
Val n will get stored
into variable n,
• In multiple variable creation the number of variables should be equal to the no of values.
•
Identifiers
Identifiers:-
Identifier is a name given to the memory location
to identify the value stored in it.
Rules of identifiers:-
1. Identifiers should not be a keyword.
2. Identifiers should not start with a keyword.
3. Identifiers should not contain space in it.
4. Identifiers should not contain any special characters in it except ‘_’.
5. Identifiers can be alphabet or group of alphabets or alphanumeric.
Data Types
Data Types:
Data type is used
to specify or to determine the type/ the size of the data/value stored in a
particular location/variable.
Based on the size of the
data the data types are classified into 2 categories .
1. Single Value Data
Type:- It is a datatype where we are going to store a single value into a
single variable.
2. Multi-Value Data
Type:- It is a datatype where we are going to store multiple values into a
single variable.
Integer :-
Integer is a real
number without decimal/floating value.
• Integer can be +ve or -ve.
• Each and every data type will have 2 types of values.
Default value:- it is a starting
value which will be internally equal to boolean False.
• Non-Default Value:- other than the
default value all the other values are considered as non-default values, which
is internally equal to boolean True
• Zero(0) is the default value for integer.
type():- type is a function which is used to get the type of
the data/the value stored inside the variable/memory location.
Syntax:- type(var/value)
Float :- (float)
Float is a real
number with decimal point/value
• Float can be either +ve or -ve number.
• 0.0 is the default value for float.
• In float mentioning floating value is mandatory, we can’t ignore decimal value / floating values.
Complex:-
Complex is a
number which consists of both real and imaginary terms.
Or
The number which is in
the form of a+bj / a-bj is known as a complex number.
• In complex number we can’t use any other alphabet/character as a imaginary number except J/j
• If we use J internally it will convert into j
• In complex numbers we can’t rearrange the values of b&j.
• It is not possible to mention an independent j.
• 0j is the default value for complex.
Boolean(bool):-
• Boolean is a data type which consists of only two values, they are True,False
• True is internally considered as integer 1 and False is considered as integer 0.
• Since there are only two values, “True” is considered as non-default value and “False” is considered
as default value.
• Boolean values are used in two scenarios.
1. As a value while creating variables.
2. As a result while checking the
condition.
String (str):-
• String is a collection of characters enclosed between pairs of single or double or triple quotes.
• Syntax to create string variable is:
◦ var_name= 'char1char2….charn’
◦ var_name= “char1char2….charn”
◦ var_name= ‘’’char1char2….charn’’’
Where characters can be either uppercase alphabets or lowercase
alphabets or numeric characters or special characters.
• If we are creating a string with a pair of three single quotes it will be considered as a doc string (multi-
line string).
• In string each and every character will be close to each other, there will be no separation between
characters.
• If we are starting with single quotes we have to end with single quotes only.
• If we are starting with double quotes we have to end with double quotes only.
• If we are starting with triple quotes we have to end with triple quotes only.
• If we are creating the string with double or triple quotes internally, the controller will consider and
store it in the form of single quotes only.
• Whenever we need to create a string containing single quotes then we need to enclose the string
with a pair of double or triple quotes.
• Default value for string is ‘ ’ (no space)
Memory allocation for collection:-
• As soon as control sees a value of collection it will create a layer of memory inside value space,
address will be given & that address will get stored with respect to variable name in variable space.
• The created memory layer will get divided into a number of blocks which is exactly equal to the
length of the collection.
• Each and every value will be picked from the collection and that will get stored with respect to each
and every block of memory one by one continuously.
• Whenever we want to access an individual value/character/data from the collection we have to make
use of a concept called “INDEXING”
Indexing:-
Indexing is a phenomenon of giving sub addresses to each and every block
of memory stored inside the collection.
• There are two type of indexing is there:
1. Positive Indexing:-
whenever we want to travel from left to right of the collection we will make
use of positive indexing.
a. It will start from (0 …….length of
the collection -1)
2. Negative Indexing:-whenever we want to
travel from right to left of the collection we will make use of Negative
indexing.
• It will start from (0 …….length of
the collection -1)
For users convenience we have -ve and +ve indexing but the controller will internally consider +ve
indexing.
• To access the individual value present inside the collection we can make use of the syntax:
var_name[index]
• Based on modification of values inside the collection Data Types got classified into two types.
◦ Mutable Collection:- it
is a collection which will allow the user to modify the original values
in it.
◦ Immutable Collection:- it
is a collection which will not allow the user to modify the original
values in it.
• Since string will not allow the user to modify the values/characters in it, we can call it an Immutable
collection.
List:-
List is a collection of Homogeneous & Heterogeneous collections which is enclosed between a pair
of
square braces.
Homogeneous:-
It is collection which consist of single type of data items in it
Heterogeneous:- It
is collection which consist of multiple type of data items in it
• Syntax to create list item is:
◦ Var_name=[val1,val2,val3,....,val n]
• In list values are separated by , (comma) operator.
• [ ] is default value for list collection.
• Since list allows the user to modify the original values init we call it as a ‘Mutable Collection’.
Tuple:-
Tuple is a collection of Homogeneous & Heterogeneous collections which is enclosed between a
pair of
parentheses.
There are two syntaxes to create a tuple.
1. Var_name=(val1,val2,val3,....,val n)
2. Var_name=val1,val2,val3,....,val n
• Whenever we want to create a tuple with a single value we need to mention the value along with the ,
◦ ex:-var_name=(value,)
• ( ) is the default value for tuple.
• Tuple is the most secured data type in python for data transfer.
• Tuple will not allow the user to modify the original values in it. Because of this reason tuple is used for
secured data transformation.
• Tuple is an immutable collection, because of this reason we don’t have any built-in function to modify
the values
in it.
Set:-
Set is an unordered non duplicate collection of homogeneous or heterogeneous data items
enclosed
between a pair of flower braces.{}
Or
Set is a collection of homogeneous or some
heterogeneous un-ordered non duplicate collection.
syntax:- Var_name={val1,val2,val3,....,val n}
• In set we can’t store the mutable data items in it.
• Since the values will be arranged randomly in the set, indexing is not possible.
• We can’t modify the values in set with the help of indexing, but we can modify the values in set with
values in set with the help of built-in functions.
• Because of the above reason we call set as a mutable collection.
• Set is an immutable collection so that we can’t store set inside the set collection.
• set() is the default value of set collection.
• Set is capable of removing the duplicate values in it, so we can use set for filtration process.
Dictionary:-
Dictionary is a collection of key & Value pairs enclosed between a pair of curly braces {}
Syntax:- Var_name={k1:v1,k2:v2,.....,kn:vn}
• Where key and values are separated by : and key value pairs are separated by , operator.
• We can use only immutable values as keys and values can be either mutable/ immutable.
• Dictionary will not accept duplicate keys, if we try to store the duplicate keys it overwrites the
previous value with the new value.
• {} is the default value for a dictionary.
• Dictionaries will not support indexing.
• To get the values present inside the dictionary we can make use of a syntax:- var_name[key]
• To modify the value present inside the dictionary, we have to make use of keys, and the syntax is:-
var_name[key]=new_value.
Memory allocation for dictionary:-
• As soon as control sees a process of dictionary creation it divides the memory into two layers inside
the memory.
• (i) Key Layer
(ii)Value Layer
• Address will be given to the key layer and that address will be stored with respect to variable name in
variable space.
• All the values will be stored in the value layer with respect toi keys.
• Syntax to add key value pair to a dictionary:-
◦ Var_name[new key]=new value
Slicing:-
Slicing is a phenomenon of extracting the group of data items from the existing collection.
The syntax used for slicing is:-
var_name[Starting index: Ending index+/-1:Updation]
• Without indexing we can’t perform slicing.
• Slicing can be done only on string, list, tuple items only.
• Since indexing is not present in set and dictionary we can’t perform slicing.
• If we perform slicing on string the o/p will be in the form of string and the same will be for list and
tuple.
• While traveling from left to right of the collection we should use ending index+1, from right to left of
the collection we should use ending index-1
Slicing on the dictionary.
• We can’t apply slicing on dictionary directly because dictionary will not support indexing, but we can
apply slicing on dictionary when we have a values of dictionaries in the form of string or list or tuple
Type Conversion
•
Type conversion is a phenomenon of converting the data of one type to another type based on the
user requirement.
• Syntax:- destination_variable=destination data type(source_variable)
[Link] of integer(int) to other types:-
Source Type Destination Type
Source_type: int int(a) →92(no use)
a=92 float(a) →92.0
Type(a)=int complex(a) →92+0j
bool(a) →True
str(a) → ‘92’
list(a) →Error
tuple(a) →Error
set(a) →Error
dict(a) →Error
[Link] of float(float) to other types:-
Source Type Destination Type
Source type: float int(a) →25
a=25.6 float(a) →25.6(no use)
Type(a)=float complex(a) →25.6+0j
bool(a) →True
str(a) → ‘25.6’
list(a) →Error
tuple(a) →Error
set(a) →Error
dict(a) →Error
[Link] of Complex(complex) to other types:-
Source Type Destination Type
Source_type: complex int(a) →Error
a=18+6j float(a) →Error
Type(a)=complex complex(a) →18+6j(no use)
bool(a) →True
str(a) → ‘18+6j’
list(a) →Error
tuple(a) →Error
set(a) →Error
dict(a) →Error
[Link] of Boolean(bool) to other types:-
Source Type Destination Type Destination Type
Source_type: bool int(a) →1 int(b) →0
a=True float(a) →1.0 float(b) →0.0
b=False complex(a) →1+0J complex(b) →0+0j(no use)
Type(a)=bool bool(a) →True(no use) bool(b) →False
Type(b)=bool str(a) → ‘True’ str(b) → ‘False’
list(a) →Error list(a) →Error
tuple(a) →Error tuple(a) →Error
set(a) →Error set(a) →Error
dict(a) →Error dict(a) →Error
[Link] of String(str) to other types:-
Source Type Destination Type Destination Type
Source_type:String int(a) →35 int(b) →Error
a= ‘35’ float(a) →35.0 float(b) →Error
b= ‘abc’ complex(a) →35+0J complex(b) →Error
Type(a)=str bool(a) →True bool(b) →True
Type(b)=str str(a) → ‘35’ str(b) → ‘abc’
list(a) →['3', '5'] list(a) →['a', 'b', 'c']
tuple(a) →('3', '5') tuple(a) →('a', 'b', 'c')
set(a) →{'3', '5'} set(a) →{'a', 'c', 'b'}
dict(a) →Error dict(a) →Error
[Link] of
List(list) to other types:-
Source Type Destination Type Destination Type
Source_type:LIst int(a) →Error int(b) →Error
a= [1,2,3,4] float(a) →Error float(b) →Error
b= [[1,2],[3,4]] complex(a) →Error complex(b) →Error
Type(a)=list bool(a) →True bool(b) →True
Type(b)=list str(a) → ‘[1,2,3,4]’ str(b) → ‘[[1,2],[3,4]]’
list(a) →[1,2,3,4] list(a) →[[1,2],[3,4]]
tuple(a) →(1,2,3,4) tuple(a) →([1,2],[3,4])
set(a) →{1,2,3,4} set(a) →Error
dict(a) →Error dict(a) →{1:2,3:4}
[Link] of Tuple(tuple) to other types:-
Source Type Destination Type Destination Type
Source_type:Tuple int(a) →Error int(b) →Error
a= (1,2,3,4) float(a) →Error float(b) →Error
b= ((1,2),(3,4)) complex(a) →Error complex(b) →Error
Type(a)=tuple bool(a) →True bool(b) →True
Type(b)=tuple str(a) → ‘(1,2,3,4)’ str(b) → ‘((1,2),(3,4))’
list(a) →[1,2,3,4] list(a) →[(1,2),(3,4)]
tuple(a) →(1,2,3,4) tuple(a) →((1,2),(3,4))
set(a) →{1,2,3,4} set(a) →{(1, 2),
dict(a) →Error
(3, 4)}
dict(a) →{1:2,3:4}
[Link] of
Set(set) to other types:-
Source Type Destination Type Destination Type
urce_type:set int(a) →Error int(b) →Error
a= {1,2,3,4} float(a) →Error float(b) →Error
b= {(1,2),(3,4)} complex(a) →Error complex(b) →Error
Type(a)=set boole(a) →True boole(b) →True
Type(b)=set str(a) → ‘{1,2,3,4}’ str(b) →‘((1,2),(3,4))’
list(a) →[1,2,3,4] list(a) →{(1,2),(3,4)}
tuple(a) →(1,2,3,4) tuple(a) →((1,2),(3,4))
set(a) →{1,2,3,4} set(a) →{(1, 2),
dict(a) →Error
(3, 4)}
dict(a) →{1:2,3:4}
Operators:-
operator:- operator is a special symbol which is used to perform some specific task/ Operation.
operand:- operand is the input to the expression to perform the operation.
In python operators are classified into 7 Types:-
1. Arithmetic operators. [+, -, *, /, //, %, **]
2. Logical operators. [and, or, not]
3. Bitwise operators. [&, |, ~,^, >>, <<]
4. Relational operators. [>, <, >=, <=, ==, !=]
5. Assignment operators. [=]
6. Membership operators. [in, not in]
7. Identity operators. [is, is not]
Arithmetic operator:-(+, -, *, **, /, //, %)
1. Addition operator (+):-
• It is an operator which is used to find the sum of two or more operands.
◦ syntax:-
▪ operand1 + operand 2 (addition operation)
▪ collection 1 + collection 2 (concatenation)
concatenation:-
• concatenation is a phenomenon of adding/ merging two collections
• while performing concatenation both the operands should be of same data type
• operand1 - operand2
Subtraction(-):-
it is an operator which is used to find the difference between two or
more operands
Syntax:-
1. Subtraction operator will support for all the individual data types and only for set
2. True Division(/)
3. Floor Division (//)
4. Modules (%)
Multiplication (*):-
It is an operator which is used to find the product of two or more operands.
Syntax:-
• operand 1 * operand 2 (only for single value data types)
• Collection * n (n should be integer for collection)
we can multiply one single value data type with another single value data type, in case of collections we
can multiply only with integer data type
Division :-
in python division operators are classified into 3 types:
True Division(/):-
• It is a division operator which is used to get the exact division output
• it will support all the single value data types but it will not support collection data types.
Floor Division:-
• it is a division operator which is used to get the exact division output by removing decimal value
• it will support only int & float.
Modules :-
• it is an operator which is used to get the remainder of the division output.
• it will support only int & float.
Power Operator:-
• it is an operator which is used to multiply the given operand(number) for n no. of times.
• syntax:-
◦ operand ** n
◦ where n should be single value only
Logical Operators:- (and, or, not)
Logical And Operator:-
• and is an operator which will return the result as true, if both the operands/ conditions are true, else it
returns False
• The syntax is:-
◦ operand1 and operand 2
• if operand 1 is True the output will be the operand 2
• if operand 1 is False the output will be the operand 1
Logical Or Operator(or):-
• or is an operator which will return the output as True, if any of the conditions is true, and it returns
False if Both the conditions are False.
• Syntax:-
operand1 or operand
2
◦ if operand 1 is True the output will be the operand 1
◦ if operand 1 is False the output will be the operand 2
Logical Not Operator:-
• not is an unary operator which will return the result as True, if the given input is internally False, and it
will return the result as False, If the given input is internally True.
• Syntax:-not(Operand/ Condition)
Relational operators:-[>, <, >=, <=, ==, != ]
These are the operators which are used to find the relation between two or more operands.
[Link] Equal to operator:-(==)
It is an operator which will return the Result as
True, if both operands are equal to each other, else it returns the result as False
[Link] not Equal to operator:-(!=)
It is an operator which will return the result as
True , if both the operands are opposite to each other, else it returns False
ASCII:- American Standard Code For Information Interchange
ord Function:- IT is a built in Function which is used to find the ASCII value of a specific character.
chr Function :-
it is a built in function which is used to find the character of a specific ASCII number
[Link] Greater Than operator:-(>)
It is an operator which will return the result as
True, if the operand 1 is grater then the operand 2, else it returns False.
• if the operands are collections it compares the first element of the first collection and the first
element of the second collection.
• if the operands are strings it compares the ASCII value of the first character of the first string and the
ASCII value of the first character of the second String.
[Link] Less Than operator:-(<)
It is an operator which will return the result as
True, if the operand 1 is Less then the operand 2, else it returns False.
• if the operands are collections it compares the first element of the first collection and the first
element of the second collection.
• if the operands are strings it compares the ASCII value of the first character of the first string and the
ASCII value of the first character of the second String.
[Link] Greater Than Or Equal to operator:-(>=)
It is an operator which will return the result as
True if the operand 1 == operand 2 or if operand 1 > operand 2, else it
returns False
[Link] Less Than Or Equal to operator:-(<=)
It is an operator which will return the result as
True if the operand 1 == operand 2 or if operand 1 < operand 2, else it
returns False
Identity Operators:- (is, is not)
it is an operator which is used to check whether
both the operands are pointing to the same memory location or not.
Identity Is Operator:
it is an operator which will return the result as true if both the operands are pointing to the same memory
location, else it
returns the result as False.
Identity is not:
it is an operator which will return the result as True if both operands are pointing to different memory
locations.
Bitwise Operator:-
It is an operator which will convert the given integer numbers in the form of binary and performs each
operation by considering bit by bit, and it returns the output in the form of integer.
Bit-wise operators are classified into 6 types:-
1. Bitwise and (&)
2. Bit-wise or (|)
3. Bit-wise not (~)
4. Bit-wise xor (^)
5. Bit-wise right shift (>>)
6. Bit-wise left shift (>>)
Bit-wise and (&):-
It is an operator which will convert the given numbers in the form of binary and performs logic and
operation by considering bit by bit, and returns the output in the form of integer.
Bit-wise or (|):-
It is an operator which will convert the given numbers in the form of binary and performs logical or
operation by considering
bit by bit, and returns the output in the form of integer.
Bit-wise not (~) :-
It is an unary operator which will accept only one operand at RHS and returns the output in the form of -
(N+1).
Bit-wise xor (|):-
It is an operator which will convert the given integer numbers in the form of binary and performs xor
operation by considering
bit by bit, and it returns the output in the form of integer number.
Bit-wise Right Shift:- (>>)
It is an operator which will convert the given number in the form of binary and shift the binary values to
the RHS for no. of
steps and returns the result in the form of integer.
Bit-wise Left Shift:- (>>)
It is an operator which will convert the given number in the form of binary and shift the binary values to
the LHS for no. of
steps and returns the result in the form of integer.
Assignment operators:- (=)
It is an operator which is used to assign somevalue to a variable
Ex:- +=, -=, *=, >>=,..........
Membership operators. :-[in, not in]
It is an operator which is used to check whether the given collection is present in the given collection or
not.
Membership in operator:-(in)
it is an operator which will return the result as True if the sub collection is present in the collection, else it
returns the
result as False.
Membership not in operator:-(not in)
it is an operator which will return the result as True if the sub collection is not present in the collection,
else it returns
the result as False.
Copy Operations:-
It is a phenomenon of copying the content of one variable to another variable.
Classified in 3 types:
1. General Copy
2. Shallow Copy
3. Deep Copy
[Link] Copy:-
It is a phenomenon of copying the address of one variable to another variable.
• Syntax:-
◦ destination_var = Source variable
• In the case of General copy the modification with respect to one variable will affect the other variable.
2. Shallow Copy:-
It is a phenomenon of copying the linear layer of one variable to another variable.
• Syntax:-
◦ destination_var = source_var.copy()
• in case of shallow copy modification with respect to values /linear layer of one variable will not affect
the another variable,
• but modification with respect to nested values / layer will affect the another variable
[Link] copy:-
It is a phenomenon of copying the entire content of one variable to
another variable as a new value.
• syntax:-
◦ import copy
destination_var
= [Link](source_var)
• in case of deep copy modification with respect to one variable will not affect another variable either
in linear or in nested
Control Statements:-
control statements are the instructions which are used to control the
flow of execution of a program
• Control Statements are classified into two types
◦ 1. Decitional Statements/ Conditional Statements
◦ 2. Looping Statements.
Decisional Statements:-
Simple IF
It is a keyword which is used to check whether the
given condition is True or False.
• if the condition is True it executes True Statement Block(TSB)
• if the given condition is False it comes out of the statement block
• Whenever we have a single condition and a single statement to execute those cases we can make
use of a simple if statement.
if else:-
for a single condition whenever we have two set of statement blocks then
we can make use of if else statements
in this case if the condition is True it executes True Statement
Block(TSB),
if the condition is False it executes False Statement Block(FSB)
elif:-
Whenever we have multiple conditions and a set of
statement blocks for every condition that time we can make use of elif
statements.
• elif will start with if condition & it will end with else block.
• writing else block is not mandatory
• if first condition is True it executes TSB1 and come out of the if statement block,
• if the first condition is false it checks the second condition
• if the second condition is True it executes TSB2 and come out of the statement block
• if none of the conditions are True it executes False Statement Block(FSB)/ Default Statement
Block(DSB)
Auto (Python)
a = int(input('enter the number:'))
b = int(input('enter the number:'))
print('a is a positive number')
print('b is a positive number')
print('hiii how are you')
# WAP to check whether the entered number is positive or not.
a = int(input('enter the number:')) #-9
if a >= 0:
print('the enterd number is a positive number')
print('hii good morning')
# WAP to check whether the entered number is even or not
a = int(input('enter the number:'))
if a % 2 == 0:
print('the entered number is a even number')
# WAP to check whether the entered character is vowel or not.
a = input('enter the string:')
if a in 'AEIOUaeiou':
print('the entered character is vowel character')
# WAP to check whether the entered character is uppercase alphabet or not.
a = input('enter the charcter:')
if 'A' <= a <= 'Z': # 'A' <= and a <= 'Z'
print('the entered characte is an uppercase alphabet')
# WAP to check whether the entered character is lowercase alphabet or not
a = input('enter the string:')
if 'a' <= a <= 'z':
print('the entered character is a lowercase alphabet')
# WAp to check whether the entere character is numerical charcter or not.
a = input('enter the chacracter:')
if '0' <= a <= '9':
print('the entered character is a numerical character')
# WAp to check whether the entered number is posotive or negative
a = int(input('enter the number:'))
if a >= 0:
print('the entered number is a positive number')
else:
print('the entered number is a negative number')
# WAP to check whether the entered number is even or odd.
a = int(input('enter the number:'))
if a % 2 == 0:
print('the entered number is a even number')
else:
print('the entered number is a odd number')
# WAP to check whether the entered character is vowel or consonent.
a = input('enter the character:')
if a in 'AEIOUaeiou':
print('the entered character is a vowel character')
else:
print('the entered character is a consonant')
# WAp to find the greatest number among the given two numbers.
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
if a > b:
print('a is a greatest number')
elif b > a:
print('b is a greatest number')
elif a == b:
print('both the entered numbers are same')
# WAP to find the type of a entered character
a = input('enter the character:')
if 'A' <= a <= 'Z':
print('the entered character is an uppercase alphabet')
elif 'a' <= a <= 'z':
print('the entered character is a lowercase alphabet')
elif '0' <= a <= '9' :
print('the entered charcater is a numerical character')
else:
print('the entered character is a special character')
# WAP to find the greatest among 3 numbers.
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
c = int(input('enter the number 3:'))
if a > b and a > c:
print('a is the greatest number')
elif b > c:
print('b is the greatest number')
else:
print('c is the greatest number')
# WAP to find the greatest among 5 numbers.
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
c = int(input('enter the number 3:'))
d = int(input('enter the number 4:'))
e = int(input('enter the number 5:'))
if a > b and a > c and a > d and a > e:
print('a is the greatest number')
elif b > c and b > d and b > e:
print('b is the greatest number')
elif c > d and c > e:
print('c is the greatest number')
elif d > e:
print('d is the greatest number')
else:
print('e is the greatest number')
# WAP to check whether the entered character is uppercase alphabet or not.
a = input('enter the character:')
if 'A' <= a <= 'Z' or 'a' <= a <= 'z':
if 'A' <= a <= 'Z':
print('the entered character is uppercase alphabet')
else:
print('the entered character is alphabet but not an uppercase alphabet')
else:
print('entered character is not at all an alphabet')
# WAP to find the second greatest number among 4 numbers
a = int(input('enter the numbmer:'))
b = int(input('enter the numbmer:'))
c = int(input('enter the numbmer:'))
d = int(input('enter the numbmer:'))
if a > b and a> c and a > d:
if b > c and b > d:
print('b is the second greatest number')
elif c > d:
print('c is the second greatest number')
else:
print('d is the second greatest number')
elif b > c and b > d:
if a > c and a > d:
print('a is the second greatest number')
elif c > d:
print('c is the second greatest number')
else:
print('d is the second greatest number')
elif c > d:
if a > b and a > d:
print('a is the second greatest number')
elif b > d:
print('b is the second greatest number')
else:
print('d is the second greatest number')
else:
if a > b and a > c:
print('a is the second greatest number')
elif b > c:
print('b is the second greatest number')
else:
print('c is the second greatest number')
Looping Statements: - These are the control statements which are used to execute a set of instructions
again and again
While loop :
While loop is a looping statement which is used to execute a set of instructions again and again untill the
given termination condition becomes false
Auto (Python)
# Looping Statements: - These are the control statements which are used to
execute a set of instructions again and again
# While loop :
# While loop is a looping statement which is used to execute a set of
instructions again and again untill the given termination condition becomes false
# For loop
# Print Hello world for 5 times
i = 0
while i < 5:
print('Hello world')
i += 1
# WAP to print first 10 natural numbers.
i = 1
while i <= 10:
print(i)
i += 1
# WAP to print first n natrual numbers
n = int(input('enter the number:'))
i = 1
while i <= n:
print(i)
i += 1
# WAP to print all the even numbers from 10 to 25
n = 10
while n <= 25:
if n % 2 == 0:
print(n)
n += 1
# WAP to print all the odd numbers in between the user entered limits.
s = int(input('enter the number:'))
e = int(input('enter the number:'))
i = s
while i <= e:
if i % 2 == 1: # i % 2 != 0
print(i)
i += 1
# # WAP to print the multiplication table of a user entered number
# # n = 2
# 2 * 1 = 2
# 2 * 2 = 4
# 2 * 3 = 6
# .
# .
# 2 * 10 = 20
Auto (Python)
# # WAP to print the multiplication table of a user entered number
# # n = 2
# 2 * 1 = 2
# 2 * 2 = 4
# 2 * 3 = 6
# .
# .
# 2 * 10 = 20
n = int(input('enter the number:'))
i = 1
while i <= 10:
print(n, '*', i, '=', n*i)
i += 1
# WAP to print all the characters from the given string.
a = 'python'
i = 0
while i < len(a):
print(a[i])
i += 1
# WAP to print all the uppercase alphabets from the given string.
a = input('enter the string:')
i = 0
while i < len(a):
if a[i].isupper(): # 'A' <= a[i] <= 'Z'
print(a[i])
i += 1
# WAP to print all the lowercase alphebets from the given string
a = input('enter the string:')
i = 0
while i < len(a):
if 'a' <= a[i] <= 'z':
print(a[i])
i += 1
# WAP to print all the numerical characters from the given string.
a = input('enter the string:')
i = 0
while i < len(a):
if '0' <= a[i] <= '9':
print(a[i])
i += 1
# WAP to print all the special characters from the given string.
a = input('enter the string:')
i = 0
while i < len(a):
if not('A' <= a[i] <= 'Z' or 'a' <= a[i] <= 'z' or '0' <= a[i] <= '9'):
print(a[i])
i += 1
# WAP to copy all the characters from ont variable to another variable.
a = input('enter the string:')
b = ''
i = 0
while i < len(a):
b += a[i]
i += 1
print(b)
# WAP to extract all the uppercase alphabets from the given string.
a = input('enter the string:')
res = ''
i = 0
while i < len(a):
if 'A' <= a[i] <= 'Z':
res += a[i]
i += 1
print(res)
# WAP to extract all the Special characters from the given string.
a = input('enter the string:')
res = ''
i = 0
while i < len(a):
if not('A' <= a[i] <= 'Z' or 'a' <= a[i] <= 'z' or '0' <= a[i] <= '9'):
res += a[i]
i += 1
print(res)
# WAP to convert all the uppercase alphabets into lowercase alphabets in the
given string.
a = input('enter the string:')
res = ''
i = 0
while i < len(a):
if 'A' <= a[i] <= 'Z':
res += chr(ord(a[i])+32)
else:
res += a[i]
i += 1
print(res)
# WAP to convert all the lowercase alphabets from the given into Uppercase.
a = input('enter the string:')
res = ''
i = 0
while i < len(a):
if 'a' <= a[i] <= 'z':
res += chr(ord(a[i])-32)
else:
res += a[i]
i += 1
print(res)
# WAP to remove all the repeated characters from the given string.
a = 'Banana'
res = ''
i = 0
while i < len(a):
if a[i] not in res:
res += a[i]
i += 1
print(res)
# # WAP to separate all the characters from the given string
# a = input('enter the string:')
# uc = ''
# lc = ''
# nc = ''
# sc = ''
# # WAP to replace the white space" " with underscore in the given string.
# i/p: - 'Python is easy'
# o/p: - 'python_is_easy'
Auto (Python)
# WAP to separate all the characters from the given string
a = input('enter the string:')
uc = ''
lc = ''
nc = ''
sc = ''
i = 0
while i < len(a):
if 'A' <= a[i] <= 'Z':
uc += a[i]
elif 'a' <= a[i] <= 'z':
lc += a[i]
elif '0' <= a[i] <= '9':
nc += a[i]
else:
sc += a[i]
i += 1
print(uc)
print(lc)
print(nc)
print(sc)
# WAP to replace the white space" " with underscore in the given string.
# i/p: - 'Python is easy'
# o/p: - 'python_is_easy'
a = input('enter the string:')
res = ''
i = 0
while i < len(a):
if a[i] == ' ':
res += '_'
else:
res += a[i]
i += 1
print(res)
# WAP to extract all the even numbers from in between user entered limits
s = 10
e = 20
res = []
i = s
while i < e+1:
if i % 2 == 0:
res += [i]
i += 1
print(res)
# WAP to extract all the divisors of a given number
n = int(input('enter the number:'))
res = []
i = 1
while i < n:
if n % i == 0:
res += [i]
i += 1
print(res)
# WAP to check whether the entered number is a prime number or not.
n = int(input('enter the number:'))
res = []
i = 1
while i < n:
if n % i == 0:
res += [i]
i += 1
if len(res) == 1:
print('the entered number is a prime number')
else:
print('the entered number is not a prime number')
# WAP to check whether the entered number is a perfect number or not.
n = int(input('enter the number:'))
res = []
i = 1
while i < n:
if n % i == 0:
res += [i]
i += 1
if sum(res) == n:
print('the entered number is a perfect number')
else:
print('the entered number is not a perfect number')
# WAP to check whether the entered numbers are amicable or not
a = int(input('enter the number:'))
b = int(input('enter the number:'))
c = []
d = []
i = 1
while i < a:
if a % i == 0:
c += [i]
i += 1
j = 1
while j < b:
if b % j == 0:
d += [j]
j += 1
if sum(d) == a and sum(c) == b:
print('the entered numbers are micable numbers')
else:
print('the entered numbers are not an amicable numbers')
# WAP to find the sum of individual digits of a given number
n = int(input('enter the number:'))
res = 0
i = n
while i > 0:
res += i % 10
i //= 10
print(res)
# WAP to check whether the entered number is armstrong or not.
Auto (Lua)
# WAP to check whether the entered number is armstrong or not.
n = int(input('enter the number:'))
res = 0
p = len(str(n))
i = n
while i > 0:
res += (i % 10)**p
i //= 10
if res == n:
print('the entred number is an armstrong number')
else:
print('the entered number is not an armstrong number.')
# WAP to print first 10 fibonacci series numbers.
i, a, b = 0, 0, 1
while i < 50:
print(a)
c = a + b
a = b
b = c
i += 1
# # WAP to find the sum of first n natrual numbers.
n = int(input('enter the number:'))
res = 0
i = 1
while i <= n:
res += i
i += 1
print(res)
# WAP to print the factorial of a given number
n = int(input('enter the number:'))
res = 1
i = 1
while i <= n:
res *= i
i += 1
print(res)
a =['steve', 'blake', 'miller', 'martin', 'mike', 'punith', 'likith']
# res = {'steve': 5, 'blake': 5, 'miller': 6, 'martin': 6, 'mike': 4, 'punith':
6, 'likith': 6}
i = 0
res = {}
while i < len(a):
res[a[i]] = len(a[i])
i += 1
print(res)
a =['steve', 'blake', 'miller', 'martin', 'mike', 'punith', 'likith']
# res = {'steve': [5, 'steve'], 'blake': [5, 'blake'], 'miller': [6, 'miller'],
# 'martin': [6, 'martin'], 'mike': [4, 'mike'], 'punith': [6, 'punith'],
# 'likith': [6, 'likith']}
i = 0
res = {}
while i <len(a):
res[a[i]] = [len(a[i]), a[i]]
i += 1
print(res)
a =['steve', 'blake', 'miller', 'martin', 'mike', 'punith', 'likith']
# res = {'steve': [5, 'steve'], 'blake': [5, 'blake'], 'miller': [6, 'relli'],
# 'martin': [6, 'nitram'], 'mike': [4, 'ekim'], 'punith': [6, 'htinup'],
# 'likith': [6, 'htikil']}
res = {}
i = 0
while i < len(a):
if len(a[i]) % 2 == 0:
res[a[i]] = [len(a[i]), a[i][::-1]]
else:
res[a[i]] = [len(a[i]), a[i]]
i += 1
print(res)
a =['steve', 'miller', 'martin', 'mike', 'punith', 'blake', 'likith']
# res = {5: ['steve', 'blake'], 6: ['miller', 'martin', 'punith', 'likith'], 4:
['mike']}
res = {}
i = 0
while i < len(a):
if len(a[i]) not in res:
res[len(a[i])] = [a[i]]
else:
res[len(a[i])] += [a[i]] # res[len(a[i])] = res[len(a[i])] + [a[i]]
i += 1
print(res)
a =['steve', 'miller', 'martin', 'mike', 'punith', 'blake', 'likith', 'frank',
'facebook'
'tuna', 'lina', 'meena', 'seena', 'shiva', 'hari', 'krishna', 'bhanu',
'manu', 'sunith']
# res = {'s': ['steve', 'seena', 'shiva', 'sunith'], 'm':['miller', 'martin',
'mike', 'meena', 'manu'],
# 'p': ['punith'], 'b': ['blake', 'bhanu'], 'l': ['likith', 'lina']}
res = {}
i = 0
while i < len(a):
if a[i][0] not in res:
res[a[i][0]] = [a[i]]
else:
res[a[i][0]] += [a[i]] # res[a[i][0]] = res[a[i][0]] + [a[i]]
i += 1
print(res)
a = ['a', 'b', 'c', 'd'] # ['a', 'b', 'c', 'd', 'e', 'f']
b = [1, 2, 3, 4, 5]
# res = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
res = {}
i = 0
while i < len(a) and i < len(b):
res[a[i]] = b[i]
i += 1
print(res)
intermediate terminations of a loop:-
These are the statements which are used to terminate the loop in between as per the user requirement.
We use Break, continue, pass keywords to terminate the loop in between
break: - it is a keyword which is used to terminate the loop in between.
if controller see a keyword called break it will come out of the loop immediately.
Continue: - it is a keyword which is used to skip one iteration of a loop for one time.
if controller see a keyword called continue it will skip all the instructions of the loop for that iteration
pass: - it is a keyword which is used to make any empty indentive block as a valid block.
Auto (Python)
n = int(input('enter the number'))
i = 2
while i < n:
if n % i == 0:
print(i)
break
i += 1
n = int(input('enter the number:'))
i = 2
while i <= n // 2:
if n % i == 0:
print('The entered number is not a prime number')
break
i +=1
else:
print('the entered number is a prime number')
n = int(input('enter the number:'))
i = 1
while i <= n:
if i % 2 == 0:
i += 1
continue
else:
print(i)
i += 1
i = 1
while i <= 10:
pass
username = 'likith_1003'
password = '12345abcd'
un = input('enter the uername:')
if un == username:
pw = input('enter the password')
if pw == password:
print('Logged in Successfully')
else:
print('Invalid Password')
else:
print('User Not Found')
For loop : - for loop is a looping statement which is used to execute a set of instructions by traversing
through each and every element of the collection
Range function: -
range is a function which is used to generate a sequence of numbers in between the user entered limits
# Forloop : - forloop is a looping statement which is used to execute
Auto (Python)
# a set of instructions by traversing through each and every element
# of the collection
# WAP to print all the characters of a given string.
a = 'python'
i = 0
while i < len(a):
print(a[i])
i += 1
a = 'python'
for i in a:
print(i)
# WAP to print all the uppercase alphabets from the given string.
s = input('enter the string:')
for i in s:
if 'A' <= i <= 'Z':
print(i)
# WAP to check whether the entered string is a palindrome or not.
a = input('enter the string')
res = ''
for i in a:
res = i + res
if res == a:
print('the entered string is a palindrome')
else:
print('the entered string is not a palindrome')
for i in range(1, 11):
print(i)
# WAP to extract all the even numbers iin between the user entered limits.
s = int(input('enter the number:'))
e = int(input('enter the number:'))
res = []
for i in range(s, e+1):
if i % 2 == 0:
res += [i]
print(res)
# Divisors
# Prime number
# perfect number
# amicable number
# sum of first n natural numbers
# Factorial of a number
Date: - 18/Dec/2024
Auto (Python)
# Divisors
n = int(input('enter the numbmer:'))
d = []
for i in range(1, n//2+1):
if n % i == 0:
d += [i]
print(d)
# Prime number
n = int(input('enter the numbmer:'))
d = []
for i in range(1, n//2+1):
if n % i == 0:
d += [i]
if len(d) == 1:
print('the entered number is a prime number')
else:
print('the entered number is not a prime number')
# perfect number
n = int(input('enter the numbmer:'))
d = []
for i in range(1, n//2+1):
if n % i == 0:
d += [i]
if sum(d) == n:
print('the entered number is a perfect number')
else:
print('the entered number is not a perfect number')
# amicable numbers
a = int(input('enter the number 1:'))
c = []
for i in range(1, a//2+1):
if a % i == 0:
c += [i]
b = int(input('enter the number 2:'))
d = []
for j in range(1, b//2+1):
if b % j == 0:
d += [j]
if sum(d) == a and sum(c) == b:
print('the entered numbers are amicable numbers')
else:
print('the entered numbers are not an amicable numbers')
# sum of first n natural numbers
n = int(input('enter the number:'))
s = 0
for i in range(1, n+1):
s += i
print(s)
# Factorial of a number
n = int(input('enter the number:'))
s = 1
for i in range(1, n+1):
s *= i
print(s)
creds = [{'username': 'likith_1003', 'password': '1234abcd'},
{'username': 'punith_1234', 'password': 'abcd1234'},
{'username': 'allen_6543', 'password': 'allinuin'},
{'username': 'praveen_8520', 'password': '8520@praveen'},
{'username': 'shaila_1234', 'password': '1234@shaaila'}
]
un = input('enter the username:')
for i in creds:
if i['username'] == un:
pw = input('enter the password:')
if i['password'] == pw:
print('Logged in Successfull')
else:
print('invalid Password')
break
else:
print('User Not Found')
a =['steve', 'miller', 'martin', 'mike', 'punith', 'blake', 'likith',
'frank', 'facebook', 'tuna', 'lina', 'meena', 'seena', 'shiva',
'hari', 'krishna', 'bhanu', 'manu', 'sunith']
vowels = ''
for i in a:
for j in i:
if j in 'AEIOUaeiou':
vowels += j
print(vowels)
# WAP to extract all the prime numbers from 1 to 100
primes = []
for i in range(1, 101):
d = []
for j in range(1, i//2+1):
if i % j == 0:
d += [j]
if len(d) == 1:
primes += [i]
print(primes)
# WAP to extract all the perfect numbers from 1 to 1000.
perfects = []
for i in range(1, 1001):
d = []
for j in range(1, i//2+1):
if i % j == 0:
d += [j]
if sum(d) == i:
perfects += [i]
print(perfects)
# 11 12 13 14 15
# 21 22 23 24 25
# 31 32 33 34 35
# 41 42 43 44 45
# 51 52 53 54 55
for i in range(1, 6):
for j in range(1, 6):
print(i,j, sep='', end=' ')
print()
# * * * * *
# * * * * *
# * * * * *
# * * * * *
# * * * * *
for i in range(1, 6):
for j in range(1, 6):
print('* ', end=' ')
print()
# *
# * *
# * * *
# * * * *
# * * * * *
for i in range(1, 6):
for j in range(1, 6):
if i >= j:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# * * * * *
# * * * *
# * * *
# * *
# *
for i in range(1, 6):
for j in range(1, 6):
if i <= j:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# * * * * *
# * * * *
# * * *
# * *
# *
for i in range(1, 6):
for j in range(1, 6):
if i + j <= 6:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# * *
# * *
# *
# * *
# * *
#
for i in range(1, 6):
for j in range(1, 6):
if i == j or i + j == 6:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
#
# * * *
# * * *
# * * *
#
for i in range(1, 6):
for j in range(1, 6):
if not(i in (1, 5) or j in (1, 5)):
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# * * * * *
# * *
# * *
# * *
# * * * * *
for i in range(1, 6):
for j in range(1, 6):
if i in (1, 5) or j in (1, 5):
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# *
# * * * * *
# *
# *
for i in range(1, 6):
for j in range(1, 6):
if i == 3 or j == 3:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# * * *
# * * * * *
# * * *
# *
for i in range(1, 6):
for j in range(1, 6):
if (i == 3 or j == 3) or (not(i in (1, 5) or j in (1, 5))):
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# * * *
# * * * * *
# *
# *
#
for i in range(1, 6):
for j in range(1, 6):
if (i == 3 or j == 3) or (not(i in (1, 5) or j in (1, 5))) and i <= 3:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# *
# * * * * *
# * * *
# *
#
for i in range(1, 6):
for j in range(1, 6):
if (i == 3 or j == 3) or (not(i in (1, 5) or j in (1, 5))) and i >= 3:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# * *
# * * * * *
# * *
# *
for i in range(1, 6):
for j in range(1, 6):
if (i == 3 or j == 3) or (not(i in (1, 5) or j in (1, 5))) and j >= 3:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
# *
# * *
# * * * * *
# * *
# *
for i in range(1, 6):
for j in range(1, 6):
if (i == 3 or j == 3) or (not(i in (1, 5) or j in (1, 5))) and j <= 3:
print('* ', end=' ')
else:
print(' ', end=' ')
print()
1. WAP to count the number of times a character is repeated in the give string.
a = 'aaabbccdada'
o/p:- 'a5b2c2d2'
2. String occurrence
a = 'aaabbccdada'
o/p:- 'a3b2c2d1a1d1a1'
3. WAP to check whether the entered string is anagram or not.
4. WAP to convert an integer number into binary number.
5. WAP to convert a binary number into an integer number.
Auto (Python)
a = 'aaabbccdada'
res = ''
for i in a:
if i not in res:
res += i+str([Link](i))
print(res)
a = input('enter the string:')
b = input('enter the string:')
for i in a:
if len([Link](i,'')) == len([Link](i, '')):
continue
else:
print('the entred string is not a anagram')
break
else:
print('the entered string is anagram')
[Link] to print all the values in a tuple to another tuple.
[Link] to print all the values in a tuple to another list.
[Link] to print all the even digits in a tuple to another tuple.
[Link] to print all the even digits in a tuple to another list.
[Link] to print all the odd digits in a tuple to another tuple.
[Link] to print all the odd digits in a tuple to another list.
[Link] to extract all the alphabets in a tuple.
[Link] to extract all the numbers in a tuple.
[Link] to extract all the special characters in tuple.
[Link] to convert the al uppercase alphabets to lower case alphabets.
[Link] to convert all the lowercase alphabets to uppercase alphabets.
[Link] to find the length of the tuple.
[Link] to find the length of the tuple without using Len function.
[Link] to find the number of alphabets in a tuple.
[Link] to find the number of numbers in a tuple.
[Link] to find the number of special characters in a tuple.
[Link] to reverse a tuple.
[Link] to reverse a tuple w/o using slicing.
[Link] to add two tuples.
[Link] to remove the repeated values in tuple
[Link] to extract the repeated values in a tuple.
[Link] to find the sum of the numbers present in a tuple.
[Link] to find the sum of ascii values of numbers in a tuple.
[Link] to find the sum of the ascii values of special characters in a tuple.
[Link] to print number of alphabets present in a tuple, if the sum of the ascii
values of alphabets is greater than sum of ascii value of numbers.
[Link] to check whether the tuple is empty or not.
[Link] to check whether the tuple contains special characters or not.
[Link] to check whether the tuple contains numeric value or not.
[Link] to check whether the tuple contains alphabets or not.
[Link] to print the ascii values of alphabets if the alphabet present in an even
index.
[Link] to print the sum of the numbers in a tuple, if the number is present in odd
index.
[Link] to extract all the ovels in a given tuple.
[Link] to extract all the consonants is a tuple.
[Link] to print the sum of all the ascii values of the alphabet if it is in even index
and if it is ovel.
[Link] to check whether all the values in a tuple is singe value data type or not.
[Link] to check whether all the values in a tuple is multi value data type or not.
[Link] to check whether the tuple is homogeneous tuple or heterogeneous
tuple.
[Link] to check whether the tuple is homogeneous or heterogeneous, if it is
homogeneous print the type of values in a tuple.
[Link] to extract all the single value datatype values in a tuple.
[Link] to extract all the multi value data type values in a tuple.
[Link] to extract all the ovel characters in a tuple.
[Link] to extract all the values in a tuple if it is in even indexing.
[Link] to extract all the numbers if it is in odd index and if it is divisible by 5.
[Link] to extract all the happy numbers in a heterogeneous tuple
[Link] to extract all the perfect numbers in a homogeneous tuple.
[Link] to extract all the Armstrong numbers in a tuple.
[Link] to check whether the character present in a tuple or not.
[Link] to check whether the character present in a tuple or not, if it is present
print the ascii value.
[Link] to nest a tuple inside to another tuple.
[Link] to extract all the even index values in a tuple.
[Link] to extract all the odd index values in a tuple, if it is an integer datatype
and if it multiple of 3
[Link] to extract all odd index values if it is mutable datatype.
[Link] to extract all the values in a tuple separately, according to datatype.
[Link] to count the number of words in a tuple if the value is a string.
[Link] to extract all the odd index values using slicing.
[Link] to extract all the odd index values without using slicing.
[Link] to concatenate all the string values in a given tuple.
[Link] to print datatypes of all the values in a homogeneous tuple.
[Link] to print datatypes of all the values in a heterogeneous tuple separately.
[Link] to test if a variable is list or set or tuple.
[Link] to sort a list of tuples by the second Item.
[Link] to print the sum of tuple elements.
[Link] to Check if the given element is present in tuple or not.
64. W.A.P to check the second largest number given in the tuple?
[Link] TO Print the sum of all integer numbers in a tuple
[Link] TO Print the sum of even and odd numbers in a tuple.
[Link] TO Print the product of the all the even numbers in a tuple.
[Link] Check the collection is having middle value or not.
[Link] to extract the middle value of the tuple.
[Link] to Check whether given data is mutable or immutable in a tuple.
71. W.A.P to get the following output.
i/p=(‘hai’, ‘hello’, ‘how’, ‘are’, ‘you’)
o/p={‘hai’:[3,’ai’], ‘hello’:[5,’e’], ‘how’:[3,’o’], ‘are’:[3,’ae’], ‘you’:[3,’ou’]}
[Link] to Count the number of complex data items present inside the tuple.
73. Find the sum of even integer numbers if it is present in odd index and divisible
by3.
74. Split the given tuple collection of integer numbers into even & odd collection.
75. Count number of string data items present in a tuple.
76. W.A.P to get the following output.
i/p= (‘hai’, ‘hello’, ‘how’, ‘are’, ‘you’)
o/p= {‘hai’:3, ‘hello’:5, ‘how’:3, ‘are’:3, ‘you’:3}
77. Print cube of all even numbers which are divisible by 4
78. W.A.P to get the following output.
i/p= [‘hai’,90,6.7, ’hello’,(8,9),’python’]
o/p={(‘hai’,3),(‘hello’,5),(‘python’,6)}
79. Extract all the string data items present inside the given tuple only if it is
starting from ‘a’.
80. Extract all the string data items from a given tuple only if it is at odd index &
length is greater than 3.
81. W.A.P to get the following output.
i/p=’PYTHon is Easy’
o/p=(‘PYTHon2’,’is2’,’Easy3’)
82. W.A.P to get the following output.
i/p=(2.3,18,71,’hai’,3+2j,{1,2},23)
o/p=(2.3,9,8,3,3+2j,2,5)
83. W.A.P to get the following output.
i/p=’abcd hai hello*’
o/p=[‘abcd1’,’hello2’]
84. Considering heterogeneous tuple find the sum of individual digits present
inside an integer number only if it is having more than 4 digits.
85. Extract all the string values present inside a tuple collection if it is present at
odd index & length of string is even (using functions).
86. W.A.P to get the following output (using functions).
i/p= (12, ‘abcde’, ‘python’, 89, 4.5, ‘123’)
o/p=((‘abcde’,5), (‘python’,6),(‘123’,3))
87. W.A.P to get the following output.
i/p=’hai hello python’
o/p=((‘hai’,2,’a’), (‘hello’,2,’el’), (‘python’,1,’yhyn’))
89. W.A.P to get the following output.
i/p= ‘AbcD hAi Hello’
o/p=((‘AbcD’,’bc’,2), (‘hAi’,’hi’,2), (‘Hello’,’llo’,3))
90. W.A.P to find the sum of factorial of all the integer numbers present inside the
tuple (using functions).
91. Extract all the integer numbers which are divisible by 5 from the given tuple
by using recursion.
92. W.A.P to remove the duplicates from a tuple collection by using recursion
(without using typecasting).
93. W.A.P to get the following output (using recursion).
i/p=’python is very’
o/p=((‘python’,’nohtyp’,6),(‘is’,’si’,2),(‘very’,’yrev’,4))
94. Extract all the integer numbers present inside heterogonous tuple, print the
cube of all the values.
95. Extract all the integer numbers present inside heterogonous tuple, if value is
more than 15 present at odd index.
96. Extract all the integer values present inside given heterogeneous list if it’s
value is b/w the range 15 -75, and the ASCII value of the number is divisible by 3.
[Link] to print the sum of ASCII values of the integers present in the given tuple
if the value present in even index and if the ASCII value is odd.
[Link] to print the product of the indexing number if the indexing number
contains alphabets, and if the ASCII value of the character is multiple of 5 in a
given heterogeneous tuple.
[Link] to print the second greatest number in a given homogeneous tuple.
[Link] to print the third smallest number in a given homogeneous tuple.
[Link] to copy a tuple into another tuple by excluding the special characters
Functions:-
Function is a name given to a block of code/ A name given to a memory location where the set of
instructions has been
stored, is known as function name
Basically functions got classified into 2 types:
1. in-built functions
2. User-Defined Functions
1. in built functions:-
it is a function whose task is pre-defined by the developer, we can easily access the pre-defined
functions/ in built functions
Ex: input(), len(), copy(), sort(), chr(), ord()
1. User-defined Functions:-
It is a function which will get created based on user requirements.
def:- it is a keyword which is used to define the function
Function name:- It is a name given to the function to identify the
operation.
• to represent the function function name should follow the rules of identifiers
• To print the values that function returns print statement is required
• We can store the values that function returns into a variable for further usage
• a single function can be called for n no of times
• it is a type of user defined function where no need to pass the arguments to the function & function
will not
return any values.
arguments:-
These are the requirements to perform the specific operation.
return:-
it is a keyword which is is used to return the control from the function area/ method area to main space
along with values
Function Call:-
To execute the created function calling the function is mandatory Based on the return type user-
defined functions got classified into 4 types:
1. Function without argument and without return value
2. Function without argument and with return value
3. Function with argument and without return value
4. Function with argument and with return value
Function with argument and without return value
• it is a type of user-defined function where it is required to pass the arguments to the function but we
cannot expect
the return value from the function
Function with argument and with return value
• it is a type of user-defined function where passing the arguments to the function is required and we
can
expect the function to return some value
Function without argument and with return value
• it is a type of user-defined function where passing the arguments is not requires , but function will
return some value.
Function without argument and without return value
it is a type of user defined function where no need to pass the arguments to the function & function will
not return any values
Arguments got classified into two types:
[Link] arguments:
• The arguments that we are passing at the time of function definition are known as formal arguments.
[Link] Arguments:
• The arguments that we are passing at the time of function call are known as actual arguments.
• While calling the function the number of actual arguments should be equal to the number of formal
arguments.
Memory allocation with respect to Functions:
1. In case of function execution the memory will get divided into two parts.
a. Main Space/ Stack Space
b. Method Area/ Function Area./ Hep Space
2. The function will start its execution from main space only.
3. As soon as control see a keyword called def it will go to method area and it creates a block of
memory , all the instructions will get stored inside the created block & address will be given to the
memory block and that address will get stored with respect to function name in main space
4. to execute the instructions stored inside the memory block function call is mandatory.
Auto (Python)
def wish():
print('Hello Good Morning....')
def greet(name):
print(f"Hello {name} Good Morning....")
def greet(name):
return f"Hello {name} Good Morning...."
def add(a, b):# Function Declaration args are Formal Arguments
return a + b
def func(name, age, pay):
return f"Hello {name} you are {age} years of age and you get ${pay} as a pay"
func('steve', 29, 1536)# Function Call args are Actual Arguments
# the number of formal args should be same as actual arguments
def add(a, b):
return a + b
def add():
a = int(input('enter the number:'))
b = int(input('enter the number:'))
c = a + b
print(c)
n = int(input('enter the number:'))
d = []
for i in range(1, n//2 + 1):
if n % i == 0:
[Link](i)
if len(d) == 1:
print('the entered number is a prime number')
else:
print('the entered numberis not a prime number')
n = int(input('enter the number:'))
d = []
for i in range(1, n//2 + 1):
if n % i == 0:
[Link](i)
if sum(d) == n:
print('the entered number is a perfect number')
else:
print('the entered number is not a perfect number')
def divs(n):
d = []
for i in range(1, n//2 + 1):
if n % i == 0:
[Link](i)
return d
# WAP to check whether the entered number is prime or not.
def is_prime(n):
return len(divs(n)) == 1
# WAP to check whether the entered number is a perfect number or not
def is_perfect(n):
return sum(divs(n)) == n
# WAP to check whether the entered numbers are amicable or not.
def is_amicable(a, b):
return sum(divs(a)) == b and sum(divs(b)) == a
# WAP to find the prime numebrs in between user entered limits
def primes(a, b):
p = []
for i in range(a, b+1):
if is_prime(i):
[Link](i)
return p
# WAP to find the perfect numbers in between the user entered limits
def perfects(a, b):
p = []
for i in range(a, b+1):
if is_perfect(i):
[Link](i)
return p
Recursion
# WAP to extract all the uppercase alphabets from the given string
a = input('enter the string:')
i = 0
res = ''
while i < len(a):
if a[i].isupper():
res += a[i]
i += 1
def uppers(a, i=0, res=''):
if i < len(a):
if a[i].isupper():
res += a[i]
return uppers(a, i=i+1, res=res) # Recursive call
else:
return res
print(uppers('PyThOn'))
WAP to get the factorial of a given number
n = int(input('enter the number:'))
f = 1
i = 1
while i <= n:
f *= i
i += 1
def fact(n, f=1, i=1):
if i <= n:
f *= i
return fact(n, f=f, i=i+1)
else:
return f
def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)
# WAP to remove all the repeated characters from the given string.
Object
Oriented Programmings:
Class:-
Class is a container which is used to store the members/ the properties/ the functionalities/ the methods
of the object
(or)
Class is a
container which is used to store the data and which will tell the user how to utilize the stored data.
Object:-
Object is the instance of the class / object is a variable which is created for a specific class
Memory allocation for a class:
• As soon as control see a keyword class, it will create a dictionary, inside the memory
• it contains of key & value layers, address will be given to a key layer & that address will be stored with
respect to a class name.
• All the properties & functionalities will get stored into class dictionary in the form of key & value pairs,
the reference address will be given to each and every key
Memory allocation for a Object Creation:-
As soon as control see an object creation Process, it will create a dictionary inside a memory.
it contains of key & value layers, address will be given to a key layer & that address will be stored
with respect to a object name
All the properties of class dictionary will get stored into object in the form of key & Value pairs.
Control will check whether the object dictionary is having __init__ or not, if the method exists then it will
get
invoke/ execute by default.
All the properties of object will get store into object dictionary
Auto (Ruby)
# Object Oriented Programming.
# class: - class is a blueprint of an object which cosist of all the
# properties/ members & methods/ behaviours of an object
# Object: - Object object is an instance of a class
class Demo:
a = 10
b = 20
c = 30
d = 40
o1 = Demo()
o2 = Demo()
o3 = Demo()
class Bank:
bname = 'SBI'
ceo = 'girish'
manager = 'sandeep'
ifsc = 'SBIN0021519'
# name
# pno
# email
# add
# bal
# aadhaar
# pan
c1 = Bank()
[Link] = 'likith'
[Link] = 8888888888
[Link] = 'likith@[Link]'
[Link] = 'banglore'
[Link] = 2500000
c2 = Bank()
[Link] = 'vishal'
[Link] = 9999999999
[Link] = 'vishal@[Link]'
[Link] = 'hyderabad'
[Link] = 9555555
class Bank:
bname = 'SBI'
ceo = 'girish'
manager = 'sandeep'
ifsc = 'SBIN0021519'
def init(self, name, pno, email, add, bal):
[Link] = name
[Link] = pno
[Link] = email
[Link] = add
[Link] = bal
c1 = Bank()
c2 = Bank()
init(c1, 'likith', 8965478965, 'likith@[Link]', 'lepakshi', 2569874)
init(c2, 'vishal', 7896541230, 'vishal@[Link]', 'mumbai', 5987456)
class Bank:
bname = 'SBI'
ceo = 'girish'
manager = 'sandeep'
ifsc = 'SBIN0021519'
def __init__(self, name, pno, email, add, bal):
[Link] = name
[Link] = pno
[Link] = email
[Link] = add
[Link] = bal
c1 = Bank('steve', 8520147852, 'steve@[Link]', 'pune', 2582)
c2 = Bank('allen', 8596748596, 'allen@[Link]', 'kalyan', 58967)
# types of methods/ behaviors/ functionalities
# in class we can store 3 types of methods.
# 1. Object Methods.
# 2. Class Methods.
# 3. Static Method.
# 1. Object Method:-
# * it is a method which is used to access or to modify the members of the object.
# * For all the object methods passing self is mandatory, to store the address of the object
# * if we are calling an object method by using the class name , then we have to pass the address/ the
reference of the object.
# * if we are calling the object method with the help of object name, then no need to pass
# the address of the object, by default self will take the respective address of an object
# [Link] Method:-
# * it is a method which is used to access or to modify the members of the class.
# * for all the class methods we have to decorate with "@classmethod"
# * for all the class methods passing cls is mandatory, to store the address of the class
# 3. Static Method:-
# it is a method which is neither belongs to class nor belongs to object, but it will act as supportive for
both class & object
# * to create any static method we have to use a decorator called "@staticmethod"
# since static method neither belongs to class nor belongs to object, passing cls or self is not required
Auto (Python)
# there are 3 types of methods are there
# 1. Object Mthod: - a method which is used to access or modify the members of an
object
# 2. Class Method: - a method which is used to access or modify the members of a
clasa.
# 3. Static method: a method whihc is neither belongs to clas nor belongs to
object
# but static method will act as a supportive method for both class and object
class Bank:
bname = 'SBI'
ceo = 'girish'
manager = 'sandeep'
ifsc = 'SBIN0021519'
# initialisation method/ constructor method.
def __init__(self, name, pno, email, add, bal):
[Link] = name
[Link] = pno
[Link] = email
[Link] = add
[Link] = bal
def deposit(self, amount):
[Link] += amount
[Link]()
def withdraw(self, amount):
if [Link] >= amount:
[Link] -= amount
[Link]()
else:
print('insuffitient balance')
def display(self):
print(f"The Name of the customer is {[Link]}")
print(f"The Pno of the customer is {[Link]}")
print(f"The Email of the customer is {[Link]}")
print(f"The Address of the customer is {[Link]}")
print(f"The Balance of the customer is {[Link]}")
@classmethod
def ch_bname(cls, new):
[Link] = new
@staticmethod
def msg():
print('Transaction Successfull')
c1 = Bank('steve', 8520147852, 'steve@[Link]', 'pune', 2582)
c2 = Bank('allen', 8596748596, 'allen@[Link]', 'kalyan', 58967)
# to call the object methods
# obj.method_name(args)
# class.method_name(obj, args)
Inheritance:- it is a phenomenon of deriving the properties from one class to another class in this case
the class from which you are def=riving the properties we call it as a parent
class/ base class/ super class the class to which we inherit the properties we call it as a child class/
derived class/ sub-class.
basically inheritance is used to reduce the time taken to update the application that already exists.
with the help of inheritance we can increase the efficiency of the program by reducing the no of lines of a
program & by removing the code redundancy
Inheritance got classified into 5 types:
1. Single-Level Inheritance
Deriving the properties from a single parent class to a single child class is known as single level
inheritance
2. Multi-level Inheritance
Deriving the properties from one class to another class by considering more than one level is known as
multi-level inheritance
3. Multiple Inheritance
Deriving the properties from multiple parent classes to a single child class is known as multiple
inheritance
4. Hierarchical Inheritance
Deriving the properties from one parent class to multiple child classed is known as Hierarchical
Inheritance
5. Hybrid Inheritance
Combining any two or more types of inheritance is known as hybrid inheritance
Auto (Python)
# Single Level Inheritance
# Parent Class
class Bank:
bname = 'SBI'
ceo = 'Girish'
manager = 'Sandeep'
loc = 'Mumbai'
# Constructor method of a parent class
def __init__(self, name, add, bal):
[Link] = name
[Link] = add
[Link] = bal
def deposit(self, amount):
[Link] += amount
def withdraw(self, amount):
if [Link] >= amount:
[Link] -= amount
else:
print('insufficient balance')
# Method of a parent class
def display(self):
print(f"The Name of the customer is {[Link]}")
print(f"The Address of the customer is {[Link]}")
print(f"The Balance of the customer is {[Link]}")
c1 = Bank('Steve', 'Pune', 2500)
class Bank1(Bank):
# constructor method of a child class
def __init__(self, name, add, bal, pno, email, aadhar, pan):
# invoking the parent class constructor method inside the child class
constructor method
# this phenomenon we call it as constructor chaining.
Bank.__init__(self, name, add, bal)
[Link] = aadhar
[Link] = pan
[Link] = pno
[Link] = email
# method of a child class
def display(self):
# invoking the parent class method inside the child class method
# this phenomenon is known as method chaining.
# [Link]()
super().display()
print(f"The pno of the customer is {[Link]}")
print(f"The Email of the customer is {[Link]}")
print(f"The Aadhar of the customer is {[Link]}")
print(f"The Pan of the customer is {[Link]}")
c2 = Bank1('mike', 'Mumbai', 2589, 7896541230, 'mike@[Link]', 889966554477,
'ABCD1234X')
# Multi level Inheritance.
class Resume:
def __init__(self, name, pno, email, add, tyop, tp):
[Link] = name
[Link] = pno
[Link] = email
[Link] = add
[Link] = tyop
[Link] = tp
def ch_pno(self, new):
[Link] = new
def ch_email(self, new):
[Link] = new
def ch_add(self, new):
[Link] = new
def display(self):
for i, j in self.__dict__.items():
print(f"The {i} of the Candidate is {j}")
s1 = Resume('likith', 8179267926, 'likith@[Link]', 'Banglore', 2010, 95)
class Resume1(Resume):
def __init__(self, name, pno, email, add, tyop, tp, twyop, twp):
super().__init__(name, pno, email, add, tyop, tp)
[Link] = twyop
[Link] = twp
s2 = Resume1('miller', 8528631478, 'miller@[Link]', 'kochi', 2012, 85, 2014,
75)
class Resume2(Resume1):
def __init__(self, name, pno, email, add, tyop, tp, twyop, twp, dyop, dp):
super().__init__(name, pno, email, add, tyop, tp, twyop, twp)
[Link] = dyop
[Link] = dp
s3 Resume2('punith', 8596747859, 'punith@[Link]', 'chennai', 2014, 95, 2012,
98, 2015, 89)
class Resume3(Resume2):
def __init__(self, name, pno, email, add, tyop, tp, twyop, twp, dyop, dp,
myop, mp):
super().__init__(name, pno, email, add, tyop, tp, twyop, twp, dyop, dp)
[Link] = myop
[Link] = mp
s4 = Resume3('saantosh', 8899778899, 'santosh@[Link]', 'Delhi', 2012, 95,
2014, 55, 2017, 98, 2019, 86)
# multiple Inheritance
class Add:
@staticmethod
def add(a, b):
return a + b
class Sub:
@staticmethod
def sub(a, b):
return a - b
class Mul:
@staticmethod
def mul(a, b):
return a * b
class Div:
@staticmethod
def truediv(a, b):
return a / b
@staticmethod
def floordiv(a, b):
return a // b
@staticmethod
def mod(a, b):
return a % b
class Calc(Add, Sub, Mul, Div):
pass
x = Calc()
Date :- 27/DEC/2024
Auto (Python)
# Encapsulation: Encapsulation is a phenomenon of hiding the methods/ members
from the user
# Access Specifiers :- Access Specifiers will specify the members or methods
whether the user can access them outside the class or not.
# there are 3 types of Access Specifiers
# 1. Public Access Specifiers
# 2. Protected Access Specifiers
# 3. Private Access Specifiers
# 1. Public Access Specifiers
# These are the members which can be accessed by the user even from outside the
class.
# to create public members no prefix is required
class Bank:
bname = 'SBI'
manager = 'steve'
mbl = 'Mumbai'
contact = 8888588885
transactions = []
def __init__(self, name, pno, email, add, aadhar, pan, bal):
[Link] = name
[Link] = pno
[Link] = email
[Link] = add
[Link] = aadhar
[Link] = pan
[Link] = bal
def deposit(self, amount):
if amount > 50000:
upan = input('enter the Pan Number: ')
if upan == [Link]:
[Link] += amount
[Link](f"Credited of rupees {amount}")
[Link]()
else:
print('Invalid Pan number')
else:
[Link] += amount
[Link](f"Credited of rupees {amount}")
[Link]()
def withdraw(self, amount):
if [Link] >= amount:
if amount > 50000:
upan = input('enter the PAN Number: ')
if upan == [Link]:
[Link] -= amount
[Link](f"Debited of rupees {amount}")
[Link]()
else:
print('invalid pan number')
else:
[Link] -= amount
[Link](f"Debited of rupees {amount}")
[Link]()
else:
print('insuffetient Balance')
def neft(self, other, amount):
if [Link] >= amount:
if amount > 50000:
upan = input('enter your pan number:')
if upan == [Link]:
[Link](amount)
[Link](amount)
else:
print('invalid pan number')
else:
[Link](amount)
[Link](amount)
else:
print('insuffitient balance')
def statement(self):
for transaction in [Link]:
print(transaction)
print(f"The available Balance is {[Link]}")
def display(self):
for i, j in self.__dict__.items():
print(f"The {i} of the customer is {j}")
@staticmethod
def msg():
print('Transaction Successfull')
c1 = Bank('likith', 8179267926, '[Link]@[Link]', 'Anantapur',
889966554477, 'ABCD1234X', 25000)
c2 = Bank('Steve', 7896541230, 'steve@[Link]', 'Banglore', 778899665544,
'IJKL9876Y', 30000)
# 2. Protected Access Specifiers.
# These are the members which can be accessed by the user even from outside the
class.
# to create protected membres we will make use of "_" as a prefix
class Bank:
bname = 'SBI'
manager = 'steve'
mbl = 'Mumbai'
contact = 8888588885
transactions = []
def __init__(self, name, pno, email, add, aadhar, pan, bal):
self._name = name
self._pno = pno
self._email = email
self._add = add
self._aadhar = aadhar
self._pan = pan
self._bal = bal
def deposit(self, amount):
if amount > 50000:
upan = input('enter the Pan Number: ')
if upan == self._pan:
self._bal += amount
[Link](f"Credited of rupees {amount}")
self.__msg()
else:
print('Invalid Pan number')
else:
self._bal += amount
[Link](f"Credited of rupees {amount}")
self.__msg()
def withdraw(self, amount):
if self._bal >= amount:
if amount > 50000:
upan = input('enter the PAN Number: ')
if upan == self._pan:
self._bal -= amount
[Link](f"Debited of rupees {amount}")
self.__msg()
else:
print('invalid pan number')
else:
self._bal -= amount
[Link](f"Debited of rupees {amount}")
self.__msg()
else:
print('insuffetient _balance')
def neft(self, other, amount):
if self._bal >= amount:
if amount > 50000:
upan = input('enter your pan number:')
if upan == [Link]:
[Link](amount)
[Link](amount)
else:
print('invalid pan number')
else:
[Link](amount)
[Link](amount)
else:
print('insuffitient _balance')
def statement(self):
for transaction in [Link]:
print(transaction)
print(f"The available _balance is {self._bal}")
def display(self):
for i, j in self.__dict__.items():
print(f"The {i} of the customer is {j}")
@staticmethod
def __msg():
print('Transaction Successfull')
c1 = Bank('likith', 8179267926, '[Link]@[Link]', 'Anantapur',
889966554477, 'ABCD1234X', 25000)
c2 = Bank('Steve', 7896541230, 'steve@[Link]', 'Banglore', 778899665544,
'IJKL9876Y', 30000)
# 3. Private Access Specifiers
# These are the members which will not allow the users to access them ouside the
class.
# to create private access specifiers we use "__" as a prefix
class Bank:
bname = 'SBI'
manager = 'steve'
mbl = 'Mumbai'
contact = 8888588885
transactions = []
def __init__(self, name, pno, email, add, aadhar, pan, bal):
self.__name = name
self.__pno = pno
self.__email = email
self.__add = add
self.__aadhar = aadhar
self.__pan = pan
self.__bal = bal
def deposit(self, amount):
if amount > 50000:
upan = input('enter the Pan Number: ')
if upan == self.__pan:
self.__bal += amount
[Link](f"Credited of rupees {amount}")
self.__msg()
else:
print('Invalid Pan number')
else:
self.__bal += amount
[Link](f"Credited of rupees {amount}")
self.__msg()
def withdraw(self, amount):
if self.__bal >= amount:
if amount > 50000:
upan = input('enter the PAN Number: ')
if upan == self.__pan:
self.__bal -= amount
[Link](f"Debited of rupees {amount}")
self.__msg()
else:
print('invalid pan number')
else:
self.__bal -= amount
[Link](f"Debited of rupees {amount}")
self.__msg()
else:
print('insuffetient balance')
def neft(self, other, amount):
if self.__bal >= amount:
if amount > 50000:
upan = input('enter your pan number:')
if upan == [Link]:
[Link](amount)
[Link](amount)
else:
print('invalid pan number')
else:
[Link](amount)
[Link](amount)
else:
print('insuffitient balance')
def statement(self):
for transaction in [Link]:
print(transaction)
print(f"The available balance is {self.__bal}")
def display(self):
for i, j in self.__dict__.items():
print(f"The {i} of the customer is {j}")
@staticmethod
def __msg():
print('Transaction Successfull')
c1 = Bank('likith', 8179267926, '[Link]@[Link]', 'Anantapur',
889966554477, 'ABCD1234X', 25000)
c2 = Bank('Steve', 7896541230, 'steve@[Link]', 'Banglore', 778899665544,
'IJKL9876Y', 30000)
Auto (Ruby)
# Polymorphism :- it is a phenomenon of making a single method or an operator to
work on multiple operations
# it can be done in two ways: -
# 1. method over loading
# it is a phenomenon of making a single method to work on multiple operations.
# in python if we try to perform method overloading it will perform method over
writing.
# method over writing:- when ever we create multiple function with same name
# it will over writes the previous address with the latest
# 2. Operator overloading.
# it is a phenomenon of making a single operator to work on multiple operations.
class Demo:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a
def __sub__(self, other):
return self.a - other.a
Abstraction :- Abstraction is a phenomenon of hiding the implementation of a method from the user
Abstract class:- a class which consist of at least one Abstract Method in it.
Abstract Method :- a method which consist of a function declaration but not a function definition.
Concrete class :- a class which does not consist of any Abstract Method in it.
it is not possible to create an object for a abstract class
Auto (Python)
from abc import ABC, abstractmethod
class Demo(ABC):
@abstractmethod
def msg(self):
pass
@abstractmethod
def func(self):
pass
class Demo1(Demo):
def msg(self):
print('Hii Good Morning')
def func(self):
print('hii Tomorrow is weekend so enjoy....')
o1 = Demo1()
lambda: -lambda is a keyword which is used to create an anonymous function.
lambda will return the address of a function
we need a variable name to store it, we can use the variable name to call the function.
the syntax used to create a lambda function is
var_name = lambda args: return_value
Auto (Python)
# Write a Funcition to find the sum of two numbers.
addition = lambda a, b: a + b
# Write a function to find the square of the given number.
po = lambda a: a ** 2
map: map is a built in function which is used to perform some operation on each and every vale present
in the collection
map functio will accept two arguments 1. Function name, 2. Collection.
the used is: -
var_name = map(func_name, collection)
map functio will return the address of a resultant collection
if we want to display the values we need to perform Typecasting.
Auto (Python)
# Write a function to find the square of all the numbers form 1 to 20
x = map(lambda a: a ** 2, range(1, 21))
# Write a function to extract all the even numbers from 1 to 20.
x = filter(lambda a: a % 2 == 0, range(1, 21))
# Write a function to extract all the divisors of a number
n = int(input('enter the number:'))
x = filter(lambda i: n % i == 0, range(1, n))
# WAP to check whether the entered number is prime or not.
prime = lambda n: len(list(filter(lambda i: n % i == 0, range(1, n)))) == 1
# WAP to extract all the prime numbers from 1 to 100
x = filter(lambda n: len(list(filter(lambda i: n % i == 0, range(1, n)))) == 1,
range(1, 101))
Comprehension
Auto (Python)
# # WAP to extract all the even numbers in between the user entered limits.
# s = int(input('enter the number:'))
# e = int(input('enter the number:'))
# ev = []
# for i in range(s, e+1):
# if i % 2 == 0:
# [Link](i)
# print(ev)
# Comprehension: - Comprehension is a phenomenon of creating a resultant
collection by reducing the number of instructions.
# we can perform Comprehension only on mutable collections.
# comprehension is of 3 types
# 1. list Comprehension
# 2. set Comprehension
# 3. dictionar Comprehension
# 1. list Comprehension
# it is a phenomenon of creating a list collection with less no of instructions.
# if we use only if statement in comprehension we use a syntax
# syntax: - var_name = [val_to_be_added for var in collection <if condition>]
# if we not use any if statement in comprehension we use a syntax
# syntax: - var_name = [val_to_be_added for var in collection]
# if we use only if-else statement in comprehension we use a syntax
# var_name = [val_to_be_added if <condition> else val_to_be_added for var in
collection]
# # WAP to extract all the even numbers in between the user entered limits.
# s = int(input('enter the number:'))
# e = int(input('enter the number:'))
# evens = [i for i in range(s, e+1) if i % 2 == 0]
# # print(evens)
# res = [i if i % 2 == 0 else i**2 for i in range(1, 10)]
# print(res)
#
# 2. Set Comprehension
# it is a phenomenon of creating a set collection with less no of instructions.
# if we use only if statement in comprehension we use a syntax
# syntax: - var_name = {val_to_be_added for var in collection <if condition>}
# if we not use any if statement in comprehension we use a syntax
# syntax: - var_name = {val_to_be_added for var in collection}
# if we use only if-else statement in comprehension we use a syntax
# var_name = {val_to_be_added if <condition> else val_to_be_added for var in
collection}
# 3. Dictionary Comprehension
# it is a phenomenon of creating a Dictionary collection with less no of
instructions.
# if we use only if statement in comprehension we use a syntax
# syntax: - var_name = {key:value for var in collection <if condition>}
# if we not use any if statement in comprehension we use a syntax
# syntax: - var_name = {key:value for var in collection}
# if we use only if-else statement in comprehension we use a syntax
# var_name = {key:value if <condition> else value for var in collection}
a =['steve', 'miller', 'martin', 'mike', 'punith', 'blake', 'likith',
'frank', 'facebook', 'tuna', 'lina', 'meena', 'seena', 'shiva',
'hari', 'krishna', 'bhanu', 'manu', 'sunith']
# res = {'steve': 5, 'miller': 6, 'martin': 6........}
res = {i:len(i) for i in a}
# print(res)
res = {i:len(i) for i in a if len(i) % 2 == 0}
# print(res)
res = {i:len(i) if len(i) % 2 == 0 else i[::-1] for i in a}
print(res)
File Handling
Auto (Python)
# Open the file
# perform the operation
# close the file
# to handle the file getting the acces to the file is mandetory.
# to get the access we makeuse of a functio called open.
# open function will accept two arguments
# 1. Filename with extension/ Location of a file
# 2. Mode of operation
# Read mode ("r")
# Read Binary mode ("rb")
# Write Mode ("w")
# Write Binary Mode ("wb")
# Append Mode ("a")
# Append Binay Mode ("ab")
# syntax to open a file is
# var_name = open(Filename with extension/ Location of a file, mode of operation)
# to read the data we have 3 built in functions.
# 1. read
# 2. readline
# 3. readlines
# 1. Read
# it will return entire file data as one string.
f = open("[Link]", "r")
data = [Link]()
[Link]()
# 2. readline
# it will return a data from the file line by line
f = open("[Link]", "r")
data = [Link]()
[Link]()
# 3. readlines
# it wil return a list of string from the file.
f = open("[Link]")
data = [Link]()
[Link]()
# # Opening the file with context manager.
# with open('[Link]') as f:
# for i in f:
# print(i)
res = []
with open(r'C:\Users\lenovo\Desktop\batches\QEX-SPEPTD-M5\file
handling\[Link]') as f:
for i in f:
cleaned_line = [Link]()
if cleaned_line:
[Link](cleaned_line.split()[2])
print(res)
# WAP to extract all the messages from the given file
# WAP to extract all the unique messages
# WAP to count how many times each message is repeated
# WAP to extract all the IP address from [Link]
# WAP to extract all the unique IP Addresses from [Link]
# WAP to count how many times each IP Address is repeated in [Link]
#------------------------------------to get the files you can refer
"[Link]/pointsfile"---------------------------------------------
decorators:- Decorators are the functions which is used to give some additional functionalities to function
without modifying it
Auto (Python)
from time import sleep
from collections import defaultdict
def add(a, b):
sleep(5)
return a + b
def sub(a, b):
sleep(5)
return a - b
def mul(a, b):
sleep(5)
return a * b
def div(a, b):
sleep(5)
return a / b
def delay(func):
def inner(*args, **kwargs):
sleep(2)
return func(*args, **kwargs)
return inner
@delay
def add(a, b):
return a + b
@delay
def sub(a, b):
return a - b
@delay
def mul(a, b):
return a * b
@delay
def div(a, b):
return a / b
c = defaultdict(int)
def counter(func):
def inner(*args, **kwargs):
c[func.__name__] += 1
return func(*args, **kwargs)
return inner
@counter
def add(a, b):
return a + b
@counter
def sub(a, b):
return a - b
@counter
def mul(a, b):
return a * b
@counter
def div(a, b):
return a / b
c = defaultdict(int)
def restrict(func):
def inner(*args, **kwargs):
if func.__name__ in c:
if c[func.__name__] <3:
res = func(*args, **kwargs)
c[func.__name__] += 1
return res
else:
print('not morethan 3')
else:
c[func.__name__] += 1
return func(*args, **kwargs)
return inner
@restrict
def add(a, b):
return a + b
@restrict
def sub(a, b):
return a - b
@restrict
def mul(a, b):
return a * b
@restrict
def div(a, b):
return a / b
Exception: Exception is an un authorized event which occurs at the time of execution of a program and
stops the flow of execution of a program.
Except Syntax errors all the errors are considered as exceptions.
to handle the exceptions we can make use of try, except keywords
We have 3 types of Exception Handlings.
Specific Exception Handling
when ever we know the exact type of exception then we will make use of Specific Exception Handling
Generic Exception Handling
when ever we Don't know the exact type of exception then we will make use of Generic Exception
Handling
Generic Exception Handling is not capable of handling KeyboardInterrupt exceptions
Default Exception Handling
when ever we Don't know the exact type of exception then we will make use of Default Exception
Handling
Generic Exception Handling is capable of handling KeyboardInterrupt exceptions also
Auto (Python)
def div():
try:
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
return a / b
except ZeroDivisionError:
print('Please enter the value for second argument other thaan "0" ')
return div()
except ValueError:
print('Please enter only numerics as an input')
return div()
# Generic Exception Handling
def func():
try:
while True:
print('hii')
except Exception:
print('Exception HandledSuccessfully')
# Default Exception Handling
def func():
try:
while True:
print('hii')
except:
print('Exception HandledSuccessfully')
def sub():
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
if b > a:
raise ValueError('please enter b as a greatest number')
else:
return a - b
class MyException(Exception):
pass
def sub():
a = int(input('enter the number 1:'))
b = int(input('enter the number 2:'))
if b > a:
raise MyException('please enter b as a greatest number')
else:
return a - b
============ Characters ===================
. - Matches any character except new line
\. - Mathes a dot.
\\ - Matches backslash
\* - Matches astrick
============ Character set ===================
[abcd] - any character which matches either 'a' or 'b' or 'c' or 'd'
[a-z] - any character from 'a' through 'z'
[A-Z] - any character from 'A' through 'Z'
[0-9] - any numeric characters
[A-za-z] - any alphabet either uppercase or lowercase
[a-zA-Z0-9] - any alphabet or numeric.
[^abcd] - any character but not 'a' or 'b' or 'c' or 'd'
[a-z] - any character between 'a' through 'z'
=========== Special Sequences ================
\w - Word character. Same as [a-zA-Z0-9_]. Matches alphanumeric and underscore.
\W - Non-Word Character. Same as [^a-zA-Z0-9_]. Matches anything but word characters.
\d - Matches a digit. Same as [0-9]
\D - Matches a Non-Digit. Same as [^0-9]
\s - Matches only whitespace.
\S - Matches only Non-Whitespace.
* - Match expression 0 or more times
+ - Match expression 1 or more times
? - Match expression 0 or 1 times
{min,max} - Matches expression exactly 3 times
[ ] - Matches characters in square brackets
[^ ] - Matches characters Not in square brackets
Auto (Python)
# def func():
# try:
# a = 'python is easy'
# i = iter(a)
# while True:
# print(next(i))
# except StopIteration:
# pass
import re
s = 'The fat belly indicates that the cat is fat'
x = [Link]("cat", s)
# print(x)
s = "Smith's Father is a goldsmith"
x = [Link]("[Ss]mith", s)
# print(x)
s = "Virat Kohli (Hindi -pronunciation+918179267926 born 5 November 1988) is an
Indian international cricketer who plays +91 8143167926 Test and ODI cricket for
the Indian national team. A former captain in all formats of the game, Kohli
+917896541330 retired from the T20I format following India's win at the 2024 T20
World Cup. He's a +91 6587458965 right-handed batsman and an occasional
unorthodox right arm quick bowler. Kohli holds the highest IPL run-scorer record,
ranks third in T20I, +917586947859 third in ODI, and stands the fourth-highest in
international cricket. Regarded as one of the greatest batsmen of all time, he
also holds the record for scoring the most centuries in ODI cricket and is second
in the list of most international centuries scored in international cricket"
'''
+91 8143167926
+918179267926
+917586947859
+918179267926
+91 6587458965
'''
pattern = "\+91 ?[6-9]\d{9}"
x = [Link](pattern, s)
# print(x)
pan_pattern = "[A-Z]{5}[0-9]{4}[A-Z]"