Sunday, 5 August 2018

Python :: 14 - File Operations

File operations



Files in Python :
===============
Data is stored in files.

Opening a files:
----------------
file handler = open("filename","open mode","buffering")

open modes :
----------
w - write data into file.If data is already present in the file, it would be
deleted and present data will be stored.

r - To read data from file. The file pointer is positioned at the beginning of file.

a - To append data to the file. Appending means adding at the end of existing data.
     The file pointer is placed at the end of the file. If the file does not exist,
 it will create new file to write data.

w+ - To write and read data of a file. The previous data in the file will deleted.

r+ - To read and write into a file. The previous data in the file will not be deleted.
 The file pointer is placed at beginning of the file.

a+ - To append and read data of a file. The file pointer will be at the end of the file.
 if file exists. If the file does not exist,it creates a new file for reading and
 writing.

x - To open the file in exclusive creation mode.The file creation fails if the file
   already exists.


A buffer represents a temporary block of memory. 'buffering is an optional integer used to set the
size of the buffer for the file. if we specify 500 then it will use 500 bytes of data to read and write.
If we don't mention any buffering integer , then default buffer size would be 4096 or 8192 bytes.


f = open("myfile.txt","w")

Here f represents file handler or file object. It refers to the file with the name 'myfile.txt' that is opened in 'w' mode.

Closing File :
----------------
A file which is opened should be using the close()  method. Once file is opened but not closed, then
data of the file may be corrupted or deleted in some cases. Also if the file is not close, the memory
utilized by the file not freed, leading to problems like insufficient memory. This happens when we are
working with several files simultaneously. Hence it is mandatory to close file.

f.close()

1. Python program to create a text file to store individual characters.

write :
-------
f = open('myfile.txt','w')

str = input("Enter text:")

f.write(str)

f.close()

Read :
-------
f = open("myfile.txt","r")

str = f.read()

print(str)

f.close()

Append :
-------
f = open("myfile.txt","a")

str = input("Enter string:\n")

f.write(str)


f.close()


2. Python program to store a group of strings into a text file.

f = open('myfile.txt','w')

print("Please enter text(@ at end):\n")

str = None
while(str != '@'):
str = input()

if(str != '@'):
f.write(str+"\n")

f.close()



3. Program to check whether the file is exist or not.

import os,sys

fname = input("Enter file name")

if os.path.isfile(fname):
f = open(fname,'r')
str = f.read()
print(str)
else:
print(fname+'does not exist')
exit(1)

The with statement: 
===================

The with statement can be used while opening a file.
The advantage of with statement is it will take care of closing a file which is opened by it.
Hence we need not close the file explicitly.

The format of using with statement

with open("filename","openmode") as fileobject:

1. A python program to use with open a file and write some strings to the file.

with open('myfile.txt','w') as f:
f.write('I am learner\n')  
f.write('Python is attractive\n')

details.txt:
-----------
"id","name","sal","gender","dno"
101,Ravi,2000,M,10
102,Krish,3000,M,10
103,Rama,4000,F,20
104,Ramu,5000,M,20
105,lalitha,4000,F,10
Difference between read(),readline(),readlines()
----------------------------------------------
>>>file_path = 'C:\\Users\\lenovo\\Desktop\\details.txt'
>>> f = open(file_path,'r')
>>> f.read()
'"id","name","sal","gender","dno"\n101,Ravi,2000,M,10\n102,Krish,3000,M,10\n103,Rama,4000,F,20\n104,Ramu,5000,M,20\n105,lalitha,4000,F,10'
>>> f.readline()
''
>>> f = open(file_path,'r')
>>> f.readline()
'"id","name","sal","gender","dno"\n'
>>> f.readline()
'101,Ravi,2000,M,10\n'
>>> f.readline()
'102,Krish,3000,M,10\n'
>>> f.readlines()
['103,Rama,4000,F,20\n', '104,Ramu,5000,M,20\n', '105,lalitha,4000,F,10']

Python :: 13 - Package

packages



What are packages?

We don't usually store all of our files in our computer
in the same location.We use a well-organized hierarchy of
directories for easier a
ccess.


Similar files are kept in the same directory, for example, we may keep all the songs
in the "music" directory. Analogous to this, Python has packages for directories and
modules for files.

As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.Similar, as a directory can contain
sub-directories and files, a Python package can have sub-packages and modules.

A directory must contain a file named __init__.py in order for Python to consider
it as a package. This file can be left empty but we generally place the initialization
code for that package in this file.




mypackage --folder
   |
   |
   |--> __init__.py
   |--> calculations.py
   |
   |subpackage folder
|
|--> __init__.py
|-->aggregration.py
|

pkg_example.py

Here mypackage and pkg_example.py should be under same folder.

if you want to specify mypackage in golbal then copy it to site-package folder.

>>import sys
>>sys.path

calculation.py:
==============
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b

aggregration.py:
================
def sum(lst):
s = 0
for i in lst:
s = s+i
return s


pkg_example.py:
==============
import mypackage.calculation as k
import mypackage.subpackage.aggregration as l


val = k.add(10,20)
a = [10,20,30]
print("The value is ",val)

b = l.sum(a)
print("the sum of elements of list is",b)

Python :: 12 - Modules

Functions


Function:
==========
 A function is similar to a program that consists of a group of statements that are
 intended to perform a specific task. The main purpose of a function is to perform
 a specific task or work. Thus when there are several tasks to be performed, the
 programmer will write several functions.

 Built in functions : print(),sqrt(),power()
 User defined functions: Programmer can create their own functions.


Advantage of functions :
===================
1. Once function is written, it can be reused as and when required. So functions are
also called reusable code. Because of re usability , the programmer can avoid code
redundancy. It means it is possible to avoid writing the same code again and again.

2. Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated to software.

3.  When there is error in the software, the corresponding function can be modified
with out disturbing the other functions in the software.

4. The use of functions in a program will reduce the length of the program.


Difference between function and method:
=====================================

function : group of statements
method   : function inside a class.

So, please remember that a function and a method are same except their placement and
the way they are called.


Defining a function:
===================

We can define a function using keyword def followed by function name after the function name
, we should write parentheses() which may contain parameters. Consider the syntax of function
as follows.

def functionname(param1,param2...):
"""function docstring """
function statements

example :
def sum(a,b):
""" this function finds sum of two number"""
c = a + b
print(c)

def --> function specified
sum --> function name
a,b --> function parameters

After parentheses, we put a colon(:) represents the begining of the function body.

Function body contains group of statements called as 'suite'.
we should write string in first line of function body called it as 'docstring'

'docstrings' are optional.

1. Write a function that accepts two values and find their sum and return results

def sum(a,b):
""" this function find sum of two numbers"""
c = a+b
return c

x = sum(10,15)
y = sum(20,30)

2. Write a program to test whether a number is even or odd?

def even_odd(num):
 """ even number or odd number"""
if(num % 2 ==0):
print(num, "is even")
else:

print(num, " is odd")
even_odd(12)
even_odd(13)


Returning multiple values from a function :
===========================================


def sum_sub(a,b):
   c = a+b
   d = a-b
   return c,d

i,j = sum_sub(10,20)                 

print("the sum is %d and sub is %d"%(i,j))



Formal and actual arguments :
=======================

def sum(a,b):          # a,b are formal arguments
c = a+b
print(c)
x = 10
y = 15
sum(x,y)     # x,y are actual arguments


Local and Global variables :
=========================

Local : When we declare a variable inside a function, it becomes a local variable.
local variable scope is limited only to that function where it is created.
That means the local variable value is available only in that function
and not outside of the function.
Global: When a variable is declared above a function , it becomes global variable.
Such variables are available to all the functions which are written after it.


a=1  # this is global variable
def myfunction():
b =2   # this is local variable
a=10
print('a = ',a)
print('b = ',b)

myfunction()
print(a)      #available
print(b)      # Error,not available

a1
b

Recursive functions:
===================

A function that calls itself is known as 'recursive function'.

1. Python program to calculate factorial of give number

def fact(n):
if n == 0:
res = 1
else:
res = n * fact(n-1)
return res


i = 4
print('factorial of {} is {}'.format(i,fact(i)))


Anonymous function or Lambadas
==============================


A function without a name is called 'anonymous function'. So far, the functions we wrote were
defined using the keyword 'def'. But anonymous functions are not defined using  'def'. They are
defined using the keyword 'lambda' and hence they are also called 'Lambada functions'

def square(x):
return x*x

square(5)


The same function can be written as
lambda x : x * x

1. Python program that create a lambda function that return a square value of a given number

f = lambda x : x * x

value = f(5)
print('square of 5 = ',value)



Lambda function contain only one expression and they return the result implicitly.
Hence we should not write any return statement in lambda functions.
Here is lambda function that calculates sum of two numbers.

2. Python function calculate sum of two numbers.

f = lambda x,y : x+y

res = f(10,20)
print("sum is ", res)

lambdas with filter() function :
--------------------------------

The filter() is useful to filter out the elements of sequnce depending  on the
result of a function. We should supply a sequnce to filter function as:

filter(function,sequnce)




1. A Python program using filter() to filter out even numbers from a list

def is_even(n):
if n%2 == 0:
return True
else:
return false
lst = [12,21,24,31,56]

lst1 = list(filter(is_even,lst))
print(lst1)

c:\> python fun.py
[12,24,56]

2. lambda function that returns even numbers

lst = [12,21,24,31,56]

lst1 = list(filter(lambda x: (x%2==0),lst))
print(lst1)




lambdas with map() function :
--------------------------------
The map() function is similar to filter() function.but it acts on each element of the
sequence and perhaps changes the elements. The format of map() function is:

map(functoin,sequnce)

The 'function' performs a specified operation on all the elements of the sequnce and the
modified elements are returned which can be stored in another sequnce.


1. Python to find square of each element of sequnce

def squares(x):
return x*X
lst = [1,2,3,4]
lst1 = list(map(squares,lst))
print(lst1)


f = lambda x : x*x


lst = [1,2,3,4]
for i in lst:
print(f(i))

lst1 = list(map(lambda x: x*x , lst))
print(lst1)



Types of arguments:
-------------------
1.Positional arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments

1.positional arguments

These are the arguments passed to the function
in correct positional order.
Here number of arguments should be same.

def add(a,b):
return a+b
res = add(100,200)
print(res)

2. Keyword arguments

We can pass argument values by keyword i.e by parameter name

def add(a,b):
print("a value is",a)
print("b value is",b)
return a+b
res = add(10,b=30)
print(res)
res1 = add(10,40)
print(res1)
res1 = add(b=10,a=40)
print(res1)

Note : here the order is not immportant.But no.of arguments should be match.

We can take both positional arguments and keyword arguments simultaneously. But
first we have take positional arguments and keyword arguments otherwise will get
error

def add(a,b,c)
return a+b+c
res = add(10,b=20,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
result is 60


def add(a,b,c):
return a+b+c
res = add(a=20,10,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
  File "add.py", line 4
    res = add(a=20,10,c=30)
                  ^
SyntaxError: positional argument follows keyword argument

3. Default arguments

Sometimes we have to provide default values for our positional arguments

def add(a=10,b=20):
return a+b

#res = add(a=40,b=50)
res = add()
print("sum is",res)

If we are not passing any name then only default value will be considered.

Note :
After default argument we should not take any non default arguments.

def add(a=10,b):
return a+b

4. Variable length arguments

Sometimes we can pass variable number of arguments to our function, such type of
arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def add(*n):
total = 0
for i in n:
total = total+i
print("the sum is",total)
add()
add(10,20)
add(10,20,30)

Note :
we can mix variable length arguments and positional arguments.

def fun1(n1,*t):
print(n1)
for i in t:
print(i)
fun1(10)
fun1(10,20,30,40,50)
fun1(10,'A','B','C')

Output :
10
10
20
30
40
50
10
A
B
C
Note : After variable length argument, if we take any other arguments then
we should provide values as keyword arguments.

def fun1(*t,n1):
print(n1)
for i in t:
print(i)
fun1(10,n1=10)

output :
C:\Users\lenovo\Desktop>python def_ex.py
10
10

Note : We can declare keyword variable length arguments also.
For this we have to use **.

eg : def fun1(**n)

we can call this function by passing any number of keyword arguments.
Internally these keyword arguments will be stored inside a dictionary.

def details(**kwargs):
for k,v in kwargs.items():
print(k,v)

details(id=101,name='Phani')
details(n1=10,n2=20,n3=30)

output:
id 101
name Phani
n1 10
n2 20
n3 30

eg:
def details(id,*marks,**kwargs):
print(id)
for i in marks:
print(i)
for k,v in kwargs.items():
print(k,v)
details(101,10,20,30,40,name='Ravi',address='Hyderbad')

Python :: 11 - Functions

Functions


Function:
==========
 A function is similar to a program that consists of a group of statements that are
 intended to perform a specific task. The main purpose of a function is to perform
 a specific task or work. Thus when there are several tasks to be performed, the
 programmer will write several functions.

 Built in functions : print(),sqrt(),power()
 User defined functions: Programmer can create their own functions.


Advantage of functions :
===================
1. Once function is written, it can be reused as and when required. So functions are
also called reusable code. Because of re usability , the programmer can avoid code
redundancy. It means it is possible to avoid writing the same code again and again.

2. Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated to software.

3.  When there is error in the software, the corresponding function can be modified
with out disturbing the other functions in the software.

4. The use of functions in a program will reduce the length of the program.


Difference between function and method:
=====================================

function : group of statements
method   : function inside a class.

So, please remember that a function and a method are same except their placement and
the way they are called.


Defining a function:
===================

We can define a function using keyword def followed by function name after the function name
, we should write parentheses() which may contain parameters. Consider the syntax of function
as follows.

def functionname(param1,param2...):
"""function docstring """
function statements

example :
def sum(a,b):
""" this function finds sum of two number"""
c = a + b
print(c)

def --> function specified
sum --> function name
a,b --> function parameters

After parentheses, we put a colon(:) represents the begining of the function body.

Function body contains group of statements called as 'suite'.
we should write string in first line of function body called it as 'docstring'

'docstrings' are optional.

1. Write a function that accepts two values and find their sum and return results

def sum(a,b):
""" this function find sum of two numbers"""
c = a+b
return c

x = sum(10,15)
y = sum(20,30)

2. Write a program to test whether a number is even or odd?

def even_odd(num):
 """ even number or odd number"""
if(num % 2 ==0):
print(num, "is even")
else:

print(num, " is odd")
even_odd(12)
even_odd(13)


Returning multiple values from a function :
===========================================


def sum_sub(a,b):
   c = a+b
   d = a-b
   return c,d

i,j = sum_sub(10,20)                 

print("the sum is %d and sub is %d"%(i,j))



Formal and actual arguments :
=======================

def sum(a,b):          # a,b are formal arguments
c = a+b
print(c)
x = 10
y = 15
sum(x,y)     # x,y are actual arguments


Local and Global variables :
=========================

Local : When we declare a variable inside a function, it becomes a local variable.
local variable scope is limited only to that function where it is created.
That means the local variable value is available only in that function
and not outside of the function.
Global: When a variable is declared above a function , it becomes global variable.
Such variables are available to all the functions which are written after it.


a=1  # this is global variable
def myfunction():
b =2   # this is local variable
a=10
print('a = ',a)
print('b = ',b)

myfunction()
print(a)      #available
print(b)      # Error,not available

a1
b

Recursive functions:
===================

A function that calls itself is known as 'recursive function'.

1. Python program to calculate factorial of give number

def fact(n):
if n == 0:
res = 1
else:
res = n * fact(n-1)
return res


i = 4
print('factorial of {} is {}'.format(i,fact(i)))


Anonymous function or Lambadas
==============================


A function without a name is called 'anonymous function'. So far, the functions we wrote were
defined using the keyword 'def'. But anonymous functions are not defined using  'def'. They are
defined using the keyword 'lambda' and hence they are also called 'Lambada functions'

def square(x):
return x*x

square(5)


The same function can be written as
lambda x : x * x

1. Python program that create a lambda function that return a square value of a given number

f = lambda x : x * x

value = f(5)
print('square of 5 = ',value)



Lambda function contain only one expression and they return the result implicitly.
Hence we should not write any return statement in lambda functions.
Here is lambda function that calculates sum of two numbers.

2. Python function calculate sum of two numbers.

f = lambda x,y : x+y

res = f(10,20)
print("sum is ", res)

lambdas with filter() function :
--------------------------------

The filter() is useful to filter out the elements of sequnce depending  on the
result of a function. We should supply a sequnce to filter function as:

filter(function,sequnce)




1. A Python program using filter() to filter out even numbers from a list

def is_even(n):
if n%2 == 0:
return True
else:
return false
lst = [12,21,24,31,56]

lst1 = list(filter(is_even,lst))
print(lst1)

c:\> python fun.py
[12,24,56]

2. lambda function that returns even numbers

lst = [12,21,24,31,56]

lst1 = list(filter(lambda x: (x%2==0),lst))
print(lst1)




lambdas with map() function :
--------------------------------
The map() function is similar to filter() function.but it acts on each element of the
sequence and perhaps changes the elements. The format of map() function is:

map(functoin,sequnce)

The 'function' performs a specified operation on all the elements of the sequnce and the
modified elements are returned which can be stored in another sequnce.


1. Python to find square of each element of sequnce

def squares(x):
return x*X
lst = [1,2,3,4]
lst1 = list(map(squares,lst))
print(lst1)


f = lambda x : x*x


lst = [1,2,3,4]
for i in lst:
print(f(i))

lst1 = list(map(lambda x: x*x , lst))
print(lst1)



Types of arguments:
-------------------
1.Positional arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments

1.positional arguments

These are the arguments passed to the function
in correct positional order.
Here number of arguments should be same.

def add(a,b):
return a+b
res = add(100,200)
print(res)

2. Keyword arguments

We can pass argument values by keyword i.e by parameter name

def add(a,b):
print("a value is",a)
print("b value is",b)
return a+b
res = add(10,b=30)
print(res)
res1 = add(10,40)
print(res1)
res1 = add(b=10,a=40)
print(res1)

Note : here the order is not immportant.But no.of arguments should be match.

We can take both positional arguments and keyword arguments simultaneously. But
first we have take positional arguments and keyword arguments otherwise will get
error

def add(a,b,c)
return a+b+c
res = add(10,b=20,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
result is 60


def add(a,b,c):
return a+b+c
res = add(a=20,10,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
  File "add.py", line 4
    res = add(a=20,10,c=30)
                  ^
SyntaxError: positional argument follows keyword argument

3. Default arguments

Sometimes we have to provide default values for our positional arguments

def add(a=10,b=20):
return a+b

#res = add(a=40,b=50)
res = add()
print("sum is",res)

If we are not passing any name then only default value will be considered.

Note :
After default argument we should not take any non default arguments.

def add(a=10,b):
return a+b

4. Variable length arguments

Sometimes we can pass variable number of arguments to our function, such type of
arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def add(*n):
total = 0
for i in n:
total = total+i
print("the sum is",total)
add()
add(10,20)
add(10,20,30)

Note :
we can mix variable length arguments and positional arguments.

def fun1(n1,*t):
print(n1)
for i in t:
print(i)
fun1(10)
fun1(10,20,30,40,50)
fun1(10,'A','B','C')

Output :
10
10
20
30
40
50
10
A
B
C
Note : After variable length argument, if we take any other arguments then
we should provide values as keyword arguments.

def fun1(*t,n1):
print(n1)
for i in t:
print(i)
fun1(10,n1=10)

output :
C:\Users\lenovo\Desktop>python def_ex.py
10
10

Note : We can declare keyword variable length arguments also.
For this we have to use **.

eg : def fun1(**n)

we can call this function by passing any number of keyword arguments.
Internally these keyword arguments will be stored inside a dictionary.

def details(**kwargs):
for k,v in kwargs.items():
print(k,v)

details(id=101,name='Phani')
details(n1=10,n2=20,n3=30)

output:
id 101
name Phani
n1 10
n2 20
n3 30

eg:
def details(id,*marks,**kwargs):
print(id)
for i in marks:
print(i)
for k,v in kwargs.items():
print(k,v)
details(101,10,20,30,40,name='Ravi',address='Hyderbad')

Python :: 10 - Tuple and Dictionaries

Tuple and Dictionaries



Tuple:
=========

>A tuple is a Python sequence which stores a group of elements or items.

>Main difference between tuple and list is, Tuples are immutable but list are mutable.

Hence we can not perform operations like append(),extend(),insert(),remove(),pop()
and clear() on tuples.

Creating Tuples :
---------------

1. creating empty tuple
>>> tup1 = ()
>>> type(tup1)
<class 'tuple'>

2. if single element by default will take integer so to make it tuple then it should be ended with ,
>>> tup1 = (10)
>>> type(tup1)
<class 'int'>
>>> tup1 = (10,)
>>> type(tup1)
<class 'tuple'>
>>>

3. type casting
>>> tup1 = [10,20,30]
>>> type(tup1)
<class 'list'>
>>> tup2 = tuple(tup1)
>>> type(tup2)
<class 'tuple'>

4. using range function

>>> a = tuple(range(1,10,2))
>>> a
(1, 3, 5, 7, 9)


Accessing Tuple elements:
========================

tup = (50,60,70,80,90,100)

>>> tup = (50,60,70,80,90,100)
>>> print(tup[0])
50
>>> print(tup[5])
100
>>> print(tup[-1])
100
>>> print(tup[-6])
50
>>> print(tup[:])
(50, 60, 70, 80, 90, 100)
>>> print(tup[1:4])
(60, 70, 80)
>>> print(tup[::2])
(50, 70, 90)
>>> print(tup[::-2])
(100, 80, 60)
>>> print(tup[::-1])
(100, 90, 80, 70, 60, 50)
>>> print(tup[-4:-1])
(70, 80, 90)


>>> student = (10,'srinivas',50,60,65,61,70)
>>> student
(10, 'srinivas', 50, 60, 65, 61, 70)

>>> rno,name = student[0:2]
>>> rno
10
>>> name
'srinivas'
>>> marks = student[2:7]
>>> type(marks)
<class 'tuple'>
>>> for i in marks:
print(i)


50
60
65
61
70

Basic operations on Tuples :
-----------------------------

1. Finding length
2. Concatenation
3. repetition
4. membership


>>> student = (10,'srinivas',50,60,65,61,70)
>>> len(student)
7
>>> fees = (25000.00,)*4
>>> fees
(25000.0, 25000.0, 25000.0, 25000.0)
>>> type(fees)
<class 'tuple'>
>>> student1 = student + fees
>>> student1
(10, 'srinivas', 50, 60, 65, 61, 70, 25000.0, 25000.0, 25000.0, 25000.0)
>>> name = 'srinivas'
>>> name in student1
True

>>> name not in student1
False

>>> tpl = (10,11,12)
>>> tpl1 = tpl *3
>>> tpl1
(10, 11, 12, 10, 11, 12, 10, 11, 12)


Functions to process Tuples :
============================

>>> tpl = (1,3,2,4,13,23,22,19,2,13,22,5)

>>> len(tpl)
12


>>> min(tpl)
1


>>> max(tpl)
23


>>> tpl.count(2)
2


>>> tpl.index(2)
2

>>> sorted(tpl)
[1, 2, 2, 3, 4, 5, 13, 13, 19, 22, 22, 23]


>>> sorted(tpl,reverse = True)
[23, 22, 22, 19, 13, 13, 5, 4, 3, 2, 2, 1]


eval function :
==============

num = eval(input("Enter the elements in (): "))

>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): (1,2,3,4)
>>> num
(1, 2, 3, 4)
>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): [1,2,3,4]
>>> num
[1, 2, 3, 4]
>>> num = eval(input("Enter the elements in (): "))
Enter the elements in (): 12,2,3,44
>>> num
(12, 2, 3, 44)

1. Write a program to accepts elements in the form of tuple and display their sum and average.

num = eval(input("enter the elements in ():"))
s = 0
n = len(num)
for i in num:
s = s+i

print("sum is: ",s)
print("avg is: ",s/n)

2. Usage of split function

>>> num = input("Enter the elements in , separator: ")
Enter the elements in (): 1,2,3,4,5
>>> num
'1,2,3,4,5'
>>> str = num.split(',')
>>> str
['1', '2', '3', '4', '5']
>>> tup = tuple(str)
>>> tup
('1', '2', '3', '4', '5')

Nested Tuples:
===========

A tuple inserted inside another tuple is called nested tuple.

tup = (50,60,70,80,90,(200,201))   # tuple with 6 elements

>>> tup = (50,60,70,80,90,(200,201))
>>> tup[5]
(200, 201)
>>> tup[5][0]
200
>>>

Inserting elements in Tuple :
===========================

num = eval(input("enter the elements in ():"))
pos = int(input("Enter the position number to insert value:\n"))
new = int(input("enter the values to insert\n"))

temp = num[0:pos-1]
new_tup =(new,)
temp2 = num[pos-1:len(num)+1]
new_temp = temp+new_tup+temp2

print("final tuple is :\n",new_temp)

output:
-------
enter the elements in ():(10,20,30,40,50)
Enter the position number to insert value:
3
enter the values to insert
25
final tuple is :
 (10, 20, 25, 30, 40, 50)


 Dictionaries :
 ================

A Dictionary represents a group of elements arranged in the form of key-value pairs.

>>> details = {'rno':101,'name':'srinivas','sal':2000}


>>> print("Roll no is {}".format(details['rno']))

Roll no is 101
>>>  print("name is : ",details['name'])

name is :  srinivas

Operations on Dictionaries:
-------------------------
To access elements of dictionary , we should not use indexing and slicing.

For example dcit[0] or dict[1:3] etc. expressions will give error.

To access the value associated with a key, we can mentions the key name inside square braces.

as, dict['name']

1. Using length function

>>> details

{'rno': 101, 'name': 'srinivas', 'sal': 2000}
>>> len(details)

3

>>> details['sal']

2000
>>> details['sal'] = 4000

>>> details

{'rno': 101, 'name': 'srinivas', 'sal': 4000}
>>>

>>> details

{'rno': 101, 'name': 'srinivas', 'sal': 4000}

>>> details['location'] = 'Hyderabad'      # add element

>>> details

{'rno': 101, 'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}

>>> del details['rno']            # remove element

>>> details

{'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}

>>> details

{'name': 'srinivas', 'sal': 4000, 'location': 'Hyderabad'}
>>> 'gender' in details

False
>>> 'location' in details

True

# Keys should be unique key. It means duplicate keys are not allowed.
If we enter same key again, the old key will be overwritten and only the new key will be available.

>>> details = {1:'ravi',2:'rajesh',1:'suresh'}

>>> details

{1: 'suresh', 2: 'rajesh'}

# Keys should be immutable type. we can use a number,string or tuple as keys since they are immutable.

We can not use lists or dictionaries as keys. If they used as keys, we will get 'TypeError'.
consider following example


>>> emp = {'rno':101,['name']:'srinivas'}

Traceback (most recent call last):
  File "<pyshell#182>", line 1, in <module>
    emp = {'rno':101,['name']:'srinivas'}
TypeError: unhashable type: 'list'

Dictionary Methods :
=====================

Various methods are provided to process the elements of a dictionary. These methods
generally retrieve or manipulate the contents of a dictionary.

>>> d = {'eid':101,'ename':'John','sal':24000}

>>> d

{'eid': 101, 'ename': 'John', 'sal': 24000}
>>> d1 = d.copy()

>>> d1

{'eid': 101, 'ename': 'John', 'sal': 24000}

>>> d.items()

dict_items([('eid', 101), ('ename', 'John'), ('sal', 24000)])
>>> d.keys()

dict_keys(['eid', 'ename', 'sal'])
>>> d.values()

dict_values([101, 'John', 24000])




1. Write a program to create dictionary and find sum of values.

>>> a = eval(input("enter elements in {}:"))

enter elements in {}:{'A':10,'B':20}
>>> a.values()

dict_values([10, 20])
>>> sum(a.values())

2. Write a program to create a dictionary from keyboard and display elements.

x = {}
n = int(input("no.of elements:"))

for i in range(n):
print('enter key: \n',end = '')
k=input()
print('enter value: \n',end = '')
v=int(input())
x.update({k:v})



print('the dictionary is :',x)

NOTE: The key-value pairs which are entered by us from key board are not displayed
in the same order. Dictionaries will not maintain orderliness of pairs.


usage of get() method:
------------------

x = {}

n = int(input("Enter no.of players:\n"))

for i in range(n):
k = input("Enter player name : \n")
v = int(input("Enter score:\n"))
x.update({k:v})

print("Team players are: \n" , x.keys())
player_name = input("Enter the player name : \n")

#get function return the value of key , if key not found then return -1
score=x.get(player_name,-1)

if (score != -1):
print('%s scored %d'%(player_name,score))
else:
print("Player not found")

4. Python program to show usage of for loop to retrieve elements of dictionary.
-
colors = {'R':'red','G':'Green','B':'Blue'}

for i in colors:
print(i)
for j in colors:
print(colors[j])

print(colors.items())

for k,v in colors.items():
print("key ={} and value = {}".format(k,v))

5. Python program find occurrences of each character in given string.

letters = {}
x = "Book"

for i in x:
letters[i] = letters.get(i,0)+1

print(letters)

for k,v in letters.items():
print(" {} is found {} times".format(k,v))



dictionary = {'key' : 'value',
'key_2': 'value_2'}

nested_dict = { 'dictA': {'key_1': 'value_1'},
                'dictB': {'key_2': 'value_2'}}


How to create a nested dictionary

people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}

print(people)


Access the elements using the [] syntax
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['gen'])



How to change or add elements in a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'}}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['gen'] = 'Female'
people[3]['married'] = 'No'

print(people[3])



Add another dictionary to the nested dictionary

people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'gen': 'Female', 'married': 'No'}}

people[4] = {'name': 'Peter', 'age': '29', 'gen': 'Male', 'married': 'Yes'}

print(people[4])


How to delete elements from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'gen': 'Female', 'married': 'No'},
          4: {'name': 'Peter', 'age': '29', 'gen': 'Male', 'married': 'Yes'}}

del people[3]['married']
del people[4]['married']

print(people[3])
print(people[4])



How to delete dictionary from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'gen': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gen': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'gen': 'Female'},
          4: {'name': 'Peter', 'age': '29', 'gen': 'Male'}}

del people[3], people[4]
print(people)


How to iterate through a Nested dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

for p_id, p_info in people.items():
    print("\nPerson ID:", p_id)
 
    for key in p_info:
        print(key + ':', p_info[key])


Key Points to Remember:
1.Nested dictionary is an unordered collection of dictionary
2.Slicing Nested Dictionary is not possible.
3.We can shrink or grow nested dictionary as need.
4.Like Dictionary, it also has key and value.
5.Dictionary are accessed using key.

Python :: 09 - Lists

Lists



List :
=====

List is similar to array.

Array :  similar datatype
List : Different datatypes

List are represented by []

List slicing
[start:stop:stepsize]

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print(list)          # Prints complete list
print(list[0])       # Prints first element of the list
print(list[1:3])     # Prints elements starting from 2nd till 3rd
print(list[2:])      # Prints elements starting from 3rd element
print(tinylist * 2)  # Prints list two times
print(list + tinylist) # Prints concatenated lists
This produce the following result −

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']



Creating list using range() function :
----------------------------------------

range(start,stop,stepsize)


>>> lst = range(10)
>>> lst
range(0, 10)
>>> for i in lst:
...     print(i)
...
0
1
2
3
4
5
6
7
8
9


>>> lst = range(5,10)
>>> for i in lst:
...     print(i)
...
5
6
7
8
9

>>> i = 0
>>> while(i < len(lst)):
...     print(lst[i])
...     i += 1
...
5
6
7
8
9
>>>

>>> lst = range(10)
>>> type(lst)
<class 'range'>
>>> for i in lst:
...     print(i)
...
0
1
2
3
4
5
6
7
8
9
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Updating the elements of list :
-------------------------------



>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst = list(range(1,5))
>>> lst
[1, 2, 3, 4]
>>> lst.append(9)
>>> lst
[1, 2, 3, 4, 9]
>>> lst[1] = 8
>>> lst
[1, 8, 3, 4, 9]
>>> lst[1:3] = 10,11
>>> lst
[1, 10, 11, 4, 9]
>>> del lst[1]
>>> lst
[1, 11, 4, 9]

>>> lst
[1, 11, 4, 9]
>>> lst.reverse()
>>> lst
[9, 4, 11, 1]
>>> lst = [1,11,4,9]
>>> lst.remove(11)
>>> lst
[1, 4, 9]
>>> lst.reverse()
>>> lst
[9, 4, 1]
>>>


1. Write a program to print elements of list in reverse order.

days = ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY']

i = len(days)-1
print(i)

while(i >= 0):
print(days[i])
i -= 1

# using negative index

j = -1

while(j>=-len(days)):
print(days[j])
j -= 1


Concatenation of lists
---------------------

>>> lst1 = [10,20,30]
>>> lst2 = [40,50,60]
>>> lst = lst1 + lst2
>>> print(lst)
[10, 20, 30, 40, 50, 60]
>>>

Repetetion of list :
--------------------
>>> print(lst)
[10, 20, 30, 40, 50, 60]
>>> print(lst*2)
[10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60]


>>> print(lst)
[10, 20, 30, 40, 50, 60]
>>> a = 30
>>> print(a in lst)
True
>>>


>>> details = [101,'srinivas']
>>> rno,name = details
>>> rno
101
>>> name
'srinivas'
>>> a,b = 10,20
>>> a
10
>>> b
20
>>>




Aliasing and cloning lists:
---------------------------

Giving a new name to an existing  list is called 'aliasing'. The new name is called 'alias name'

>>> x = [10,20,30,40]
>>> y = x           
>>>
>>> id(x)
21150696
>>> id(y)
21150696
>>> x[1] = 50
>>> x
[10, 50, 30, 40]
>>> y
[10, 50, 30, 40]

If the programmer wants two independent lists, he should not go for aliasing. On other hand
he should use the cloing or copying.

>>> z = x[:]          # x is cloned as z
>>> x
[10, 50, 30, 40]
>>> z
[10, 50, 30, 40]
>>> x [0] = 60
>>> x
[60, 50, 30, 40]
>>> z
[10, 50, 30, 40]

The same can be achieved by copying the elements of one list to another list using copy()

>>> k = x.copy()
>>> x
[60, 50, 30, 40]
>>> k
[60, 50, 30, 40]
>>> x[3] = 70
>>> x
[60, 50, 30, 70]
>>> k
[60, 50, 30, 40]
>>>



Methods to process Lists:
=========================

>>> num = [10,20,30,40,50]
>>> n = len(num)

>>> print(' no.of elements %d'%n)
 no.of elements 5

>>> num.append(60)
>>> print('num after appending 60: ',num)

num after appending 60:  [10, 20, 30, 40, 50, 60]

>>> num.insert(0,5)

>>> print('num after inserting 5 at 0th position: ', num)

num after inserting 5 at 0th position:  [5, 10, 20, 30, 40, 50, 60]

>>> num1 = num.copy()
>>> print('newly created list num1 : ',num1)

newly created list num1 :  [5, 10, 20, 30, 40, 50, 60]

>>> num.extend(num1)
>>> print('num after appending num1: ',num)

num after appending num1:  [5, 10, 20, 30, 40, 50, 60, 5, 10, 20, 30, 40, 50, 60]

>>> n = num.count(50)
>>> print('no.of times 50 found in the list num : ', n)

no.of times 50 found in the list num :  2

>>> num.remove(50)
>>> print('num after removing 50 : ',num)
num after removing 50 :  [5, 10, 20, 30, 40, 60, 5, 10, 20, 30, 40, 50, 60]

>>> num
[5, 10, 20, 30, 40, 60, 5, 10, 20, 30, 40, 50, 60]
>>> num.pop()
60

>>> print('num after removing ending element: ', num)
num after removing ending element:  [5, 10, 20, 30, 40, 60, 5, 10, 20, 30, 40, 50]


>>> num.sort()
>>> print('num after sorting :', num)

num after sorting : [5, 5, 10, 10, 20, 20, 30, 30, 40, 40, 50, 60]


>>> num.reverse()
>>> print('num after reversing: ', num)

num after reversing:  [60, 50, 40, 40, 30, 30, 20, 20, 10, 10, 5, 5]

>>> num.clear()
>>> print('num after removing all elements: ', num)

num after removing all elements:  []



Finding biggest and smallest elements in a List :
--------------------------------------------------
>>> num
[10, 23, 43, 22, 25, 64, 39, 99]
>>> n1 = max(num)
>>> print(n1)
99
>>> n2 = min(num)
>>> print(n2)
10
>>>

Sorting the list of elements:
-----------------------------

>>> num
[10, 23, 43, 22, 25, 64, 39, 99]

>>> num.sort()

>>> num
[10, 22, 23, 25, 39, 43, 64, 99]

>>> num.sort(reverse= True)

>>> num
[99, 64, 43, 39, 25, 23, 22, 10]


Nested lists:
------------------

>>> a = [80,90]
>>> b = [30,40,50,a]
>>> b
[30, 40, 50, [80, 90]]
>>> b[3]
[80, 90]
>>> for i in b[3]:
...     print(i)
...
80
90


Nested list with Matrices:
------------------------------


>>> mat = [[1,2,3],[4,5,6],[7,8,9]]
>>> for i in mat:
...     print(i)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]


>>> for i in mat:
...     for j in i:
...             print(j, end=' ')
...     print()
...
1 2 3
4 5 6
7 8 9
>>>

List Comprehensions:
------------------------

List compreshensions represent creation of new lists from an iterable object(like a list,set,tuple,dictionar or range)
that satisfy a given condition.

List compreshensions contain very compact code usually a single statement that performs the task.

>>> squeares=[]
>>> for i in range(1,11):
...     squeares.append(i ** 2)
...
>>> squeares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

1.

>>> squear = [ i**2 for i in range(1,11)]
>>> print(squear)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


2. create a list for even numbers between 1 to 20

>>> even_numbers = [  i for i in range(1,20) if(i%2==0)]
>>> even_numbers
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>


3. If we have two lists 'x' and 'y' and we want to add each element of 'x' with each element of 'y'. you can write for loop as

>>> x = [10,20,30]
>>> y = [1,2,3,4]

>>> lst = []
>>> for i in x:
...     for j in y:
...             lst.append(i+j)
...
>>> lst
[11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34]
>>>
>>> lst1 = [ i+j for i in x for j in y]
>>> lst1
[11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34]
>>>


4. Take a list of strings, create a list with first letters of each string.

>>> fruits = [ 'apple','banana','cherry' ]
>>> first_letter= [ w[0] for w in fruits ]
>>> first_letter
['a', 'b', 'c']
>>>

5. Let's take two lists 'num1' and 'num2' with some numbers as
num1 = [1,2,3,4,5]
num2 = [10,11,1,2]
create another list num3  with numbers present in num1 but not in 'num2'


>>> for i in num1:
...     if i not in num2:
...             num3.append(i)
...
>>> num3
[3, 4, 5]

>>>
>>> num4 = [i for i in num1 if i not in num2]
>>> num4
[3, 4, 5]
>>>

Python :: 08 - String Operations

String operations



Usage of pip keyword
====================

pip is a package management system used to install and manage software packages written in Python.

pip is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs Python".
 Alternatively, pip stands for "preferred installer program".

C://users/lenovo/Desktop> pip install jupyter

To install package :
--------------------
pip install some-package-name

To uninstall package  :

pip uninstall some-package-name



String operations:
=====================

declaration statements

>>> s1 = 'welcome to python'
>>> print(s1)
welcome to python
>>> s2 = "welcome to python"
>>> print(s2)
welcome to python
>>> s3 = ''' welcomt to python
python is portable '''
>>> print(s3)
 welcomt to python
python is portable
>>> s4 = """ welcome to python
python is portable """
>>> print(s4)
 welcome to python
python is portable

length of string :
-------------
>>> len(s4)
38
>>> len(s1)
17



Indexing of string :
------------------

p y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1


Strling slicing :
=================

name = 'Quality Thought!'

print(name)          # Prints complete string
print (name[0])       # Prints first character of the string
print (name[2:5])     # Prints characters starting from 3rd to 5th
print (name[2:])      # Prints string starting from 3rd character
print (name * 2)      # Prints string two times
print (name + "INSTITUTE") # Prints concatenated string



Quality Thought!
Q
ali
ality Thought!
Quality Thought!Quality Thought!
Quality Thought!INSTITUTE


>>> name = "quality thought"
>>> name[::1]
'quality thought'
>>> name[::-1]
'thguoht ytilauq'


string reverse:
================

s = "python"


for i in s:
print(i,end='')

print("\n")

for i in range(len(s)-1,-1,-1):
print(s[i],end ='')

print("\n")

for i in range(-1,-len(s)-1,-1):
print(s[i],end='')
#p y t h o  n
#0 1 2 3 4 5
#-6         -5       -4      -3       -2       -1
#
#len(s) --> 6


>>> str1 = "welcome"
>>> str1[0:3]
'wel'
>>> str1[::-1]
'emoclew'


repeating string :
--------------------

>>> str1 = "python"
>>> str1 * 2
'pythonpython'


>>> str1 = "core python"

>>> str1[3 : 5]
'e '
>>> str1[5:7]
'py'
>>> str1[5:7] * 2

concatenation of strings:
-----------------------

>>> str1 = "python"
>>> str2 = "hadoop"
>>>

>>> s3 = str1 + str2
>>> print(s3)
pythonhadoop

checking membership:
----------------------

>>>str1 = "come"
>>> str2 = "welcome to python"
>>> if(str1 in str2):
print("membership")



comparing strings;
-------------------

s1 = "book"
s2 = "pen"
if(s1 == s2):
print("same")
else:
print("not same")


Remvoing spaces from string :
-------------------------====

lstrip() --> remove spaces left side
rstrip() --> remove spaces right side
strip() ---> remove spaces both sides

>>> if ('python' == '  python'):
print("same")
else:
print("not same")


not same
>>> if('python' == '  python'.lstrip()):
print("same")
else:
print("not same")


same



counting substring in a string :

-----------------

str1 = 'welcome to python . python is portable'

n = str1.count('python')

print(n)


str1 = 'python python'

n = str1.count('p',0,5)

print(n)




str1 = 'python is opensource. python is portable'

n = str1.count('python',0,len(str1))

print(n)



 Replacing a string with another string :

-----------------------------------------

 stringname.replace(old,new)


>>> str = 'this is a beautiful girl'

>>> str1 = 'girl'

>>> str2 = 'flower'

>>> print(str.replace(str1,str2))

this is a beautiful flower

>>>



splitting and joining strings:

----------------------------------


splitting :

=========



str = "one,two,three,four"
str_lst = str.split(',')

 print(str_lst)



for i in str_lst:

                print(i)

           

['one', 'two', 'three', 'four']

one

two

three

four



joining:

==========

separator.join(str)

here str is list.

str = "one,two,three,four"

str_lst = str.split(',')

print(str_lst)

for i in str_lst:

                print(i)

           

str2 = '|'.join(str_lst)

print(str2)



D:\Users\phani\Desktop>python python_exercise.py

['one', 'two', 'three', 'four']

one

two

three

four

one|two|three|four



str = ['apple','guava','grapes','mango']

sep = ':'

str1 = sep.join(str)

print(str1)



D:\Users\-phani\Desktop>python python_exercise.py

apple:guava:grapes:mango






Changing case of string:

-----------------------


str = 'Welcome to quality thought'



str = 'Welcome to quality thought'

print(str)

print(str.upper())

print(str.lower())

print(str.swapcase())

print(str.title())



D:\Users\phani\Desktop>python python_exercise.py

Welcome to quality thought

WELCOME TO QUALITY THOUGHT

welcome to quality thought

wELCOME TO QUALITY THOUGHT

Welcome To Quality Thought
============================================================

String testing methods:
----------------------

isalnum() -->  [a to z,A to Z,0-9]
isalpha() -->  [ a to z , A to Z]
isdigit() -->  [0-9]
islower() -->   [a to z]
istitle() ---> each of word of string starts with capital letter

>>> str = "QualityThought!"
>>> str.isalnum()
False
>>> str = "QualityThought123"
>>> str.isalnum()
True



>>> str = "QualityThought"
>>> str.isalpha()
True
>>> str1 = "QualityThougth123"
>>> str1.isalpha()
False



>>> str1 = "12345"
>>> str1.isdigit()
True
>>> str2 = "123abcd"
>>> str2.isdigit()
False



>>> str1 = "welcome to python"
>>> str1.istitle()
False
>>> str2 = "Welcome To Python"
>>> str2.istitle()
True


mobile number validation
--------------------------
num=input("enter mobile number\n".title())

if (len(str(num)) != 10):
print("invalid mobile number")
elif (str(num).isdigit()== False):
print(" in_valid mobile number")
else:
print(" valid mobile number")


Formatting the strings :
------------------------

Formatting a string means presenting string in clearly understandable manner

The format() method is used to format strings. This method is used as :

Syntax:

'format string with replacement fiedls'.format(values)

Here the replacement fields are denoted by {} that contain names and indexes.
These names or indexes represent the order of the values.

For example:

id = 101
name = 'srinivas'
sal = 19500.75

str = '{}{}{}'.format(id,name,sal)

>>> id = 101
>>> name = 'srinivas'
>>> sal = 19500.75

>>> str = '{}{}{}'.format(id,name,sal)

>>> print(str)
101srinivas19500.75

>>> str = '{},{},{}'.format(id,name,sal)
>>> print(str)
101,srinivas,19500.75

>>> str = '{}-{}-{}'.format(id,name,sal)
>>> print(str)
101-srinivas-19500.75

>>> str = 'ID={},NAME={},SAL={}'.format(id,name,sal)
>>> print(str)
ID=101,NAME=srinivas,SAL=19500.75

>>> str = 'ID={}\nNAME={}\nSAL={}'.format(id,name,sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=19500.75



>>> str = 'ID={0}\nNAME={1}\nSAL={2}'.format(id,name,sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=19500.75
>>> str = 'ID={1}\nNAME={0}\nSAL={2}'.format(id,name,sal)
>>> print(str)
ID=srinivas
NAME=101
SAL=19500.75
>>> str = 'ID={a}\nNAME={b}\nSAL={c}'.format(a=id,b=name,c=sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=19500.75


>>> str = 'ID={:d}\nNAME={:s}\nSAL={:f}'.format(id,name,sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=19500.750000
>>> str = 'ID={:d}\nNAME={:s}\nSAL={:.2f}'.format(id,name,sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=19500.75
>>> str = 'ID={:d}\nNAME={:s}\nSAL={:10.2f}'.format(id,name,sal)
>>> print(str)
ID=101
NAME=srinivas
SAL=  19500.75

consolidated list of format operations.



print('{}{}{}'.format(id,name,sal))
print('ID={}\nNAME={}\nSAL={}'.format(id,name,sal))
print('{}-{}-{}'.format(id,name,sal))
print('{}\n{}\n{}'.format(id,name,sal))
print('ID={}\nNAME={}\nSAL={}'.format(id,name,sal))
print('ID={0}\n NAME={1}\n SAL={2}'.format(id,name,sal))
print('ID={1}\n NAME={0}\n SAL={2}'.format(id,name,sal))
print('ID={a}\n NAME={b}\n SAL={c}'.format(a=id,b=name,c=sal))
print('ID={b}\n NAME={a}\n SAL={c}'.format(a=id,b=name,c=sal))
print('ID={:d}\n NAME={:s}\n SAL={:f}'.format(id,name,sal))
print('ID={:d}\n NAME={:s}\n SAL={:.2f}'.format(id,name,sal))
print('ID={:d}\n NAME={:s}\n SAL={:10.2f}'.format(id,name,sal))