0% found this document useful (0 votes)
364 views

Python IDP

1. The document discusses various Python concepts like data types (lists, tuples, sets, dictionaries), operators (arithmetic, comparison, logical, assignment), conditional statements (if, if-else, if-elif-else), loops (for, while), functions, variables and more. 2. It provides details on list methods, defining tuples as immutable lists, set properties of being unordered and unindexed, dictionary indexing and various operators like their usage and examples. 3. The document also explains conditional statements and control flow like if, if-else, if-elif-else, break, continue, pass as well as for and while loops for iteration.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
364 views

Python IDP

1. The document discusses various Python concepts like data types (lists, tuples, sets, dictionaries), operators (arithmetic, comparison, logical, assignment), conditional statements (if, if-else, if-elif-else), loops (for, while), functions, variables and more. 2. It provides details on list methods, defining tuples as immutable lists, set properties of being unordered and unindexed, dictionary indexing and various operators like their usage and examples. 3. The document also explains conditional statements and control flow like if, if-else, if-elif-else, break, continue, pass as well as for and while loops for iteration.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Lists

Tuples
Sets
Dictionary
Relations
Logical Operators
Shorthand Operator
Expressions
Type Conversion
Integer arithmetic
Truth Value
if,
if-else
Nested conditions
While loop For loop
Functions
Defining a Function
Local and global variables
Default argument
Keyword arguments
Closures
Higher order functions
map functions
Modules
Introduction to Module
Importing Modules
Submodules
Strings Methods of string objects
String module
String formatting
The pprint module the REPR module unicode
File Handling Open a file in Python.
Python file encoding.
Close a file in Python.
Python Write operation.
Python Read operation.
File read positions in Python.
Renaming and deleting files in Python.
Python file object methods.
Pickling the data
Reading file from URL
Exceptions
Try statement
NameError
TypeError
Handing Exceptions
Raising Exceptions
Finally
Custom Exception Objects
List Data Type
1.    A list is a collection which is ordered and changeable.
2.    Allows duplicate members
3.    In Python lists are written with square brackets.
4.    Heterogeneous objects are allowed

1.    append() - Add an element to the end of the list


2.    extend() - Add all elements of a list to the another list
3.    insert() - Insert an item at the defined index
4.    remove() - Removes an item from the list
5.    pop() - Removes and returns an element at the given index
6.    clear() - Removes all items from the list
7.    index() - Returns the index of the first matched item
8.    count() - Returns the count of number of items passed as an argument
9.    sort() - Sort items in a list in ascending order
10. reverse() - Reverse the order of items in the list
11. copy() - Returns a shallow copy of the list
2. Tuple Data Type
1.       Tuple data type is exactly same as List data Type.
2.       A tuple is a collection which is ordered and unchangeable.
3.       In Python tuples are written with round brackets.
4.       Tuple is the read only
3. Set Data Type
1.    A set is a collection which is unordered and unindexed.
2.    In Python sets are written with curly brackets.
3.    Insertion Order is not preserved
4.    Duplicates are not allowed
5.    Heterogenous objects are allowed
6.    Index concept is not applicable
7.    It is a mutual collection

Dict Types

1.    A dictionary is a collection which is unordered, changeable and indexed.


2.    In Python dictionaries are written with curly brackets, and they have keys and values.
3.    Duplicate Keys are not allowed but values can be duplicated.
4.    Heterogeneous objects are allowed for both key and values
5.    Insertion order is not preserved
6.    Dict are mutable
7.    Dict are dynamic
8.    Indexing and slicing concepts are not application.
e keys and values.
Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtractiox-y
* Multiplicatx*y
/ Division x/y
% Modulus x%y
** Exponent x**y
// Floor Divisx/ y

Python Comparison Operators


Operator Name Example
== Equal x==y
!= Not equal x!=y
>  Greater thx>y
<  Less than x<y
>= Greater thx>=y
<= Less than x<=y

Python Logical Operators


Operator Example Result
and (x and y) is True if both x and y are true.
or (x or y) is True if either x or y is true.
not (x not y) If a condition is true then Logical not operator will make false.

Python Assignment Operators


Operator Shorthand Expression
+= x+=y x = x + y
-= x-= y x = x -y
*= x*= y x = x*y
/= x/= y x = x/y
%= x%= y x = x%y
**= x**=y x = x**y
//= x//=y x = x//y

Python Bitwise Operators


OperatorShorthand Expression
& And x&y
| Or x|y
^ Xor x^y
~ Not ~x
<<  Shift left x <<y
>>  Shift right x >>y
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description
in  Returns True if a sequence with
not in Returns True if a sequence with

not in Returns Tru


x not in y
Result
Sum of x and y.
Difference of x and y.
Product of x and y.
Quotient of x and y.
Remainder of x divided by y.
x**y will give x to the power y
The division of operands where the result is the quotient in which the digits after the decimal point are removed.

Result
True if x is exactly equal to y.
True if x is exactly not equal to y.
True if x (left-hand argument) is greater than y (right-hand argument).
True if x (left-hand argument) is less than y (right-hand argument).
True if x (left-hand argument) is greater than or equal to y (left-hand argument).
True if x (left-hand argument) is less than or equal to y (right-hand argument).

d y are true.

e then Logical not operator will make false.

Description
Adds 2 numbers and assigns the result to left operand.
Subtracts 2 numbers and assigns the result to left operand.
Multiplies 2 numbers and assigns the result to left operand.
Divides 2 numbers and assigns the result to left operand.
Computes the modulus of 2 numbers and assigns the result to left operand.
Performs exponential (power) calculation on operators and assign value to the equivalent to left operand.
Performs floor division on operators and assign value to the left operand.

Description
Bits that are set in both x and y are set.
Bits that are set in either x or y are set.
Bits that are set in x or y but not both are set.
Bits that are set in x are not set, and vice versa.
Shift the bits of x, y steps to the left
Shift the bits of x, y steps to the right.
a sequence is presented in an object:
Example
x in y
x not in y
1              Type Conversion
Casting in python is therefore done using constructor functions:
1.    int() - constructs an integer number from an integer literal, a float literal (by rounding down to the
2.    float() - constructs a float number from an integer literal, a float literal or a string literal (providing
3.    str() - constructs a string from a wide variety of data types, including strings, integer literals and fl
2              Truth Values
We can use any object to test the truth value. By providing the condition in the if or while statement, the checking
al (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)
or a string literal (providing the string represents a float or an integer)
trings, integer literals and float literals.

le statement, the checking can be done.


ents a whole number)
1             Conditional Statements

If Statement
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
if-elif Statement
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 Statement
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.

Transfer Statements
7.1 Break
break statement we can stop the loop before it has looped through all the items:
We can use break statement inside loops to break loop execution based on some
condition.
Continue
With the continue statement we can stop the current iteration of the loop, and continue with the next:
pass
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to

Iterative Statements
For
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.
9.2 While

10 Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for
•              • A variable name must start with a letter or the underscore character
•              • A variable name cannot start with a number
•              • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
•              • Variable names are case-sensitive (age, Age and AGE are three different variables)
with the next:

ut in the pass statement to avoid getting an error.

a set, or a string).
me, total_volume). Rules for Python variables:

-z, 0-9, and _ )


1              Functions
1.    A function is a block of code which only runs when it is called.
2.    You can pass data, known as parameters, into a function.
3.    A function can return data as a result.
1.1         Creating Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
1.2         Calling Function
To call a function, use the function name followed by parenthesis:

1.3         Arguments
1.    Information can be passed into functions as arguments.
2.    Arguments are specified after the function name, inside the parentheses.
3.    You can add as many arguments as you want, just separate them with a comma.
4.    The following example has a function with one argument (fname).
5.    When the function is called, we pass along a first name, which is used inside the fun

1.4         Default Parameter Value


If we call the function without argument, it uses the default value:

1.5         Passing a List of Parameter


You can send any data types of argument to a function (string, number, list, dictionary e

1.6         Return Values


To let a function, return a value, use the return statement:

1.7         Keyword Arguments


You can also send arguments with the key = value syntax.
This way the order of the arguments does not matte

1.8         Arbitrary Keyword Arguments


If you do not know how many keyword arguments that will be passed into your function, add two
This way the function will receive a dictionary of arguments, and can access the items accordingly:
If the number of keyword arguments is unknown, add a double ** before the parameter name:

1.9         Closures Function

1.    We must have a nested function (function inside a function).


2.    The nested function must refer to a value defined in the enclosing function.
3.    The enclosing function must return the nested function.
4.    Closures can avoid the use of global values and provides some form of data hiding.
5.    It can also provide an object-oriented solution to the problem.
6.    When there are few methods (one method in most cases) to be implemented in a class, closures ca
But when the number of attributes and methods get larger, better implement a class.
he parentheses.
ate them with a comma.

which is used inside the function to print the full name:

g, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an a

ur function, add two asterix: ** before the parameter name in the function definition.
ccordingly:

data hiding.

nted in a class, closures can provide an alternate and more elegant solutions.
g. if you send a List as an argument, it will still be a List when it reaches the function:

You might also like