python classes



What is Programming Language?
--------------------------
1.A programming language is a set of rules that
provides a way of telling a computer what
operations to perform.

2.A programming language is a set of rules for
communicating an algorithm

3.It provides a linguistic framework for
describing computations
provides a way of telling a computer what
operations to perform.

Types of computer languages:
--------------------------
Machine Language :

     1.The fundamental language of the computer’s processor, also called Low Level Language.
     2.All programs are converted into machine language before they can be executed.
     3.Consists of combination of 0’s and 1’s that represent high and low electrical voltage.

Assembly Language :
     1.A low level language that is similar to machine language.
 2.Uses symbolic operation code to represent the machine operation code.
      Eg :
LOAD r1,b
LOAD r2,h
MUL r1,r2
DIV r1,#2
RET

High level Language :

1.Computer (programming) languages that are easier to learn.
2.Uses English like statements.
3.Examples are Python,C ++, Visual Basic, Pascal, Fortran and …....

What is Python?
-----------------
1. Python is an easy to learn, powerful programming language. The application development process much faster and easier
2. The programming language Python was conceived in the late 1980s, and its implementation was started in December 1989 by
    Guido van Rossum at  Netherlands as a successor to the ABC (programming language)
3. Python First release happened in 1991.
4. Python was named for the BBC TV show Monty Python's Flying Circus.


Why python?
-----------
1. Easy to understand
2. Beginners language
3. Portable
4. Less lines of code
5. Simple to implement
6. Huge libraries supports


8. Large standard library(numpy,scipy)
9. GUI programming (Tkinter)

Python Implemenation alternatives:
-------------------------------
1. CPython(stadnard implemenation of python)
2. Jython(Python for java)
3. IronPython( Python for .net)
4. Stackless (Python for concurrency)
5. PyPy ( Python for speed)

Python Packages :
---------------
1. Web devlopment - Django,Flask frameworks,Pylons,Web2py framworks.
2. Artificiat Intelligence : Scikit-learn,Keras,TensorFlow,OpenCV
3. GUI - TKinter
4. Desktop Applications : Jython, WxPython
5. Game Development : pygame
6. Testing : Spliter Tool,pytest framework
7. Bigdata : Pydoop,DASK,PySpark Libraries
8. DataScience : NumPy,Pandas,matplotlib,seaborn libraries
9. AWS : boto
10. Robotic process : pyro
11. Web Scraping : Beautifulsoup4,urllib2,mechanize
12. Devops & System Admin : Os,Sys,Shutil,Glob,Subprocess,PathLib,fabric
13. Networking : Twisted,socket,client and server

Who uses Python :
------------------

Data engineers, data scientists, System administrators and
developers. Python is not industry specific, but task specific—great
for data processing, business intelligence, and some application
development

Google, You Tube,
Instagram, DropBox,
Survey Monkey, Quora,
Pinterest, Reddit
Yahoo Maps,…..
Duration
------------------------------------------------------------------------------------

Day 2 - print(),variables




Python print()
-----------------------

Print Statement :
---------------


eg:
>>print('Welcome to python')
>>print('Python is OpenSource')

>>print("welcome to python")
>>print("Python is OpenSource")

above two are valid

Below are invalid.
>> print("welcome to python")
>>print("Python is OpenSource")

Error due to indentation
** Statement should start in first column

** Printing double quotes with in string

>>> print("Welcome to \"QualityThought\" ")
Welcome to "QualityThought"
>>> print("Welcome to \'QualityThought\' ")
Welcome to 'QualityThought'


** Printing multiple times

>>>print("QualityThought"*5)
QualityThoughtQualityThoughtQualityThoughtQualityThoughtQualityThought


>>>print("QualityThought\n"*5)
QualityThought
QualityThought
QualityThought
QualityThought
QualityThought



Python Variable:
----------------
variable :
Think of a number. Any number. Now, before you forget that number, let’s store it for later.
When you think of a number, you are holding that value in your head.
 If you want to remember it  you will write it down on a piece of paper.
And if it’s really important, you will put it in a safe place.
In computer science, that safe place is a variable. They’re called variables because, well, they’re “capable of being varied or changed”

--A variable is a memory location where a programmer can store a value. Example : roll_no, amount, name etc.
--Value is either string, numeric etc. Example : "Sara", 120, 25.36
--Variables are created when first assigned.
--The value stored in a variable can be accessed or updated later.
--No declaration required
--The type (string, int, float etc.) of the variable is determined by Python
--The interpreter allocates memory on the basis of the data type of a variable.



Rules for python variables :
=========================

--Must begin with a letter (a - z, A - B) or underscore (_)

>>> @account_number = 34525
SyntaxError: invalid syntax

>>> _account_number=34525
>>> print(_account_number)
34525

--Other characters can be letters, numbers or _
-- Must not contain any special characters !, @, #, $, %
>>> a@ = 20
SyntaxError: inva--lid syntax
>>> a$ = 49
SyntaxError: invalid syntax


--Case Sensitive

>>> product_name = 'TV'
>>> print(product_name)
TV
>>> print(Product_name)

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    print(Product_name)
NameError: name 'Product_name' is not defined
>>> print(PRODUCT_NAME)

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    print(PRODUCT_NAME)
NameError: name 'PRODUCT_NAME' is not defined



--There are some reserved words which you cannot use as a variable name because Python uses them for other things.
>>> for = 10
SyntaxError: invalid syntax

Good Variable Name :
========================
**Choose meaningful name instead of short name. roll_no is better than rno.
**Maintain the length of a variable name. Roll_no_of_a-student is too long?
**Be consistent; roll_no or RollNo
**Begin a variable name with an underscore(_) character for a special case.


Multi assignment

a=10
print(a)

Name='RAVI'
Age=21


a = b = c = 1
print(a)
print(b)
print(c)



a,b,c = 10,20,"QualityThought"
print(a)
print(b)
print(c)

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

id(),input(),comments



How to print variables
--------------------
>>> name ="Ravi"
>>> age = 34
>>> print("name is",name,"age is",age)
name is Ravi age is 34

id() function
--------------

Every instance (object or variable) has an identity, i.e. an integer which is unique within the script or program,
i.e. other objects have different identities

>>> x = 30
>>> id(x)
19489708
>>> y = 40
>>> id(y)
19489588
>>> z = y
>>> id(z)
19489588


>>> x = 40
>>> id(x)
19489588
>>> k = 40
>>> id(k)
19489588

Here id is created for value not for variable.



COMMENTS:
-=======

Python Comments:
===============
1. Single line comment ----> #
2. Multi line comments -----> ''' or """

Input()
------
>>> a = input()
12
>>> print(a)
12

>>> age = input("Enter your age \n")
Enter your age
28
>>> print(age)
28

comments_ex.py
=============

'''
Script name : comments_ex.py
Author : Phani
Date : 08/08/2018
Description : Example program for comments
'''

#Enter input value from keyboard
name = input("Enter your name\n")

age = input("Enter your age\n")

print("name is",name,"age",age)


Assignment:
----------

Student details

Enter student id
101
Enter student name
Raji
Enter sub1 marks
23
enter sub2 marks
78
enter sub3 marks
90

Student id is 10
Student name is Raji
Subject1 marks 23
subject2 marks 78
subject3 marks 90

Please provide .py script to qtpython01@gmail.com

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

Datatypes



Python Datatypes :
================
A datatype represents the type of data stored into a variable or memory.

Buitin datatypes -- Already available in python
User defined datatypes -- Datatypes created by programmers

1. Built in datatypes :

* None Type
* Numaric Types --> int,float,complex
* Sequences     --> str,bytes,bytearray,list,tuple,range
* Sets          --> set,frozenset
* Mappings      --> dict


Determine datatype :
----------------
type(variable name)


None :
-----
 'None' datatype represents an object that does not contain any value.
  In java - NULL
  In Python - None

>> print(type(None))
>>

>>> def calc():
...     a=10
...     b=20
...     c=a+b
...

    >>> calc()
    >>> res = calc()
    >>> type(res)
    <class 'NoneType'>


>>> if(res==None):
...     print("does not return any values")
...
does not return any values

Numaric dataypes :
--------------------
1. int
2. float
3. complex

int :
* Int represents an integer number.
* It is number with out decimal part and fraction part
* There is no limit for size of int datatype. It can store any integer number conveniently.

Eg :
>>> a = 20
>>> type(a)
<class 'int'>
>>> a = -234
>>> print(a)
-234
>>> a = 22222222222222222222222222222222222222222222222222222222
>>> print(a)
22222222222222222222222222222222222222222222222222222222
>>> type(a)
<class 'int'>

Float :
* Float represents floating number
* A floating number contains decimal part

Eg:
>>> a = 223.345
>>> type(a)
<class 'float'>
>>> a = 22e5
>>> print(a)
2200000.0


Converting the datatype explicitly :
--------------------------------
>>> x = 23
>>> type(x)
<class 'int'>
>>> b = float(x)
>>> print(b)
23.0
>>> c = 23.345
>>> d = int(c)
>>> print(d)
23

Complex Datatype :

* complex number is number that is written in the form of a+bj or a+bJ
a : real part
b : imaginary part

Eg :

>>> a = 1+2j
>>> b = 2+3j
>>> c = a+b
>>> print(c)
(3+5j)

>>> c = 1+2j
>>> d = 1-2j
>>> res = c * d
>>> print(res)
(5+0j)




  Sequences in Python :
 --------------------

 A sequence represents a group of elements or items.

 eg : group of integer numbers will form seqence

 There are six types of sequences in python :

 1. str
 2. bytes
 3. bytearray
 4. list
 5. tuple
 6. range

str datatype :

* str represents string datatype.
* string represents group of characters
* string enclosed in single quotes or double quotes('',"")
* string can also be represent in """ or '''(if assign to variable then string otherwise it would be comment only)


eg :

>>> print(word)
welcome
>>> word = "welcome"
>>> print(word)
welcome
>>> word = '''welcome'''
>>> print(word)
welcome
>>> word = """welcome"""
>>> print(word)
welcome

for = 'Quality Thought!'
SyntaxError: invalid syntax (for is key word, variable name should not be key word)

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

Note : explain about file processing , file name contain date

>>> name[0:4]
'Qual'
>>> name[0:6:2]
'Qai'
>>> print(name[0:4])
Qual
>>> print(name[0:6:2])
Qai


There is no char datatype like C in python.

>>> ch = 'A'
>>> type(ch)
<class 'str'>

>>> ch = 'A'
>>> type(ch)
<class 'str'>
>>> name = "ravi"
>>> name[0]
's'

practice
--------

>>> a = None
>>> type(a)
<class 'NoneType'>
>>> a = 200
>>> type(a)
<class 'int'>
>>> a = 10
>>> type(a)
<class 'int'>
>>>
>>>
>>> avg = 20.34
>>> type(avg)
<class 'float'>
>>>
>>> a = 10 + 2j
>>> type(a)
<class 'complex'>
>>> a = 10+2j
>>> b = 12+4j
>>> a
(10+2j)
>>> b
(12+4j)
>>> c = a+b
>>> c
(22+6j)
>>>
>>>
>>> name = "ravi"
>>> type(name)
<class 'str'>
>>>
>>> product_name = 'mobile'
>>> product_name
'mobile'
>>> category = ''' baby product
mobile '''
>>> category
' baby product\nmobile '
>>>
>>>
>>>
>>>
>>> str1  = "WELCOME"
>>> str1[2]
'L'
>>> str1[4]
'O'
>>> str1[3]
'C'
>>> str1
'WELCOME'
>>> str1[2]
'L'
>>> str1[-5]
'L'
>>> str1[-3]
'O'
>>> str1[-1]
'E'
>>> str1
'WELCOME'
>>> str1[2:5]
'LCO'
>>> str1[3:7]
'COME'
>>> str1[2:]
'LCOME'
>>> str1[:4]
'WELC'
>>>
>>> str1
'WELCOME'
>>> str1[0:7]
'WELCOME'
>>> str1[0:7:2]
'WLOE'
>>> str1[1:6:2]
'ECM'
>>> str1[1:6:3]
'EO'
>>> str1
'WELCOME'
>>> str1[-3]
'O'
>>> str1[-5:-2]
'LCO'
>>>
>>>
>>> str1[-5:]
'LCOME'
>>> str1[:-2]
'WELCO'
>>>
>>>
>>> str1[:]
'WELCOME'
>>> str1[::2]
'WLOE'
>>> str1[::-1]
'EMOCLEW'
>>>
>>>
>>> a = [10,20,30,40]
>>> type(a)
<class 'list'>
>>> details = [101,'phani','Hyderabad']
>>>
>>>
>>> details[1]
'phani'
>>> details[2]
'Hyderabad'
>>>
>>> a = [10,20,30,40,50,60]
>>> a[3]
40
>>> a[-1]
60
>>> a[2:5]
[30, 40, 50]
>>> a[1:4]
[20, 30, 40]
>>>
>>> a[2:]
[30, 40, 50, 60]
>>> a[ :3]
[10, 20, 30]
>>> a[1:5:2]
[20, 40]
>>> 

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

Complete Datatypes Material


Python Datatypes :
================
A datatype represents the type of data stored into a variable or memory.

Buitin datatypes -- Already available in python
User defined datatypes -- Datatypes created by programmers

1. Built in datatypes :

* None Type
* Numaric Types --> int,float,complex
* Sequences     --> str,bytes,bytearray,list,tuple,range
* Sets          --> set,frozenset
* Mappings      --> dict


Determine datatype :
----------------
type(variable name)


None :
-----
 'None' datatype represents an object that does not contain any value.
  In java - NULL
  In Python - None

>> print(type(None))
>>

>>> def calc():
...     a=10
...     b=20
...     c=a+b
...

    >>> calc()
    >>> res = calc()
    >>> type(res)
    <class 'NoneType'>


>>> if(res==None):
...     print("does not return any values")
...
does not return any values

Numaric dataypes :
--------------------
1. int
2. float
3. complex

int :
* Int represents an integer number.
* It is number with out decimal part and fraction part
* There is no limit for size of int datatype. It can store any integer number conveniently.

Eg :
>>> a = 20
>>> type(a)
<class 'int'>
>>> a = -234
>>> print(a)
-234
>>> a = 22222222222222222222222222222222222222222222222222222222
>>> print(a)
22222222222222222222222222222222222222222222222222222222
>>> type(a)
<class 'int'>

Float :
* Float represents floating number
* A floating number contains decimal part

Eg:
>>> a = 223.345
>>> type(a)
<class 'float'>
>>> a = 22e5
>>> print(a)
2200000.0


Converting the datatype explicitly :
--------------------------------
>>> x = 23
>>> type(x)
<class 'int'>
>>> b = float(x)
>>> print(b)
23.0
>>> c = 23.345
>>> d = int(c)
>>> print(d)
23

Complex Datatype :

* complex number is number that is written in the form of a+bj or a+bJ
a : real part
b : imaginary part

Eg :

>>> a = 1+2j
>>> b = 2+3j
>>> c = a+b
>>> print(c)
(3+5j)

>>> c = 1+2j
>>> d = 1-2j
>>> res = c * d
>>> print(res)
(5+0j)






bool datatype :

The bool datatype in python represents boolean values.


>>> a = 20
     >>> b = 10
     >>> print(a>b)
     True
     >>> print(a<b)
     False
     >>> c=print(a>b)
     True
     >>> print(c)
     None
     >>> c=a>b
     >>> print(c)
     True
 
 
     >>> True + True
     2
     >>> True - False
     1
 
     >>> file1 = True
     >>> file2 = True
     >>> file3 = True
     >>> print(file1+file2+file3)
     3


 Sequences in Python :
 --------------------

 A sequence represents a group of elements or items.

 eg : group of integer numbers will form seqence

 There are six types of sequences in python :

 1. str
 2. bytes
 3. bytearray
 4. list
 5. tuple
 6. range

str datatype :

* str represents string datatype.
* string represents group of characters
* string enclosed in single quotes or double quotes('',"")
* string can also be represent in """ or '''(if assign to variable then string otherwise it would be comment only)


eg :

>>> print(word)
welcome
>>> word = "welcome"
>>> print(word)
welcome
>>> word = '''welcome'''
>>> print(word)
welcome
>>> word = """welcome"""
>>> print(word)
welcome

for = 'Quality Thought!'
SyntaxError: invalid syntax (for is key word, variable name should not be key word)

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

Note : explain about file processing , file name contain date

>>> name[0:4]
'Qual'
>>> name[0:6:2]
'Qai'
>>> print(name[0:4])
Qual
>>> print(name[0:6:2])
Qai


There is no char datatype like C in python.

>>> ch = 'A'
>>> type(ch)
<class 'str'>

>>> ch = 'A'
>>> type(ch)
<class 'str'>
>>> name = "ravi"
>>> name[0]
's'



bytes datatype :

The bytes datatype represents a group of byte numbers
just like an array does.
* should be 0 to 255
* Does not support negative numbers

>>> a = [12,23,45]
>>> x = bytes(a)
>>> type(x)
<class 'bytes'>
>>> x[0]=55
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
x[0]=55
TypeError: 'bytes' object does not support item assignment
>>> a = [12,23,45,345]
>>> x = bytes(a) x
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)
>>> a = [12,23,45,-23]
>>> x = bytes(a)
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)

bytearray datatype :

* The bytearray datatype is similar to bytes data type. The difference is that
the bytes type array can not be modified but bytearray can be modified

>>> a = [12,23,34,54]
>>> x = bytearray(a)
>>> print(x[0])
12
>>> x[0] = 55
>>> for i in x:
print(i)
55
23
34
54

List datatype :


List  : Store different data type elements, can grow dynamically.

* List represent in [] and elements separated by ,

>>> a= [101,"ravi",'NRT']
>>> b =[102,"raju","HYD"]
>>> a[0]
101
>>> a[0:2]
[101, 'ravi']
>>> b[:3]
[102, 'raju', 'HYD']

>>> print(a)
[101, 'ravi', 'NRT']
>>> type(a)
<class 'list'>

>>> print(a)
[101, 'ravi', 'NRT']
>>> a[0]
101
>>> a[0] = 111
>>> print(a)
[111, 'ravi', 'NRT']           

list elements can be modified



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']







tuple datatype :

* Tuple is similar to list.
* Can contain different datatypes of elements
* Represents ()
* Differene between list and tuple is
can not modify the tuple so tuple is read only list.

>>> account_details = (101,"ravi","NRT")
>>> type(account_details)
<class 'tuple'>
>>> account_details[0]
101
>>> account_details[1]
'ravi'
>>> account_details[1] = "raju"
Traceback (most recent call last):
File "<pyshell#171>", line 1, in <module>
account_details[1] = "raju"
TypeError: 'tuple' object does not support item assignment


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print(tuple)           # Prints complete list
print(tuple[0])        # Prints first element of the list
print(tuple[1:3])      # Prints elements starting from 2nd till 3rd
print(tuple[2:])       # Prints elements starting from 3rd element
print(tinytuple * 2)   # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

range data type :
-----------------
* range data type represents sequence of numbers.
* The numbers in range are not modifiable
* Generally range is used for repeating a for loop for specific number of times.

>>> a = range(10)
>>> print(a)
range(0, 10)
>>> type(a)
<class 'range'>
>>> for i in a:
print(i)


0
1
2
3
4
5
6
7
8
9



>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28


>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28

 Sets :

A set is an unordered collection of elements much like a set in mathematics.

* Order of elements is not maintained. It means elements may not appear in the same order as they entered in to set.
* Set does not accept duplicate elements
* Two types of sets
1. set datatype
2. frozenset datatype

set datatype :
* set elements should separated with ,
* set always print only unique elements.


>>> s = {10,20,30,40,50}
>>> print(s)
{40, 10, 50, 20, 30}
>>> type(s)
<class 'set'>
>>> s = {10,10,20,20,30,30}
>>> print(s)
{10, 20, 30}

>>> str1 = set("srinivas")
>>> print(str1)
{'r', 'v', 'n', 'a', 's', 'i'}

>>> str2 = list(str1)
>>> print(str2)
['r', 'v', 'n', 'a', 's', 'i']
>>> print(str2[0])
r
>>> print(str2[1])
v

>>> s = {10,20,30,40}
>>> s.update([50])        // adding element to set
>>> print(s)
{40, 10, 50, 20, 30}
>>>
>>> print(s)
{40, 10, 50, 20, 30}
>>> s.remove(50)            // remove element from set
>>> print(s)
{40, 10, 20, 30}

fronzenset datatype:

* Create frozenset by passing set data
* Can not be modified (update and remove methods will not work)


>>> s = {50,60,70,80,90}
>>> fs = frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> print(fs)
frozenset({80, 50, 70, 90, 60})
>>> s = {50,50,60,60,70}
>>> fs1 = frozenset(s)
>>> type(fs1)
<class 'frozenset'>
>>> print(fs1)
frozenset({50, 60, 70})


Mapping Type :
-------------
* map represents a group of elements in the form of key values pairs so that when key is given
  will retrive a value.

 * The 'dict' datatype is an example of map
 * dict represents dictionary that contains of pair of elements first one is Key and second one is Value
 * key and value separated by ':'


>>> d = {101:"Ram",102:"Ravi",103:"Rani"}
>>> print(d)
{101: 'Ram', 102: 'Ravi', 103: 'Rani'}
>>> d[101]
'Ram'
>>> d[102]
'Ravi'
>>> type(d)
<class 'dict'>


dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict['one'])       # Prints value for 'one' key
print(dict[2])           # Prints value for 2 key
print(tinydict)          # Prints complete dictionary
print(tinydict.keys())   # Prints all the keys
print(tinydict.values()) # Prints all the values

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

OPERATORS IN PYTHON :
==========================

* The operator is symbol that perform some operation.
* a+b  => a,b are operands and + is operator

1. Arithmetic operators --->+,-,*,/,//,%
2. Assignment operators --> =, +=,-=,*=,/=,//=
3. Unary minus operators --> -
4. Relational operators -----> <,<=,>,>=,==
5. Logical operators ----> and or not
6. Boolean operators --> True, False
7. Bitwise operators
8. Membership operators ---> in , not in
9. Identity operators --> is,is not

Arithmetic operators  : +,-,*,/,//,%
--------------------
x = 15
y = 4


print('x + y =',x+y)
# Output: x + y = 19



print('x - y =',x-y)
# Output: x - y = 11

print('x * y =',x*y)
# Output: x * y = 60


print('x / y =',x/y)
# Output: x / y = 3.75


print('x // y =',x//y)
# Output: x // y = 3
--divide the result to whole number


print('x ** y =',x**y)
# Output: x ** y = 50625

>>> print("x % y is ",x%y)
   
x % y is  3

assignment operators
--------------------

Assignment operators in Python
Operator Example Equivatent to
=           x = 5   x = 5
*= x *= 5   x = x * 5
+=          x += 5    x = x+5
/=         x /= 5   x = x / 5
%=         x %= 5   x = x % 5
//=         x //= 5   x = x // 5
**=         x **= 5   x = x ** 5
^=         x ^= 5   x = x ^ 5


Unary minus Operator :
----------------------

Unary operator is denoted by (-) symbol. when this operator
used before symbol the value will be negated

>>> n = 10
>>> print(-n)
-10

Comparison (Relational) Operators
---------------------------------
< ,<=, > , >= , ==

True
False

x = 10
y = 12


print('x > y  is',x>y)
# Output: x > y is False


print('x < y  is',x<y)
# Output: x < y is True

print('x == y is',x==y)
# Output: x == y is False

print('x != y is',x!=y)
# Output: x != y is True

print('x >= y is',x>=y)
# Output: x >= y is False

print('x <= y is',x<=y)
# Output: x <= y is True


Logical operators
-----------------------



>>> a = 10
>>> b = 20
>>>
>>> c = a > b --> False
>>> d = a < b ---> True
>>> c
False
>>> d
True
>>>
>>> c and d
False
>>>
>>> c or d
True
>>>
>>> not c
True
>>>
>>> not a
False

Boolean Operators :
---------------------

We know there are two bool type literals. They are TRUE and FALSE.
Boolean operators act upon 'bool' type literals and they provide 'bool' type output.

It mean the result provided by boolean operators will be again either True or False.

There are 3 boolean operators as mentioned below

Let's take x= True
           y= False

>>> x = True
>>> y = False
>>> x and y
False
>>> x or y
True
>>> not x
False
>>> not y

True


TRUTH TABLE:
--------------

X Y X AND Y X OR Y x  xor y
T T T T F
T F F T T
F T F T T
F F F F F



Membership operators---> in ,not in
-----------------------

Operator     Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

x = 'Hello world'
y = {1:'a',2:'b'}


print('H' in x)
# Output: True

print('hello' not in x)
# Output: True

print(1 in y)
# Output: True

print('a' in y)
# Output: False



>>> a = [101,"srinivas","Hyd"]
>>> b = 101
>>> if(b in a):
print("true")
else :
print("false")


true
--------------

>>> a = {101:"srinivas",102:"Ravi",103:"Vijay"}
>>> rno = int(input("enter roll number\n"))
enter roll number
101
>>> print(rno)
101
>>> if( rno in a):
print(a[rno])

'srinivas'



Identity operators :
--------------------

These operators compare the memory location of two objects. Hence it is possible to know whether
the two objects are equal or not.

Object memory location can be identified by using id() function.

a =25
b =25

They are two identity operators

1. is
2. is not

*'is' operator :
it will compare the identity number of two objects. if both are same it will return true otherwise false.

* 'is not' operator :

>>> a = 20
>>> b = 21
>>> a is b
False

Difference between is and ==

>>> a = [1,2,3,4]
>>> b = [1,2,3,4]
>>> a == b                    // value is same
True
>>> a is b                    // value same but identity location is different.
False

>>> id(a)
52538696
>>> id(b)
52538504


# Python program to illustrate the use
# of 'is' identity operator
x = 5
if (type(x) is int):
    print ("true")
else:
    print ("false")

# Python program to illustrate the
# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
    print ("true")
else:
    print ("false")



Operator Precedence :
--------------------

()     --> paranthesis
**     --> Exponential
-,~    --> unary mins, Bitwise complement
*,/,//,%     --> Multiplication,division,floor division,Modules
+,- --> Addition,subtraction
<<,>> --> Bitwise left shift, Bitwise right shift
& --> Bitwise AND
^ --> Bitwise XOR
| --> Bitwise OR
>,>=,<,<=,==,!=     --> Assignment operators
is, is not --> Identity operators
in, not in --> Membership operators
not --> logical not
or  --> logical or
and --> logical and


precedence represents the priority level of the operator.
The operator which are high precedence will execute first than of lower precedence.

>>> a=1
>>> b=2
>>> c=3
>>> d=4
>>> e=5
>>> (a*b)+c*d
14
>>> a*(b+c)*d
20
>>> a*b+c*d
14
>>>

Bitwise operators
---------------------

Binary Number : starts with 0b

>>> a = 0b1101
>>> print(bin(a))
0b1101
>>> print(a)
13


>>> b = 18
>>> print(bin(18))
0b10010
>>> b = 0b10110
>>> print(b)
22

 Octal Number : start with 0O

>>> a = 0O101
>>> print(a)
65

>>> b = 96
>>> print(oct(b))
0o140

Hexa Decimal : starts with 0X


>>> b = 26
>>> print(hex(b))
0x1a
>>> b = 27
>>> print(hex(b))
0x1b
>>> b = 28
>>> print(hex(b))
0x1c
>>> b = 29
>>> print(hex(b))
0x1d
>>> b = 30
>>> print(hex(b))
0x1e
>>> b = 31
>>> print(hex(b))
0x1f
>>> b = 32
>>> print(hex(b))
0x20

i)Bitwise complement operatory(~)

>>> a = 4
>>> ~a
-5
>>> bin(a)
'0b100'

a=4 ---> 0100
~a --->  1011  ---> 11

But here compliler display -5  ( in 2's complement)

~N = -(N+1)

~4 =

N = 4 =  0100
+1    =     1
        --------
(N+1) 0101     = 5

~N = -(N+1)
~4 = -5




ii) Bitwise AND operator(&)

>>> a = 4
>>> b = 5
>>> a & b
4

a =   0100
b =   0101
a&b = 0100 = 4
      (both 1 then only 1 otherwise 0)

iii) Bitwise OR operator(|)

>>> a = 4
>>> b = 5
>>> a | b
5

a =  0100
b =  0101
a|b = 0101 = 5

(both 0 then 0 remaining 1)


iv) Bitwise XOR Operator(^)

>>> a = 4
>>> b = 5
>>> a ^ b
1

a   = 0100
b   = 0101
a^b = 0001

(any one should be 1 then 1 otherwise 0)



v) Bitwise Left shift operator(<<)

>>> a = 4
>>> a << 2
16
>>> a << 3
32

a = 4 = 0000 0100
a << 2= 0001 0000  = 16
a << 3= 0010 0000  = 32

vi) Bitwise Right shift operator(>>)


>>> a = 24
>>> a >> 2
6

a     = 0001 1000
a >>2 = 0000 0110  = 6 


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


Command line arguments and conditional statements



Command Line Arguments:
-----------------------
While running program arguments which are passing through commnd line
are called as command line arguments .

Here arguments are separated by space.

>> python add.py 10 20

* These argumens are stored by default in the form of strings in a list with name argv.
  this is available in sys module.

argv[0] --> add.py
10   --> 10
20 --> 20

cmnd_line.py
===============

import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

print(type(a))
print(type(b))

add = a + b
print(add)

NOTE : default it will take string so we have convert to integer

execution :

C:\Users\welcome\Desktop>python cmnd_line.py 10 20


Flow control:
--------------

1.conditional statements
2. Transfer statements
3. Iterative statements



conditional statments(if..elif..else)
============================

 If any statment expecting its sub statements then it should be ended with :

conditional execution :

if x > 0 :
print('x is positive')

Alternative execution :

if x%2 == 0 :
print('x is even')
else :
print('x is odd')

Chained conditionals :

if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'


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

Assignment



1. Write a program to read 2 numbers from keyboards and print sum

2. Write a program to read employee data from keyboard and Print.
Note : employee data contains eno,ename,esal,eaddress

3. Write a program to find biggest of give 2 numbers from the command prompt?

4. Write a program to find biggest of given 3 numbers from the command prompt?

5. Write a program to find smallest of given 2 numbers?

6. Write a program to check whether the given number is even or odd?

7. Write a program to check whether the give number is in between 1 and 50?

8. Write a program to take a single digit number from the keyboard and print its value in word?

9. Write a program to check whether a number is negative, positive or zero.

10. Write a program to check whether a number is divisible by 5 and 11 or not.

11. Write a program to check whether a number is even or odd.

12. Write a program to input week number and print week day.

13. Write a program to input basic salary of an employee and calculate its Gross salary according to following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%

14. Write a program to calculate and print the Electricity bill of a given customer. The customer id., name and unit consumed by the user should be taken from the keyboard and display the total amount to pay to the customer.

The charge are as follow :
Unit Charge/unit
upto 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00

If bill exceeds Rs. 400 then a surcharge of 15% will be charged and the minimum bill should be of Rs. 100/-.

Test Data :
Enter Customer ID : 1001
Enter Customer Name : Reddy
Enter Number of Units Consumed : 800

Expected Output :
Customer ID :1001
Customer Name :Reddy
unit Consumed :800
Amount Charges @Rs. 2.00 per unit : 1600.00
Surchage Amount : 240.00
Net Amount Paid By the Customer : 1840.00


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

user_authentication.py


'''
scriptname : user_authentication.py
Author : phani
Date : 16/08/2018
Description : User authentication
Version : 1.0

'''
#python user_authentication.py HDFC

import sys


if (len(sys.argv) < 2) :
print("invalid number of arguments")
sys.exit(1)


bank_name = sys.argv[1]

print("welcome to ",bank_name)



usr_details = {'HDFC001':'HDFC_PWD_001','HDFC002':'HDFC_PWD_002'}

usr_nm = input("Enter user name \n")
pwd = input("Enter password \n")

#usr_details.keys()---> ['HDFC001','HDFC002']

if (usr_nm in usr_details.keys()):
if(pwd == usr_details[usr_nm]):
print("login succssfull")
else:
print("in valid password")
sys.exit(1)

else:
print("invalid user")
sys.exit(1)

print("Welcome Mr.",usr_nm)



usr_acnt_dtls = {'HDFC001':'3234565','HDFC002':'5674839'}
acc_blnce_dtls = {'3234565':20000,'5674839':30000}

option = int(input("Enter your choice \n 1.Balance Enquiry \n 2. WithDraw \n 3. Deposit\n"))

if option==1:
acc_nmbr = usr_acnt_dtls[usr_nm]
#'3234565'
balance = acc_blnce_dtls[acc_nmbr]
print("current balance is",balance)

elif option==2:
print("you have choosen withdraw\n")

elif option==3:
print("you have choosen deposit\n")
else:
print("invalid choice")

print("Thanks for visiting",bank_name)


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

loops




What is loop?

A loop is a sequence instructions that is continually repeated
until a certain condition reached.


Types of loops in Python :
------------------------
1. for loop
2. while loop
3. Nested loop

Loop control statements :
1. break
2. Continue

for loop :
=========


for(i=0;i<n;i++) ===> ( which is not implemented in python)



>>> for i in range(5):
print(i)


0
1
2
3
4




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

>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> for i in range(1,n,2):
print(i)



1
3

>>> for i in "PYTHON":
print(i)


P
Y
T
H
O
N

for_example.py
-------------
1. To do operation on each and every element of list.
a = [1,2,3,4]
s = 0
for i in a:
s = s+i
print(s)



2. return to list

a = [1,2,3,4]

for i in a:
print(i ** 2)

b = [  (i**2) for i in a]
print(b)



for with if :
-------------

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number ")
else:
print(data," is odd number")


output:
--------
12  is even number
3  is odd number
42  is even number
34  is even number
4  is even number
2  is even number
2  is even number


usage of end  in print statement :

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number",end = ":\n")
else:
print(data," is odd number",end = ":\n")


12  is even number:
3  is odd number:
42  is even number:
34  is even number:
4  is even number:
2  is even number:
2  is even number:


student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(" %d is even number " %data)
else:
print(" %d is odd number " %data)

%d,%i --> integer
%s  --> string
%f ---> float


>>> name = "ravi"
>>> age = 24

>>> print(" stuedent name %s and age is %d" %(name,age))
 stuedent name ravi and age is 24



dataset =  ['python','java','perl']

for i in dataset:
print(i.upper())

PYTHON
JAVA
PERL

for i in dataset:
print(i[0].upper()+i[1:])

Python
Java
Perl



for loop with else clause :
-------------------------

numbers = [10,20,30,40,50]

for i in numbers:
print(i)
else:
print("Loop completed successfuly")



Looping control statement :
-------------------------
A statement that alters the execution of loop from its designated sequence is called loop control statement

1. Break:

To break out the loop we can use break function.

syntax :

for varaiable_name in sequence :
statement1
statement2
if(condition):
break

>>> lst = [10,20,30,40]
>>> for i in lst:
if(i == 30):
break
print(i)


10
20

Note: if we stop loop using break statement then else part will not execute.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
break

print(i)
else :
print("loop completed")

10
20

1. program to write list contains at least one even number

lst = [1,2,3,5,7,9]

for i in lst:
if(i%2 == 0):
print("event number present")
break
else:
print("list does not contain even number")


Continue statement :
----------------

Continue statement is used to tell python to jump to the next iteration of loop.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
continue

print(i)
else :
print("loop completed")


10
20
40
loop completed


while loop:
===========

while loop is used to execute no.of statements till the condition passed in while loop.
once condition is false, the control will come out the loop.

syntax :

while<expression>:
statement1
statement2


>>> while(i < n):
print(i)
i += 1


0
1
2
3
4
5
6
7
8
9

>>> while(i < n):
print(i)

infinite loop

while else loop:
-----------------

i=0
while (i<10):
print(i)
i += 1
else:
print("loop completed")


Pythone Nested Loops:
=====================

Nested loop --> loop inside another loop

mulitiplication table :

for i in range(1,5):
for j in range(1,10):
print('%d * %d = %d' %(i,j,i*j))

print("\n")

for..else condition example:
===========================


lst = [1,3,5,7]

for i in lst:
if(i%2==0):
print("even number found")
break

else:
print("did not find any even number")

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


Assignment 2



1. Write a program to print a statment "Python World" 10 times (Using forloop)
2. Write a program to display numbers from 0 to 10
3. Write a program to display numbers from 0 to 100 which are divisible by 4
4. Write a program to display odd numbers from 0 to 20
5. Write a program to display numbers from 10 to 1 in decending order(use range with step size -1)
6. Write a program to print sum of elements of list
7. Write a program to convert lower case to uppercase of list of strings.
8. Write a Python program to find those numbers which are divisible by 7
between 100 and 200

9. Write a Python program that accepts a word from the user and reverse it

10. Write a Python program to count the number of even and odd numbers from a series
   of numbers

   ex : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output :
Number of even numbers : 5
Number of odd numbers : 4


11. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5

12. Write a Python program to get the Fibonacci series between 0 to 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before it.
Expected Output : 1 1 2 3 5 8 13 21 34

13. Write a Python program to check whether an alphabet which entered from
keyboard is vowel or constant.

Expected Output:

Input a letter of the alphabet: k                                   
k is a consonant.


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

String operations


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 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))

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


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]
>>>


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

tuples,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))

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

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)


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



Functions - Types of arguments




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')


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

modules , packages



Working with python modules :
==============================

Module is anyone ending with .py extension.
(or)
A module is a file consisting of python code also can contains
functions classes and variables.
(or)
Module refere to a file containing python statement and definitions
a module allows you to logically organize your python code.


How to create module :
===================

calc.py
--------

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

def sub(a,b):
c = a-b
return c

def mul(a,b):
c = a*b
return c

def div(a,b):
c = a/b
return c

module_ex.py

import calc

ret=calc.add(10,20)

print("the sum is",ret)



>> from..import is used to import only particular function instead of whole module definitions.


from calc import add

res = add(10,20)
print("result is ",res)

Usage of help function.

>>help()
>>modules()
>>quit

How to identify defintions;

>> import sys
>>dir(sys)


===============================

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)

Wednesday, August 22, 2018

Functions - Types of arguments





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')

Tuesday, August 21, 2018

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)


Saturday, August 18, 2018

tuples,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))



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]
>>>

Friday, August 17, 2018

String operations



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 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))

Assignment 2




1. Write a program to print a statment "Python World" 10 times (Using forloop)
2. Write a program to display numbers from 0 to 10
3. Write a program to display numbers from 0 to 100 which are divisible by 4
4. Write a program to display odd numbers from 0 to 20
5. Write a program to display numbers from 10 to 1 in decending order(use range with step size -1)
6. Write a program to print sum of elements of list
7. Write a program to convert lower case to uppercase of list of strings.
8. Write a Python program to find those numbers which are divisible by 7
between 100 and 200

9. Write a Python program that accepts a word from the user and reverse it

10. Write a Python program to count the number of even and odd numbers from a series
   of numbers

   ex : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output :
Number of even numbers : 5
Number of odd numbers : 4


11. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5

12. Write a Python program to get the Fibonacci series between 0 to 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before it.
Expected Output : 1 1 2 3 5 8 13 21 34

13. Write a Python program to check whether an alphabet which entered from
keyboard is vowel or constant.

Expected Output:

Input a letter of the alphabet: k                                   
k is a consonant.

Thursday, August 16, 2018

loops





What is loop?

A loop is a sequence instructions that is continually repeated
until a certain condition reached.


Types of loops in Python :
------------------------
1. for loop
2. while loop
3. Nested loop

Loop control statements :
1. break
2. Continue

for loop :
=========


for(i=0;i<n;i++) ===> ( which is not implemented in python)



>>> for i in range(5):
print(i)


0
1
2
3
4




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

>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> for i in range(1,n,2):
print(i)



1
3

>>> for i in "PYTHON":
print(i)


P
Y
T
H
O
N

for_example.py
-------------
1. To do operation on each and every element of list.
a = [1,2,3,4]
s = 0
for i in a:
s = s+i
print(s)



2. return to list

a = [1,2,3,4]

for i in a:
print(i ** 2)

b = [  (i**2) for i in a]
print(b)



for with if :
-------------

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number ")
else:
print(data," is odd number")


output:
--------
12  is even number
3  is odd number
42  is even number
34  is even number
4  is even number
2  is even number
2  is even number


usage of end  in print statement :

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number",end = ":\n")
else:
print(data," is odd number",end = ":\n")


12  is even number:
3  is odd number:
42  is even number:
34  is even number:
4  is even number:
2  is even number:
2  is even number:


student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(" %d is even number " %data)
else:
print(" %d is odd number " %data)

%d,%i --> integer
%s  --> string
%f ---> float


>>> name = "ravi"
>>> age = 24

>>> print(" stuedent name %s and age is %d" %(name,age))
 stuedent name ravi and age is 24



dataset =  ['python','java','perl']

for i in dataset:
print(i.upper())

PYTHON
JAVA
PERL

for i in dataset:
print(i[0].upper()+i[1:])

Python
Java
Perl



for loop with else clause :
-------------------------

numbers = [10,20,30,40,50]

for i in numbers:
print(i)
else:
print("Loop completed successfuly")



Looping control statement :
-------------------------
A statement that alters the execution of loop from its designated sequence is called loop control statement

1. Break:

To break out the loop we can use break function.

syntax :

for varaiable_name in sequence :
statement1
statement2
if(condition):
break

>>> lst = [10,20,30,40]
>>> for i in lst:
if(i == 30):
break
print(i)


10
20

Note: if we stop loop using break statement then else part will not execute.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
break

print(i)
else :
print("loop completed")

10
20

1. program to write list contains at least one even number

lst = [1,2,3,5,7,9]

for i in lst:
if(i%2 == 0):
print("event number present")
break
else:
print("list does not contain even number")


Continue statement :
----------------

Continue statement is used to tell python to jump to the next iteration of loop.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
continue

print(i)
else :
print("loop completed")


10
20
40
loop completed


while loop:
===========

while loop is used to execute no.of statements till the condition passed in while loop.
once condition is false, the control will come out the loop.

syntax :

while<expression>:
statement1
statement2


>>> while(i < n):
print(i)
i += 1


0
1
2
3
4
5
6
7
8
9

>>> while(i < n):
print(i)

infinite loop

while else loop:
-----------------

i=0
while (i<10):
print(i)
i += 1
else:
print("loop completed")


Pythone Nested Loops:
=====================

Nested loop --> loop inside another loop

mulitiplication table :

for i in range(1,5):
for j in range(1,10):
print('%d * %d = %d' %(i,j,i*j))

print("\n")

for..else condition example:
===========================


lst = [1,3,5,7]

for i in lst:
if(i%2==0):
print("even number found")
break

else:
print("did not find any even number")

Wednesday, August 15, 2018

user_authentication.py



'''
scriptname : user_authentication.py
Author : phani
Date : 16/08/2018
Description : User authentication
Version : 1.0

'''
#python user_authentication.py HDFC

import sys


if (len(sys.argv) < 2) :
print("invalid number of arguments")
sys.exit(1)


bank_name = sys.argv[1]

print("welcome to ",bank_name)



usr_details = {'HDFC001':'HDFC_PWD_001','HDFC002':'HDFC_PWD_002'}

usr_nm = input("Enter user name \n")
pwd = input("Enter password \n")

#usr_details.keys()---> ['HDFC001','HDFC002']

if (usr_nm in usr_details.keys()):
if(pwd == usr_details[usr_nm]):
print("login succssfull")
else:
print("in valid password")
sys.exit(1)

else:
print("invalid user")
sys.exit(1)

print("Welcome Mr.",usr_nm)



usr_acnt_dtls = {'HDFC001':'3234565','HDFC002':'5674839'}
acc_blnce_dtls = {'3234565':20000,'5674839':30000}

option = int(input("Enter your choice \n 1.Balance Enquiry \n 2. WithDraw \n 3. Deposit\n"))

if option==1:
acc_nmbr = usr_acnt_dtls[usr_nm]
#'3234565'
balance = acc_blnce_dtls[acc_nmbr]
print("current balance is",balance)

elif option==2:
print("you have choosen withdraw\n")

elif option==3:
print("you have choosen deposit\n")
else:
print("invalid choice")

print("Thanks for visiting",bank_name)



Tuesday, August 14, 2018

Assignment




1. Write a program to read 2 numbers from keyboards and print sum

2. Write a program to read employee data from keyboard and Print.
Note : employee data contains eno,ename,esal,eaddress

3. Write a program to find biggest of give 2 numbers from the command prompt?

4. Write a program to find biggest of given 3 numbers from the command prompt?

5. Write a program to find smallest of given 2 numbers?

6. Write a program to check whether the given number is even or odd?

7. Write a program to check whether the give number is in between 1 and 50?

8. Write a program to take a single digit number from the keyboard and print its value in word?

9. Write a program to check whether a number is negative, positive or zero.

10. Write a program to check whether a number is divisible by 5 and 11 or not.

11. Write a program to check whether a number is even or odd.

12. Write a program to input week number and print week day.

13. Write a program to input basic salary of an employee and calculate its Gross salary according to following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%

14. Write a program to calculate and print the Electricity bill of a given customer. The customer id., name and unit consumed by the user should be taken from the keyboard and display the total amount to pay to the customer.

The charge are as follow :
Unit Charge/unit
upto 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00

If bill exceeds Rs. 400 then a surcharge of 15% will be charged and the minimum bill should be of Rs. 100/-.

Test Data :
Enter Customer ID : 1001
Enter Customer Name : Reddy
Enter Number of Units Consumed : 800

Expected Output :
Customer ID :1001
Customer Name :Reddy
unit Consumed :800
Amount Charges @Rs. 2.00 per unit : 1600.00
Surchage Amount : 240.00
Net Amount Paid By the Customer : 1840.00

Command line arguments and conditional statements




Command Line Arguments:
-----------------------
While running program arguments which are passing through commnd line
are called as command line arguments .

Here arguments are separated by space.

>> python add.py 10 20

* These argumens are stored by default in the form of strings in a list with name argv.
  this is available in sys module.

argv[0] --> add.py
10   --> 10
20 --> 20

cmnd_line.py
===============

import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

print(type(a))
print(type(b))

add = a + b
print(add)

NOTE : default it will take string so we have convert to integer

execution :

C:\Users\welcome\Desktop>python cmnd_line.py 10 20


Flow control:
--------------

1.conditional statements
2. Transfer statements
3. Iterative statements



conditional statments(if..elif..else)
============================

 If any statment expecting its sub statements then it should be ended with :

conditional execution :

if x > 0 :
print('x is positive')

Alternative execution :

if x%2 == 0 :
print('x is even')
else :
print('x is odd')

Chained conditionals :

if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'

Sunday, August 12, 2018

Operators





OPERATORS IN PYTHON :
==========================

* The operator is symbol that perform some operation.
* a+b  => a,b are operands and + is operator

1. Arithmetic operators --->+,-,*,/,//,%
2. Assignment operators --> =, +=,-=,*=,/=,//=
3. Unary minus operators --> -
4. Relational operators -----> <,<=,>,>=,==
5. Logical operators ----> and or not
6. Boolean operators --> True, False
7. Bitwise operators
8. Membership operators ---> in , not in
9. Identity operators --> is,is not

Arithmetic operators  : +,-,*,/,//,%
--------------------
x = 15
y = 4


print('x + y =',x+y)
# Output: x + y = 19



print('x - y =',x-y)
# Output: x - y = 11

print('x * y =',x*y)
# Output: x * y = 60


print('x / y =',x/y)
# Output: x / y = 3.75


print('x // y =',x//y)
# Output: x // y = 3
--divide the result to whole number


print('x ** y =',x**y)
# Output: x ** y = 50625

>>> print("x % y is ",x%y)
   
x % y is  3

assignment operators
--------------------

Assignment operators in Python
Operator Example Equivatent to
=           x = 5   x = 5
*= x *= 5   x = x * 5
+=          x += 5    x = x+5
/=         x /= 5   x = x / 5
%=         x %= 5   x = x % 5
//=         x //= 5   x = x // 5
**=         x **= 5   x = x ** 5
^=         x ^= 5   x = x ^ 5


Unary minus Operator :
----------------------

Unary operator is denoted by (-) symbol. when this operator
used before symbol the value will be negated

>>> n = 10
>>> print(-n)
-10

Comparison (Relational) Operators
---------------------------------
< ,<=, > , >= , ==

True
False

x = 10
y = 12


print('x > y  is',x>y)
# Output: x > y is False


print('x < y  is',x<y)
# Output: x < y is True

print('x == y is',x==y)
# Output: x == y is False

print('x != y is',x!=y)
# Output: x != y is True

print('x >= y is',x>=y)
# Output: x >= y is False

print('x <= y is',x<=y)
# Output: x <= y is True


Logical operators
-----------------------



>>> a = 10
>>> b = 20
>>>
>>> c = a > b --> False
>>> d = a < b ---> True
>>> c
False
>>> d
True
>>>
>>> c and d
False
>>>
>>> c or d
True
>>>
>>> not c
True
>>>
>>> not a
False

Boolean Operators :
---------------------

We know there are two bool type literals. They are TRUE and FALSE.
Boolean operators act upon 'bool' type literals and they provide 'bool' type output.

It mean the result provided by boolean operators will be again either True or False.

There are 3 boolean operators as mentioned below

Let's take x= True
           y= False

>>> x = True
>>> y = False
>>> x and y
False
>>> x or y
True
>>> not x
False
>>> not y

True


TRUTH TABLE:
--------------

X Y X AND Y X OR Y x  xor y
T T T T F
T F F T T
F T F T T
F F F F F



Membership operators---> in ,not in
-----------------------

Operator     Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

x = 'Hello world'
y = {1:'a',2:'b'}


print('H' in x)
# Output: True

print('hello' not in x)
# Output: True

print(1 in y)
# Output: True

print('a' in y)
# Output: False



>>> a = [101,"srinivas","Hyd"]
>>> b = 101
>>> if(b in a):
print("true")
else :
print("false")


true
--------------

>>> a = {101:"srinivas",102:"Ravi",103:"Vijay"}
>>> rno = int(input("enter roll number\n"))
enter roll number
101
>>> print(rno)
101
>>> if( rno in a):
print(a[rno])

'srinivas'



Identity operators :
--------------------

These operators compare the memory location of two objects. Hence it is possible to know whether
the two objects are equal or not.

Object memory location can be identified by using id() function.

a =25
b =25

They are two identity operators

1. is
2. is not

*'is' operator :
it will compare the identity number of two objects. if both are same it will return true otherwise false.

* 'is not' operator :

>>> a = 20
>>> b = 21
>>> a is b
False

Difference between is and ==

>>> a = [1,2,3,4]
>>> b = [1,2,3,4]
>>> a == b                    // value is same
True
>>> a is b                    // value same but identity location is different.
False

>>> id(a)
52538696
>>> id(b)
52538504


# Python program to illustrate the use
# of 'is' identity operator
x = 5
if (type(x) is int):
    print ("true")
else:
    print ("false")

# Python program to illustrate the
# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
    print ("true")
else:
    print ("false")



Operator Precedence :
--------------------

()     --> paranthesis
**     --> Exponential
-,~    --> unary mins, Bitwise complement
*,/,//,%     --> Multiplication,division,floor division,Modules
+,- --> Addition,subtraction
<<,>> --> Bitwise left shift, Bitwise right shift
& --> Bitwise AND
^ --> Bitwise XOR
| --> Bitwise OR
>,>=,<,<=,==,!=     --> Assignment operators
is, is not --> Identity operators
in, not in --> Membership operators
not --> logical not
or  --> logical or
and --> logical and


precedence represents the priority level of the operator.
The operator which are high precedence will execute first than of lower precedence.

>>> a=1
>>> b=2
>>> c=3
>>> d=4
>>> e=5
>>> (a*b)+c*d
14
>>> a*(b+c)*d
20
>>> a*b+c*d
14
>>>

Bitwise operators
---------------------

Binary Number : starts with 0b

>>> a = 0b1101
>>> print(bin(a))
0b1101
>>> print(a)
13


>>> b = 18
>>> print(bin(18))
0b10010
>>> b = 0b10110
>>> print(b)
22

 Octal Number : start with 0O

>>> a = 0O101
>>> print(a)
65

>>> b = 96
>>> print(oct(b))
0o140

Hexa Decimal : starts with 0X


>>> b = 26
>>> print(hex(b))
0x1a
>>> b = 27
>>> print(hex(b))
0x1b
>>> b = 28
>>> print(hex(b))
0x1c
>>> b = 29
>>> print(hex(b))
0x1d
>>> b = 30
>>> print(hex(b))
0x1e
>>> b = 31
>>> print(hex(b))
0x1f
>>> b = 32
>>> print(hex(b))
0x20

i)Bitwise complement operatory(~)

>>> a = 4
>>> ~a
-5
>>> bin(a)
'0b100'

a=4 ---> 0100
~a --->  1011  ---> 11

But here compliler display -5  ( in 2's complement)

~N = -(N+1)

~4 =

N = 4 =  0100
+1    =     1
        --------
(N+1) 0101     = 5

~N = -(N+1)
~4 = -5




ii) Bitwise AND operator(&)

>>> a = 4
>>> b = 5
>>> a & b
4

a =   0100
b =   0101
a&b = 0100 = 4
      (both 1 then only 1 otherwise 0)

iii) Bitwise OR operator(|)

>>> a = 4
>>> b = 5
>>> a | b
5

a =  0100
b =  0101
a|b = 0101 = 5

(both 0 then 0 remaining 1)


iv) Bitwise XOR Operator(^)

>>> a = 4
>>> b = 5
>>> a ^ b
1

a   = 0100
b   = 0101
a^b = 0001

(any one should be 1 then 1 otherwise 0)



v) Bitwise Left shift operator(<<)

>>> a = 4
>>> a << 2
16
>>> a << 3
32

a = 4 = 0000 0100
a << 2= 0001 0000  = 16
a << 3= 0010 0000  = 32

vi) Bitwise Right shift operator(>>)


>>> a = 24
>>> a >> 2
6

a     = 0001 1000
a >>2 = 0000 0110  = 6 

Thursday, August 9, 2018

Complete Datatypes Material



Python Datatypes :
================
A datatype represents the type of data stored into a variable or memory.

Buitin datatypes -- Already available in python
User defined datatypes -- Datatypes created by programmers

1. Built in datatypes :

* None Type
* Numaric Types --> int,float,complex
* Sequences     --> str,bytes,bytearray,list,tuple,range
* Sets          --> set,frozenset
* Mappings      --> dict


Determine datatype :
----------------
type(variable name)


None :
-----
 'None' datatype represents an object that does not contain any value.
  In java - NULL
  In Python - None

>> print(type(None))
>>

>>> def calc():
...     a=10
...     b=20
...     c=a+b
...

    >>> calc()
    >>> res = calc()
    >>> type(res)
    <class 'NoneType'>


>>> if(res==None):
...     print("does not return any values")
...
does not return any values

Numaric dataypes :
--------------------
1. int
2. float
3. complex

int :
* Int represents an integer number.
* It is number with out decimal part and fraction part
* There is no limit for size of int datatype. It can store any integer number conveniently.

Eg :
>>> a = 20
>>> type(a)
<class 'int'>
>>> a = -234
>>> print(a)
-234
>>> a = 22222222222222222222222222222222222222222222222222222222
>>> print(a)
22222222222222222222222222222222222222222222222222222222
>>> type(a)
<class 'int'>

Float :
* Float represents floating number
* A floating number contains decimal part

Eg:
>>> a = 223.345
>>> type(a)
<class 'float'>
>>> a = 22e5
>>> print(a)
2200000.0


Converting the datatype explicitly :
--------------------------------
>>> x = 23
>>> type(x)
<class 'int'>
>>> b = float(x)
>>> print(b)
23.0
>>> c = 23.345
>>> d = int(c)
>>> print(d)
23

Complex Datatype :

* complex number is number that is written in the form of a+bj or a+bJ
a : real part
b : imaginary part

Eg :

>>> a = 1+2j
>>> b = 2+3j
>>> c = a+b
>>> print(c)
(3+5j)

>>> c = 1+2j
>>> d = 1-2j
>>> res = c * d
>>> print(res)
(5+0j)






bool datatype :

The bool datatype in python represents boolean values.


>>> a = 20
     >>> b = 10
     >>> print(a>b)
     True
     >>> print(a<b)
     False
     >>> c=print(a>b)
     True
     >>> print(c)
     None
     >>> c=a>b
     >>> print(c)
     True
 
 
     >>> True + True
     2
     >>> True - False
     1
 
     >>> file1 = True
     >>> file2 = True
     >>> file3 = True
     >>> print(file1+file2+file3)
     3


 Sequences in Python :
 --------------------

 A sequence represents a group of elements or items.

 eg : group of integer numbers will form seqence

 There are six types of sequences in python :

 1. str
 2. bytes
 3. bytearray
 4. list
 5. tuple
 6. range

str datatype :

* str represents string datatype.
* string represents group of characters
* string enclosed in single quotes or double quotes('',"")
* string can also be represent in """ or '''(if assign to variable then string otherwise it would be comment only)


eg :

>>> print(word)
welcome
>>> word = "welcome"
>>> print(word)
welcome
>>> word = '''welcome'''
>>> print(word)
welcome
>>> word = """welcome"""
>>> print(word)
welcome

for = 'Quality Thought!'
SyntaxError: invalid syntax (for is key word, variable name should not be key word)

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

Note : explain about file processing , file name contain date

>>> name[0:4]
'Qual'
>>> name[0:6:2]
'Qai'
>>> print(name[0:4])
Qual
>>> print(name[0:6:2])
Qai


There is no char datatype like C in python.

>>> ch = 'A'
>>> type(ch)
<class 'str'>

>>> ch = 'A'
>>> type(ch)
<class 'str'>
>>> name = "ravi"
>>> name[0]
's'



bytes datatype :

The bytes datatype represents a group of byte numbers
just like an array does.
* should be 0 to 255
* Does not support negative numbers

>>> a = [12,23,45]
>>> x = bytes(a)
>>> type(x)
<class 'bytes'>
>>> x[0]=55
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
x[0]=55
TypeError: 'bytes' object does not support item assignment
>>> a = [12,23,45,345]
>>> x = bytes(a) x
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)
>>> a = [12,23,45,-23]
>>> x = bytes(a)
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)

bytearray datatype :

* The bytearray datatype is similar to bytes data type. The difference is that
the bytes type array can not be modified but bytearray can be modified

>>> a = [12,23,34,54]
>>> x = bytearray(a)
>>> print(x[0])
12
>>> x[0] = 55
>>> for i in x:
print(i)
55
23
34
54

List datatype :


List  : Store different data type elements, can grow dynamically.

* List represent in [] and elements separated by ,

>>> a= [101,"ravi",'NRT']
>>> b =[102,"raju","HYD"]
>>> a[0]
101
>>> a[0:2]
[101, 'ravi']
>>> b[:3]
[102, 'raju', 'HYD']

>>> print(a)
[101, 'ravi', 'NRT']
>>> type(a)
<class 'list'>

>>> print(a)
[101, 'ravi', 'NRT']
>>> a[0]
101
>>> a[0] = 111
>>> print(a)
[111, 'ravi', 'NRT']           

list elements can be modified



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']







tuple datatype :

* Tuple is similar to list.
* Can contain different datatypes of elements
* Represents ()
* Differene between list and tuple is
can not modify the tuple so tuple is read only list.

>>> account_details = (101,"ravi","NRT")
>>> type(account_details)
<class 'tuple'>
>>> account_details[0]
101
>>> account_details[1]
'ravi'
>>> account_details[1] = "raju"
Traceback (most recent call last):
File "<pyshell#171>", line 1, in <module>
account_details[1] = "raju"
TypeError: 'tuple' object does not support item assignment


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print(tuple)           # Prints complete list
print(tuple[0])        # Prints first element of the list
print(tuple[1:3])      # Prints elements starting from 2nd till 3rd
print(tuple[2:])       # Prints elements starting from 3rd element
print(tinytuple * 2)   # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

range data type :
-----------------
* range data type represents sequence of numbers.
* The numbers in range are not modifiable
* Generally range is used for repeating a for loop for specific number of times.

>>> a = range(10)
>>> print(a)
range(0, 10)
>>> type(a)
<class 'range'>
>>> for i in a:
print(i)


0
1
2
3
4
5
6
7
8
9



>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28


>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28

 Sets :

A set is an unordered collection of elements much like a set in mathematics.

* Order of elements is not maintained. It means elements may not appear in the same order as they entered in to set.
* Set does not accept duplicate elements
* Two types of sets
1. set datatype
2. frozenset datatype

set datatype :
* set elements should separated with ,
* set always print only unique elements.


>>> s = {10,20,30,40,50}
>>> print(s)
{40, 10, 50, 20, 30}
>>> type(s)
<class 'set'>
>>> s = {10,10,20,20,30,30}
>>> print(s)
{10, 20, 30}

>>> str1 = set("srinivas")
>>> print(str1)
{'r', 'v', 'n', 'a', 's', 'i'}

>>> str2 = list(str1)
>>> print(str2)
['r', 'v', 'n', 'a', 's', 'i']
>>> print(str2[0])
r
>>> print(str2[1])
v

>>> s = {10,20,30,40}
>>> s.update([50])        // adding element to set
>>> print(s)
{40, 10, 50, 20, 30}
>>>
>>> print(s)
{40, 10, 50, 20, 30}
>>> s.remove(50)            // remove element from set
>>> print(s)
{40, 10, 20, 30}

fronzenset datatype:

* Create frozenset by passing set data
* Can not be modified (update and remove methods will not work)


>>> s = {50,60,70,80,90}
>>> fs = frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> print(fs)
frozenset({80, 50, 70, 90, 60})
>>> s = {50,50,60,60,70}
>>> fs1 = frozenset(s)
>>> type(fs1)
<class 'frozenset'>
>>> print(fs1)
frozenset({50, 60, 70})


Mapping Type :
-------------
* map represents a group of elements in the form of key values pairs so that when key is given
  will retrive a value.

 * The 'dict' datatype is an example of map
 * dict represents dictionary that contains of pair of elements first one is Key and second one is Value
 * key and value separated by ':'


>>> d = {101:"Ram",102:"Ravi",103:"Rani"}
>>> print(d)
{101: 'Ram', 102: 'Ravi', 103: 'Rani'}
>>> d[101]
'Ram'
>>> d[102]
'Ravi'
>>> type(d)
<class 'dict'>


dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict['one'])       # Prints value for 'one' key
print(dict[2])           # Prints value for 2 key
print(tinydict)          # Prints complete dictionary
print(tinydict.keys())   # Prints all the keys
print(tinydict.values()) # Prints all the values


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


modules , packages



Working with python modules :
==============================

Module is anyone ending with .py extension.
(or)
A module is a file consisting of python code also can contains
functions classes and variables.
(or)
Module refere to a file containing python statement and definitions
a module allows you to logically organize your python code.


How to create module :
===================

calc.py
--------

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

def sub(a,b):
c = a-b
return c

def mul(a,b):
c = a*b
return c

def div(a,b):
c = a/b
return c

module_ex.py

import calc

ret=calc.add(10,20)

print("the sum is",ret)



>> from..import is used to import only particular function instead of whole module definitions.


from calc import add

res = add(10,20)
print("result is ",res)

Usage of help function.

>>help()
>>modules()
>>quit

How to identify defintions;

>> import sys
>>dir(sys)


===============================

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)

Wednesday, August 22, 2018

Functions - Types of arguments





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')

Tuesday, August 21, 2018

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)


Saturday, August 18, 2018

tuples,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))



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]
>>>

Friday, August 17, 2018

String operations



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 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))

Assignment 2




1. Write a program to print a statment "Python World" 10 times (Using forloop)
2. Write a program to display numbers from 0 to 10
3. Write a program to display numbers from 0 to 100 which are divisible by 4
4. Write a program to display odd numbers from 0 to 20
5. Write a program to display numbers from 10 to 1 in decending order(use range with step size -1)
6. Write a program to print sum of elements of list
7. Write a program to convert lower case to uppercase of list of strings.
8. Write a Python program to find those numbers which are divisible by 7
between 100 and 200

9. Write a Python program that accepts a word from the user and reverse it

10. Write a Python program to count the number of even and odd numbers from a series
   of numbers

   ex : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output :
Number of even numbers : 5
Number of odd numbers : 4


11. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5

12. Write a Python program to get the Fibonacci series between 0 to 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before it.
Expected Output : 1 1 2 3 5 8 13 21 34

13. Write a Python program to check whether an alphabet which entered from
keyboard is vowel or constant.

Expected Output:

Input a letter of the alphabet: k                                   
k is a consonant.

Thursday, August 16, 2018

loops





What is loop?

A loop is a sequence instructions that is continually repeated
until a certain condition reached.


Types of loops in Python :
------------------------
1. for loop
2. while loop
3. Nested loop

Loop control statements :
1. break
2. Continue

for loop :
=========


for(i=0;i<n;i++) ===> ( which is not implemented in python)



>>> for i in range(5):
print(i)


0
1
2
3
4




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

>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> n = 5
>>> for i in range(1,n):
print(i)


1
2
3
4
>>> for i in range(1,n,2):
print(i)



1
3

>>> for i in "PYTHON":
print(i)


P
Y
T
H
O
N

for_example.py
-------------
1. To do operation on each and every element of list.
a = [1,2,3,4]
s = 0
for i in a:
s = s+i
print(s)



2. return to list

a = [1,2,3,4]

for i in a:
print(i ** 2)

b = [  (i**2) for i in a]
print(b)



for with if :
-------------

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number ")
else:
print(data," is odd number")


output:
--------
12  is even number
3  is odd number
42  is even number
34  is even number
4  is even number
2  is even number
2  is even number


usage of end  in print statement :

student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(data," is even number",end = ":\n")
else:
print(data," is odd number",end = ":\n")


12  is even number:
3  is odd number:
42  is even number:
34  is even number:
4  is even number:
2  is even number:
2  is even number:


student_marks = [12,3,42,34,4,2,2]

for data in student_marks:
if( data % 2 == 0):
print(" %d is even number " %data)
else:
print(" %d is odd number " %data)

%d,%i --> integer
%s  --> string
%f ---> float


>>> name = "ravi"
>>> age = 24

>>> print(" stuedent name %s and age is %d" %(name,age))
 stuedent name ravi and age is 24



dataset =  ['python','java','perl']

for i in dataset:
print(i.upper())

PYTHON
JAVA
PERL

for i in dataset:
print(i[0].upper()+i[1:])

Python
Java
Perl



for loop with else clause :
-------------------------

numbers = [10,20,30,40,50]

for i in numbers:
print(i)
else:
print("Loop completed successfuly")



Looping control statement :
-------------------------
A statement that alters the execution of loop from its designated sequence is called loop control statement

1. Break:

To break out the loop we can use break function.

syntax :

for varaiable_name in sequence :
statement1
statement2
if(condition):
break

>>> lst = [10,20,30,40]
>>> for i in lst:
if(i == 30):
break
print(i)


10
20

Note: if we stop loop using break statement then else part will not execute.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
break

print(i)
else :
print("loop completed")

10
20

1. program to write list contains at least one even number

lst = [1,2,3,5,7,9]

for i in lst:
if(i%2 == 0):
print("event number present")
break
else:
print("list does not contain even number")


Continue statement :
----------------

Continue statement is used to tell python to jump to the next iteration of loop.


lst = [10,20,30,40]
for i in lst:
if(i == 30):
continue

print(i)
else :
print("loop completed")


10
20
40
loop completed


while loop:
===========

while loop is used to execute no.of statements till the condition passed in while loop.
once condition is false, the control will come out the loop.

syntax :

while<expression>:
statement1
statement2


>>> while(i < n):
print(i)
i += 1


0
1
2
3
4
5
6
7
8
9

>>> while(i < n):
print(i)

infinite loop

while else loop:
-----------------

i=0
while (i<10):
print(i)
i += 1
else:
print("loop completed")


Pythone Nested Loops:
=====================

Nested loop --> loop inside another loop

mulitiplication table :

for i in range(1,5):
for j in range(1,10):
print('%d * %d = %d' %(i,j,i*j))

print("\n")

for..else condition example:
===========================


lst = [1,3,5,7]

for i in lst:
if(i%2==0):
print("even number found")
break

else:
print("did not find any even number")

Wednesday, August 15, 2018

user_authentication.py



'''
scriptname : user_authentication.py
Author : phani
Date : 16/08/2018
Description : User authentication
Version : 1.0

'''
#python user_authentication.py HDFC

import sys


if (len(sys.argv) < 2) :
print("invalid number of arguments")
sys.exit(1)


bank_name = sys.argv[1]

print("welcome to ",bank_name)



usr_details = {'HDFC001':'HDFC_PWD_001','HDFC002':'HDFC_PWD_002'}

usr_nm = input("Enter user name \n")
pwd = input("Enter password \n")

#usr_details.keys()---> ['HDFC001','HDFC002']

if (usr_nm in usr_details.keys()):
if(pwd == usr_details[usr_nm]):
print("login succssfull")
else:
print("in valid password")
sys.exit(1)

else:
print("invalid user")
sys.exit(1)

print("Welcome Mr.",usr_nm)



usr_acnt_dtls = {'HDFC001':'3234565','HDFC002':'5674839'}
acc_blnce_dtls = {'3234565':20000,'5674839':30000}

option = int(input("Enter your choice \n 1.Balance Enquiry \n 2. WithDraw \n 3. Deposit\n"))

if option==1:
acc_nmbr = usr_acnt_dtls[usr_nm]
#'3234565'
balance = acc_blnce_dtls[acc_nmbr]
print("current balance is",balance)

elif option==2:
print("you have choosen withdraw\n")

elif option==3:
print("you have choosen deposit\n")
else:
print("invalid choice")

print("Thanks for visiting",bank_name)



Tuesday, August 14, 2018

Assignment




1. Write a program to read 2 numbers from keyboards and print sum

2. Write a program to read employee data from keyboard and Print.
Note : employee data contains eno,ename,esal,eaddress

3. Write a program to find biggest of give 2 numbers from the command prompt?

4. Write a program to find biggest of given 3 numbers from the command prompt?

5. Write a program to find smallest of given 2 numbers?

6. Write a program to check whether the given number is even or odd?

7. Write a program to check whether the give number is in between 1 and 50?

8. Write a program to take a single digit number from the keyboard and print its value in word?

9. Write a program to check whether a number is negative, positive or zero.

10. Write a program to check whether a number is divisible by 5 and 11 or not.

11. Write a program to check whether a number is even or odd.

12. Write a program to input week number and print week day.

13. Write a program to input basic salary of an employee and calculate its Gross salary according to following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%

14. Write a program to calculate and print the Electricity bill of a given customer. The customer id., name and unit consumed by the user should be taken from the keyboard and display the total amount to pay to the customer.

The charge are as follow :
Unit Charge/unit
upto 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00

If bill exceeds Rs. 400 then a surcharge of 15% will be charged and the minimum bill should be of Rs. 100/-.

Test Data :
Enter Customer ID : 1001
Enter Customer Name : Reddy
Enter Number of Units Consumed : 800

Expected Output :
Customer ID :1001
Customer Name :Reddy
unit Consumed :800
Amount Charges @Rs. 2.00 per unit : 1600.00
Surchage Amount : 240.00
Net Amount Paid By the Customer : 1840.00

Command line arguments and conditional statements




Command Line Arguments:
-----------------------
While running program arguments which are passing through commnd line
are called as command line arguments .

Here arguments are separated by space.

>> python add.py 10 20

* These argumens are stored by default in the form of strings in a list with name argv.
  this is available in sys module.

argv[0] --> add.py
10   --> 10
20 --> 20

cmnd_line.py
===============

import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

print(type(a))
print(type(b))

add = a + b
print(add)

NOTE : default it will take string so we have convert to integer

execution :

C:\Users\welcome\Desktop>python cmnd_line.py 10 20


Flow control:
--------------

1.conditional statements
2. Transfer statements
3. Iterative statements



conditional statments(if..elif..else)
============================

 If any statment expecting its sub statements then it should be ended with :

conditional execution :

if x > 0 :
print('x is positive')

Alternative execution :

if x%2 == 0 :
print('x is even')
else :
print('x is odd')

Chained conditionals :

if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'

Sunday, August 12, 2018

Operators





OPERATORS IN PYTHON :
==========================

* The operator is symbol that perform some operation.
* a+b  => a,b are operands and + is operator

1. Arithmetic operators --->+,-,*,/,//,%
2. Assignment operators --> =, +=,-=,*=,/=,//=
3. Unary minus operators --> -
4. Relational operators -----> <,<=,>,>=,==
5. Logical operators ----> and or not
6. Boolean operators --> True, False
7. Bitwise operators
8. Membership operators ---> in , not in
9. Identity operators --> is,is not

Arithmetic operators  : +,-,*,/,//,%
--------------------
x = 15
y = 4


print('x + y =',x+y)
# Output: x + y = 19



print('x - y =',x-y)
# Output: x - y = 11

print('x * y =',x*y)
# Output: x * y = 60


print('x / y =',x/y)
# Output: x / y = 3.75


print('x // y =',x//y)
# Output: x // y = 3
--divide the result to whole number


print('x ** y =',x**y)
# Output: x ** y = 50625

>>> print("x % y is ",x%y)
   
x % y is  3

assignment operators
--------------------

Assignment operators in Python
Operator Example Equivatent to
=           x = 5   x = 5
*= x *= 5   x = x * 5
+=          x += 5    x = x+5
/=         x /= 5   x = x / 5
%=         x %= 5   x = x % 5
//=         x //= 5   x = x // 5
**=         x **= 5   x = x ** 5
^=         x ^= 5   x = x ^ 5


Unary minus Operator :
----------------------

Unary operator is denoted by (-) symbol. when this operator
used before symbol the value will be negated

>>> n = 10
>>> print(-n)
-10

Comparison (Relational) Operators
---------------------------------
< ,<=, > , >= , ==

True
False

x = 10
y = 12


print('x > y  is',x>y)
# Output: x > y is False


print('x < y  is',x<y)
# Output: x < y is True

print('x == y is',x==y)
# Output: x == y is False

print('x != y is',x!=y)
# Output: x != y is True

print('x >= y is',x>=y)
# Output: x >= y is False

print('x <= y is',x<=y)
# Output: x <= y is True


Logical operators
-----------------------



>>> a = 10
>>> b = 20
>>>
>>> c = a > b --> False
>>> d = a < b ---> True
>>> c
False
>>> d
True
>>>
>>> c and d
False
>>>
>>> c or d
True
>>>
>>> not c
True
>>>
>>> not a
False

Boolean Operators :
---------------------

We know there are two bool type literals. They are TRUE and FALSE.
Boolean operators act upon 'bool' type literals and they provide 'bool' type output.

It mean the result provided by boolean operators will be again either True or False.

There are 3 boolean operators as mentioned below

Let's take x= True
           y= False

>>> x = True
>>> y = False
>>> x and y
False
>>> x or y
True
>>> not x
False
>>> not y

True


TRUTH TABLE:
--------------

X Y X AND Y X OR Y x  xor y
T T T T F
T F F T T
F T F T T
F F F F F



Membership operators---> in ,not in
-----------------------

Operator     Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

x = 'Hello world'
y = {1:'a',2:'b'}


print('H' in x)
# Output: True

print('hello' not in x)
# Output: True

print(1 in y)
# Output: True

print('a' in y)
# Output: False



>>> a = [101,"srinivas","Hyd"]
>>> b = 101
>>> if(b in a):
print("true")
else :
print("false")


true
--------------

>>> a = {101:"srinivas",102:"Ravi",103:"Vijay"}
>>> rno = int(input("enter roll number\n"))
enter roll number
101
>>> print(rno)
101
>>> if( rno in a):
print(a[rno])

'srinivas'



Identity operators :
--------------------

These operators compare the memory location of two objects. Hence it is possible to know whether
the two objects are equal or not.

Object memory location can be identified by using id() function.

a =25
b =25

They are two identity operators

1. is
2. is not

*'is' operator :
it will compare the identity number of two objects. if both are same it will return true otherwise false.

* 'is not' operator :

>>> a = 20
>>> b = 21
>>> a is b
False

Difference between is and ==

>>> a = [1,2,3,4]
>>> b = [1,2,3,4]
>>> a == b                    // value is same
True
>>> a is b                    // value same but identity location is different.
False

>>> id(a)
52538696
>>> id(b)
52538504


# Python program to illustrate the use
# of 'is' identity operator
x = 5
if (type(x) is int):
    print ("true")
else:
    print ("false")

# Python program to illustrate the
# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
    print ("true")
else:
    print ("false")



Operator Precedence :
--------------------

()     --> paranthesis
**     --> Exponential
-,~    --> unary mins, Bitwise complement
*,/,//,%     --> Multiplication,division,floor division,Modules
+,- --> Addition,subtraction
<<,>> --> Bitwise left shift, Bitwise right shift
& --> Bitwise AND
^ --> Bitwise XOR
| --> Bitwise OR
>,>=,<,<=,==,!=     --> Assignment operators
is, is not --> Identity operators
in, not in --> Membership operators
not --> logical not
or  --> logical or
and --> logical and


precedence represents the priority level of the operator.
The operator which are high precedence will execute first than of lower precedence.

>>> a=1
>>> b=2
>>> c=3
>>> d=4
>>> e=5
>>> (a*b)+c*d
14
>>> a*(b+c)*d
20
>>> a*b+c*d
14
>>>

Bitwise operators
---------------------

Binary Number : starts with 0b

>>> a = 0b1101
>>> print(bin(a))
0b1101
>>> print(a)
13


>>> b = 18
>>> print(bin(18))
0b10010
>>> b = 0b10110
>>> print(b)
22

 Octal Number : start with 0O

>>> a = 0O101
>>> print(a)
65

>>> b = 96
>>> print(oct(b))
0o140

Hexa Decimal : starts with 0X


>>> b = 26
>>> print(hex(b))
0x1a
>>> b = 27
>>> print(hex(b))
0x1b
>>> b = 28
>>> print(hex(b))
0x1c
>>> b = 29
>>> print(hex(b))
0x1d
>>> b = 30
>>> print(hex(b))
0x1e
>>> b = 31
>>> print(hex(b))
0x1f
>>> b = 32
>>> print(hex(b))
0x20

i)Bitwise complement operatory(~)

>>> a = 4
>>> ~a
-5
>>> bin(a)
'0b100'

a=4 ---> 0100
~a --->  1011  ---> 11

But here compliler display -5  ( in 2's complement)

~N = -(N+1)

~4 =

N = 4 =  0100
+1    =     1
        --------
(N+1) 0101     = 5

~N = -(N+1)
~4 = -5




ii) Bitwise AND operator(&)

>>> a = 4
>>> b = 5
>>> a & b
4

a =   0100
b =   0101
a&b = 0100 = 4
      (both 1 then only 1 otherwise 0)

iii) Bitwise OR operator(|)

>>> a = 4
>>> b = 5
>>> a | b
5

a =  0100
b =  0101
a|b = 0101 = 5

(both 0 then 0 remaining 1)


iv) Bitwise XOR Operator(^)

>>> a = 4
>>> b = 5
>>> a ^ b
1

a   = 0100
b   = 0101
a^b = 0001

(any one should be 1 then 1 otherwise 0)



v) Bitwise Left shift operator(<<)

>>> a = 4
>>> a << 2
16
>>> a << 3
32

a = 4 = 0000 0100
a << 2= 0001 0000  = 16
a << 3= 0010 0000  = 32

vi) Bitwise Right shift operator(>>)


>>> a = 24
>>> a >> 2
6

a     = 0001 1000
a >>2 = 0000 0110  = 6 

Thursday, August 9, 2018

Complete Datatypes Material



Python Datatypes :
================
A datatype represents the type of data stored into a variable or memory.

Buitin datatypes -- Already available in python
User defined datatypes -- Datatypes created by programmers

1. Built in datatypes :

* None Type
* Numaric Types --> int,float,complex
* Sequences     --> str,bytes,bytearray,list,tuple,range
* Sets          --> set,frozenset
* Mappings      --> dict


Determine datatype :
----------------
type(variable name)


None :
-----
 'None' datatype represents an object that does not contain any value.
  In java - NULL
  In Python - None

>> print(type(None))
>>

>>> def calc():
...     a=10
...     b=20
...     c=a+b
...

    >>> calc()
    >>> res = calc()
    >>> type(res)
    <class 'NoneType'>


>>> if(res==None):
...     print("does not return any values")
...
does not return any values

Numaric dataypes :
--------------------
1. int
2. float
3. complex

int :
* Int represents an integer number.
* It is number with out decimal part and fraction part
* There is no limit for size of int datatype. It can store any integer number conveniently.

Eg :
>>> a = 20
>>> type(a)
<class 'int'>
>>> a = -234
>>> print(a)
-234
>>> a = 22222222222222222222222222222222222222222222222222222222
>>> print(a)
22222222222222222222222222222222222222222222222222222222
>>> type(a)
<class 'int'>

Float :
* Float represents floating number
* A floating number contains decimal part

Eg:
>>> a = 223.345
>>> type(a)
<class 'float'>
>>> a = 22e5
>>> print(a)
2200000.0


Converting the datatype explicitly :
--------------------------------
>>> x = 23
>>> type(x)
<class 'int'>
>>> b = float(x)
>>> print(b)
23.0
>>> c = 23.345
>>> d = int(c)
>>> print(d)
23

Complex Datatype :

* complex number is number that is written in the form of a+bj or a+bJ
a : real part
b : imaginary part

Eg :

>>> a = 1+2j
>>> b = 2+3j
>>> c = a+b
>>> print(c)
(3+5j)

>>> c = 1+2j
>>> d = 1-2j
>>> res = c * d
>>> print(res)
(5+0j)






bool datatype :

The bool datatype in python represents boolean values.


>>> a = 20
     >>> b = 10
     >>> print(a>b)
     True
     >>> print(a<b)
     False
     >>> c=print(a>b)
     True
     >>> print(c)
     None
     >>> c=a>b
     >>> print(c)
     True
 
 
     >>> True + True
     2
     >>> True - False
     1
 
     >>> file1 = True
     >>> file2 = True
     >>> file3 = True
     >>> print(file1+file2+file3)
     3


 Sequences in Python :
 --------------------

 A sequence represents a group of elements or items.

 eg : group of integer numbers will form seqence

 There are six types of sequences in python :

 1. str
 2. bytes
 3. bytearray
 4. list
 5. tuple
 6. range

str datatype :

* str represents string datatype.
* string represents group of characters
* string enclosed in single quotes or double quotes('',"")
* string can also be represent in """ or '''(if assign to variable then string otherwise it would be comment only)


eg :

>>> print(word)
welcome
>>> word = "welcome"
>>> print(word)
welcome
>>> word = '''welcome'''
>>> print(word)
welcome
>>> word = """welcome"""
>>> print(word)
welcome

for = 'Quality Thought!'
SyntaxError: invalid syntax (for is key word, variable name should not be key word)

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

Note : explain about file processing , file name contain date

>>> name[0:4]
'Qual'
>>> name[0:6:2]
'Qai'
>>> print(name[0:4])
Qual
>>> print(name[0:6:2])
Qai


There is no char datatype like C in python.

>>> ch = 'A'
>>> type(ch)
<class 'str'>

>>> ch = 'A'
>>> type(ch)
<class 'str'>
>>> name = "ravi"
>>> name[0]
's'



bytes datatype :

The bytes datatype represents a group of byte numbers
just like an array does.
* should be 0 to 255
* Does not support negative numbers

>>> a = [12,23,45]
>>> x = bytes(a)
>>> type(x)
<class 'bytes'>
>>> x[0]=55
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
x[0]=55
TypeError: 'bytes' object does not support item assignment
>>> a = [12,23,45,345]
>>> x = bytes(a) x
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)
>>> a = [12,23,45,-23]
>>> x = bytes(a)
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
x = bytes(a)
ValueError: bytes must be in range(0, 256)

bytearray datatype :

* The bytearray datatype is similar to bytes data type. The difference is that
the bytes type array can not be modified but bytearray can be modified

>>> a = [12,23,34,54]
>>> x = bytearray(a)
>>> print(x[0])
12
>>> x[0] = 55
>>> for i in x:
print(i)
55
23
34
54

List datatype :


List  : Store different data type elements, can grow dynamically.

* List represent in [] and elements separated by ,

>>> a= [101,"ravi",'NRT']
>>> b =[102,"raju","HYD"]
>>> a[0]
101
>>> a[0:2]
[101, 'ravi']
>>> b[:3]
[102, 'raju', 'HYD']

>>> print(a)
[101, 'ravi', 'NRT']
>>> type(a)
<class 'list'>

>>> print(a)
[101, 'ravi', 'NRT']
>>> a[0]
101
>>> a[0] = 111
>>> print(a)
[111, 'ravi', 'NRT']           

list elements can be modified



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']







tuple datatype :

* Tuple is similar to list.
* Can contain different datatypes of elements
* Represents ()
* Differene between list and tuple is
can not modify the tuple so tuple is read only list.

>>> account_details = (101,"ravi","NRT")
>>> type(account_details)
<class 'tuple'>
>>> account_details[0]
101
>>> account_details[1]
'ravi'
>>> account_details[1] = "raju"
Traceback (most recent call last):
File "<pyshell#171>", line 1, in <module>
account_details[1] = "raju"
TypeError: 'tuple' object does not support item assignment


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print(tuple)           # Prints complete list
print(tuple[0])        # Prints first element of the list
print(tuple[1:3])      # Prints elements starting from 2nd till 3rd
print(tuple[2:])       # Prints elements starting from 3rd element
print(tinytuple * 2)   # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

range data type :
-----------------
* range data type represents sequence of numbers.
* The numbers in range are not modifiable
* Generally range is used for repeating a for loop for specific number of times.

>>> a = range(10)
>>> print(a)
range(0, 10)
>>> type(a)
<class 'range'>
>>> for i in a:
print(i)


0
1
2
3
4
5
6
7
8
9



>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28


>>> r = range(10,30,3)
>>> for i in r:
print(i)


10
13
16
19
22
25
28

 Sets :

A set is an unordered collection of elements much like a set in mathematics.

* Order of elements is not maintained. It means elements may not appear in the same order as they entered in to set.
* Set does not accept duplicate elements
* Two types of sets
1. set datatype
2. frozenset datatype

set datatype :
* set elements should separated with ,
* set always print only unique elements.


>>> s = {10,20,30,40,50}
>>> print(s)
{40, 10, 50, 20, 30}
>>> type(s)
<class 'set'>
>>> s = {10,10,20,20,30,30}
>>> print(s)
{10, 20, 30}

>>> str1 = set("srinivas")
>>> print(str1)
{'r', 'v', 'n', 'a', 's', 'i'}

>>> str2 = list(str1)
>>> print(str2)
['r', 'v', 'n', 'a', 's', 'i']
>>> print(str2[0])
r
>>> print(str2[1])
v

>>> s = {10,20,30,40}
>>> s.update([50])        // adding element to set
>>> print(s)
{40, 10, 50, 20, 30}
>>>
>>> print(s)
{40, 10, 50, 20, 30}
>>> s.remove(50)            // remove element from set
>>> print(s)
{40, 10, 20, 30}

fronzenset datatype:

* Create frozenset by passing set data
* Can not be modified (update and remove methods will not work)


>>> s = {50,60,70,80,90}
>>> fs = frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> print(fs)
frozenset({80, 50, 70, 90, 60})
>>> s = {50,50,60,60,70}
>>> fs1 = frozenset(s)
>>> type(fs1)
<class 'frozenset'>
>>> print(fs1)
frozenset({50, 60, 70})


Mapping Type :
-------------
* map represents a group of elements in the form of key values pairs so that when key is given
  will retrive a value.

 * The 'dict' datatype is an example of map
 * dict represents dictionary that contains of pair of elements first one is Key and second one is Value
 * key and value separated by ':'


>>> d = {101:"Ram",102:"Ravi",103:"Rani"}
>>> print(d)
{101: 'Ram', 102: 'Ravi', 103: 'Rani'}
>>> d[101]
'Ram'
>>> d[102]
'Ravi'
>>> type(d)
<class 'dict'>


dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict['one'])       # Prints value for 'one' key
print(dict[2])           # Prints value for 2 key
print(tinydict)          # Prints complete dictionary
print(tinydict.keys())   # Prints all the keys
print(tinydict.values()) # Prints all the values

Comments

Popular posts from this blog

Python Training in Hyderabad

FULL STACK Python & Node JS Developer