Python IDP P
Python IDP P
Note:
Eg: __add__
Reserved Words
In Python some words are reserved to represent some meaning or functionality. Such type of
words are called Reserved words.
There are 33 reserved words available in Python.
True, False, None
and, or, not, is
if, elif, else
while, for, break, continue, return, in, yield
try, except, finally, raise, assert
import, from, as, class, def, pass, global, nonlocal, lambda, del, with
We can use int data type to represent whole numbers (integral values)
Eg:
a=10
type(a) #int
1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form
1. Decimal form(base-10):
It is the default number system in Python.
The allowed digits are: 0 to 9
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O.
4. Hexa Decimal Form(Base-16):
The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)
Literal value should be prefixed with 0x or 0X
a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2
We can use float data type to represent floating point values (decimal values)
Eg: f=1.234
type(f) float
We can also represent floating point values by using exponential form (scientific notation)
Eg: f=1.2e3
print(f) 1200.0
instead of 'e' we can use 'E'
The main advantage of exponential form is we can represent big values in less memory.
***Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we can
represent float values only by using decimal form.
j2 = -1
a + bj
j=
Eg:
3+5j
10+5.5j
0.5+0.1j
In the real part if we use int value then we can specify that either by decimal,octal,binary or
hexa decimal form.
But imaginary part should be specified only by using decimal form.
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
Note: Complex data type has some inbuilt attributes to retrieve the real part and
imaginary part
c=10.5+3.6j
c.real==>10.5
c.imag==>3.6
We can use complex type generally in scientific Applications and electrical engineering
Applications.
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True+True==>2
True-False==>1
str type:
s1='durga'
s1="durga"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="durga
soft"
For this requirement we should go for triple single quotes(''') or triple double quotes(""")
s1='''durga
soft'''
s1="""durga
soft"""
We can also use triple quotes to use single quote or double quote in our String.
Slicing of Strings:
[ ] operator is called slice operator, which can be used to retrieve parts of String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
-5 -4 -3 -2 -1
d u r g a
0 1 2 3 4
bytes Data Type:
bytes data type represents a group of byte numbers just like an array.
Eg:
x = [10,20,30,40]
b = bytes(x)
type(b)==>bytes
print(b[0])==> 10
print(b[-1])==> 40
>>> for i in b : print(i)
10
20
30
40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to
provide any other values then we will get value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values, otherwise we will get
TypeError.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[0]=100
TypeError: 'bytes' object does not support item assignment
bytearray is exactly same as bytes data type except that its elements can be modified.
Eg 1:
x=[10,20,30,40]
b = bytearray(x)
for i in b : print(i)
10
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
Eg 2:
>>> x =[10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:print(i)
...
40
10
20
30
13)
>>> fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
The elements present in range Data type are not modifiable. i.e range Data type is
immutable.
Form-1: range(10)
Eg:
r=range(10)
for i in r : print(i) 0 to 9
Form-2: range(10,20)
r = range(10,20)
for i in r : print(i) 10 to 19
Form-3: range(10,20,2)
r = range(10,20,2)
for i in r : print(i) 10,12,14,16,18
We can access elements present in the range Data Type by using index.
r=range(10,20)
r[0]==>10
r[15]==>IndexError: range object index out of range
Eg:
r[0]=100
TypeError: 'range' object does not support item assignment
Eg:
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Eg:
def m1():
a=10
print(m1())
None
Escape Characters:
\n==>New Line
\t===>Horizontal tab
\r ==>Carriage Return
\b===>Back space
\f===>Form Feed
\v==>Vertical tab
\'===>Single quote
\"===>Double quote
\\===>back slash symbol
....
Constants:
MAX_VALUE=10
Control Structures
list data type:
1. group of values as a single entity and collection which is ordered and changeable
2. insertion order is preserved
3. heterogeneous objects are allowed
4. duplicates are allowed
5. values should be enclosed within square brackets.
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
Append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
Arithmetic Operators
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
Relational Operators:
>,>=,<,<=
Logical Operators:
and, or, not
equality operators:
== , !=
Conditional Statements
if
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
if-else:
if condition :
Action-1
else :
Action-2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed.
if-elif-else:
Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
Based condition the corresponding action will be executed.
Python Loops
Python has two primitive loop commands:
1. while loops
2. for loops
With the while loop we can execute a set of statements as long as a condition is true.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Function
Creating a Function
Calling a Function
To call a function, use the function name followed by parenthesis:
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Return Values
To let a function return a value, use the return statement:
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Arbitrary Arguments
If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
If the number of arguments are unknown, add a * before the parameter name:
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor
power. However, when written correctly recursion can be a very efficient and mathematically-
elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decrements (-1) every time we recurse. The recursion
ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
Module
A group of functions, variables and classes saved to a file, which is nothing but module.
Every Python file (.py) acts as a module.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Use a Module
Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
There is a built-in function to list all the function names (or variable names) in a module. The
dir() function:
You can choose to import only parts from a module, by using the from keyword.
The module named mymodule has one function and one dictionary:
def greeting(name):
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person1["age"], not mymodule.person1["age"]