Monday, 10 December 2018

Python Notes

Filter a given list by value is greater than 25
-----------------------------------------------
Traditional approach:
---------------------
>>> l = [10,20,30,40,50]
>>> r = []
>>> for v in l:
...     if (v>25):
...       r.append(v)
...
...
>>> r
[30, 40, 50]

Functional programming approach:
--------------------------------
>>> l = [10,20,30,40,50]
>>> rr = [v for v in l if v > 25 ]
>>> rr
[30, 40, 50]


Functional programming approach:
--------------------------------
>>> rr = [v * 10 for v in l if v > 25]
>>> rr
[300, 400, 500]


>>> l = [10,20,30,40,50]
>>> cnt = 0
>>> for v in l:
...     if (v == 45):
...             cnt += 1
>>> if (cnt == 0):
...     print("45 is not there in the list")
... else:
...     print("45 is there in the given list")
Result:
-------
45 is not there in the list



//check 30 exists in the given list or not:
-------------------------------------------
>>> l = [10,20,30,40,50]
>>> a = 30
>>> for v in l:
...     if (v == a):
...             cnt += 1
...
>>> cnt
1

set operations:
---------------
>>> a in l
True
>>> a not in l
False
>>> 45 not in l
True
>>> 45 in l
False

set:
-----
// eliminate duplicates using set
>>> lst = [10,20,30,10,10,20,30,40]
>>> set(lst)
{40, 10, 20, 30}


//eliminating duplicates in traditional way:
--------------------------------------------
>>> lst = [10,20,30,10,10,20,30,40]
>>> dlist = [lst[0]]
>>> dlist
[10]
>>> for v in lst:
...     if v not in dlist:
...             dlist.append(v)
...
>>> dlist
[10, 20, 30, 40]


1) put the very first element in dlist
2) if an element not in dlist append that into dlist



Set Vs List
-----------
List allows duplicates
Set doesn't allow duplicate



Find common friends :
-----------------------
>>> myfriends = ['a','b','c','d','e']
>>> urfriends = ['a','c','e','m','n','p']
>>> common = []
>>> for v in myfriends:
...     if v in urfriends:
...             common.append(v)
...
>>> common
['a', 'c', 'e']


Find non common friends: (Facebook friends recommendation)
----------------------------------------------------------
myfriends = ['a','b','c','d','e']
urfriends = ['a','c','e','m','n','p']
common = []
for v not in myfriends:
     if v in urfriends:
             common.append(v)

 
>>> l = [10,20,30,40,50]
>>> [v for v in l if v > 25]
[30, 40, 50]


>>> [v+100 for v in l if v > 25]
[130, 140, 150]


List vs Tuple:
--------------

List is for homogeneous
Tuple is for Hetrogeneous

>>> tupleexa = ("Ravi",25,"Hyderabad")
>>> tupleexa[0]
'Ravi'
>>> tupleexa[1]
25
>>> tupleexa[2]
'Hyderabad'
>>> tupleexa[1:]
(25, 'Hyderabad')
>>> tupleexa[-2]
25

In List I can append new element:
--------------------------------
//List is mutable (Changeable)
>>> l = [10,20,30,40,50]
>>> l.append(60)
>>> l
[10, 20, 30, 40, 50, 60]

//Tuple is immutable (NonChangeable)
>>> t = ('sa','re',23,True)
>>> t.append(False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'


// Modified 3rd index (30 into 300) in a list
>>> l = [10,20,30,40,50,100]
>>> l[2] = 300
>>> l
[10, 20, 300, 40, 50, 100]


// Can't modify existing element in a tuple:
>>> t = ("Ravi",25,"Hyderabad")
>>> t[1] = 26
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

// Kids and age
// Tuple inside the List
// I can append new tuple within the List
>>> lx = [('a',10),('b',8),('c',5)]
>>> lx
[('a', 10), ('b', 8), ('c', 5)]
// new baby born
>>> lx.append(('d',0))
>>> lx
[('a', 10), ('b', 8), ('c', 5), ('d', 0)]

>>> lx[0]
('a', 10)
>>> lx[1]
('b', 8)
>>> lx[-1]
('d', 0)
>>> lx[0][0]
'a'
>>> lx[0][1]
10
>>> lx[-1][0]
'd'
>>> lx[-1][1]
0

Tuple: ()
List : []
Dictionary : {}

Dictionary is equivalent to Map object
Collection of Key, Value Pairs.

>>> q = {"BTech":2000,"MTech":2003,"PhD":2010}
>>> q["BTech"]

>>> q.keys()
dict_keys(['BTech', 'MTech', 'PhD'])
>>> q.values()
dict_values([2000, 2003, 2010])


>>> q.get("ds")
>>> if (q.get('ds')==None):
...     print ("No Data science")
...
No Data science

//adding new key,value pair
>>> q["ds"] = 2018
>>> q
{'BTech': 2000, 'MTech': 2003, 'PhD': 2010, 'ds': 2018}

//modifying existing key, values
>>> q["BTech"]=2001
>>> q
{'BTech': 2001, 'MTech': 2003, 'PhD': 2010, 'ds': 2018}


>>> profiles =[('m',2000),('f',4000),('m',5000),('f',6000),('f',5000),('m',6000)]
>>> for v in profiles:
...     print (v)
...

Result:
('m', 2000)
('f', 4000)
('m', 5000)
('f', 6000)
('f', 5000)
('m', 6000)

Female total salary, Male total salary:
---------------------------------------
profiles =[('m',2000),('f',4000),('m',5000),('f',6000),('f',5000),('m',6000)]
summary = {}
for v in profiles:
  sex = v[0]
  sal = v[1]
  if (summary.get(sex)==None):
   summary[sex]=sal
  else:
   summary[sex] += sal

print(summary)


C:\PyCode>python profilemap.py
{'m': 13000, 'f': 15000}



lst =[(11,10000),(12,30000),(11,30000),(12,56000),(11,50000),(13,50000),(14,45000),(15,45000),(15,50000)]
summary = {}
for v in lst:
  dept = v[0]
  sal = v[1]
  if (summary.get(dept)==None):
   summary[dept]=sal
  else:
   summary[dept] += sal

print(summary)


C:\PyCode>python deptsalgrouping.py
{11: 90000, 12: 86000, 13: 50000, 14: 45000, 15: 95000}



// Take data from file

data1.txt:
-----------
"id","name","sal","sex","dno"
101,aaaa,100000,m,11
102,bbbb,200000,f,12
103,cccc,500000,f,12
104,dddd,600000,m,13

takedatafromfile.py
--------------------
f = open("C:\\PyCode\\data1.txt")
h = f.readline() // exclude header
lines = f.readlines()
summary={}
for line in lines:
ln = line.split("\n")[0]
words = ln.split(",")
dno = int (words[4])
sal = int (words[2])

if (summary.get(dno) == None):
summary[dno] = sal
else:
summary[dno] += sal
print (summary)


C:\PyCode>python takedatafromfile.py
{11: 100000, 12: 700000, 13: 600000}


>>> "a,b,c".split(",")
['a', 'b', 'c']


// Here I didnt specify any delimiter so default delimiter is just space
>>> "a   b      c    d  e f    g    h".split()
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']




f = open("C:\\PyCode\\data1.txt")
h = f.readline()
lines = f.readlines()
s={}
for line in lines:
words = line.split(",")
sex = words[3]
dno = words[4].split('\n')[0]
sal = int(words[2])
key = (dno , sex)
if (s.get(key) == None):
s[key]=sal
else:
s[key] += sal
print (s)


Result:
-------
C:\PyCode>python takedatafromfile.py
{('11', 'm'): 100000, ('12', 'f'): 700000, ('13', 'm'): 600000}
functions in Python:
--------------------
def <function name> (<arguments>):
----
----
----
[return <values>]

// No Arguments, No Return values
>>> def printInfo():
...     print("Hello")
...     print("Welcome to DataScience")
...

>>> printInfo()
Hello
Welcome to DataScience


Function with Arguments But No Return values:
---------------------------------------------
def info(name,age):
grade="old"
if (age <= 10):
grade="kid"
elif (age <= 30):
grade="adult"
elif(age <= 50):
grade="middle"
print(name,grade)

info("Ravi",37)
info("Raju",55)

Result:
-------
C:\PyCode>python functionexa.py
Ravi middle
Raju old


Function with Arguments and Return Values:
------------------------------------------
def total(a,b):
c = a+b
return c


x = int(input("First Number : "))
y = int(input("Second Number : "))
t = total(x,y)
print("The sum of ",x, " and ", y, " is : ",t)



Result:
-------
C:\PyCode>python functionexa.py
First Number : 3
Second Number : 5
The sum of  3  and  5  is :  8



Function with Default values for arguments:
-------------------------------------------
def fun(a=20,b=30):
c = a+b
return c


print(fun())
print(fun(a=1))
print(fun(a=2,b=3))
print(fun(b=33))

C:\PyCode>python functionexa.py
50
31
5
53

// A function can accepts multiple arguments but it can return only single value

// How to get multiple number of return values?
// To return multiple values, keep multiple entities as a collection object and return a collection like tuple.

def samp(x,y):
addition = x+y
subtraction = x - y
multiplication = x * y
division = x / y
modulo = x % y
return (addition, subtraction,multiplication,division,modulo)

print(samp(1,1))
print(samp(5,3))
print(samp(6,3))


Result:
------
C:\PyCode>python functionexa.py
(2, 0, 1, 1.0, 0)
(8, 2, 15, 1.6666666666666667, 2)
(9, 3, 18, 2.0, 0)



Function that performs transformations:
---------------------------------------
def fupper(x):
fc = x[0].upper()
rc = x[1:].lower()
return fc + rc

name = str(input("Enter a name : "))
print(fupper(name))


C:\PyCode>python fupperfunctionexa.py
Enter a name : ShIVASankaR
Shivasankar


Function with Multiple return in multiple places:
-------------------------------------------------
def VotingEligibility(age,sex):
if (sex.strip().lower() == "m"):
if (age >= 21):
return "Eligible"
else:
return "Not Eligible"
else:
if (age >= 18):
return "Eligible"
else:
return "Not Eligible"


age = int(input("Enter  Age : "))
sex = str(input("Enter sex : "))
print("Eligibility Test : ",VotingEligibility(age,sex))


Result:
-------
C:\PyCode>python votingeligibility.py
Enter  Age : 3
Enter sex : 3
Eligibility Test :  Not Eligible

C:\PyCode>python votingeligibility.py
Enter  Age : 21
Enter sex : M
Eligibility Test :  Eligible

C:\PyCode>python votingeligibility.py
Enter  Age : 18
Enter sex : F
Eligibility Test :  Eligible




def VotingEligibility(age,sex):
if (sex  == "m"):
if (age >= 21):
return "Eligible"
else:
return "Not Eligible"
else:
if (age >= 18):
return "Eligible"
else:
return "Not Eligible"


f = open("C:\\PyCode\\matrimony.txt")
lines = f.readlines()

for x in lines:
w = x.split(",")
sex = w[1].lower()
age = int(w[2].split("\n")[0])
print(w[0], " is ", VotingEligibility(age,sex))

Result:
-------
C:\PyCode>python votingeligibility-file.py
Ravi  is  Eligible
Mani  is  Not Eligible
Manish  is  Eligible
Meena  is  Not Eligible


>>> print("Hello")
Hello

>>> vegetable = 'asparagus'
>>> vegetable
'asparagus'

>>> vegetable="asparagus"
>>> vegetable
'asparagus'

>>> name = "Raja"
>>> name2 = "Mohan"
>>> city ='pallathur'
>>> name + name2 + city
'RajaMohanpallathur'

>>> sentence = 'He said, "That asparagus tastes great!"'
>>> sentence
'He said, "That asparagus tastes great!"'

>>> sentence = "That's some great tasting asparagus!"
>>> sentence
"That's some great tasting asparagus!"

>>> sentence[0]
'T'
>>> sentence[3]
't'
>>> len(sentence)
36
>>> l = len(sentence)
>>> print(l)
36

>>> print(sentence.lower())
that's some great tasting asparagus!
>>> print(sentence.upper())
THAT'S SOME GREAT TASTING ASPARAGUS!
>>> print('_'*12)
____________
>>> '_'*234
'__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________'
>>> a = 100
>>> str(a) + "sare"
'100sare'

>>> print("{} {} {}".format("Python","is","fun"))
Python is fun
>>>

>>> print("Python {0} {1} and {1} {0} awesome!".format('is','fun'))
Python is fun and fun is awesome!

>>> print("{0:25} | {1:50}".format("Product","Price"))
Product                   | Price



>>> costPerHour = 1.02
>>> costPerDay = costPerHour * 24
>>> costPerMonth = costPerDay * 30
>>> print ("Cost / Day : {0}, Cost / Month : {1}".format(costPerDay, costPerMonth)
... )
Cost / Day : 24.48, Cost / Month : 734.4
print()
len()
str()
input()
upper()
lower()
format()


>>> vegetable = input("Enter name of a vegetable")
Enter name of a vegetable  carrot

>>> print("{} is a lovely vegetable".format(vegetable))
carrot is a lovely vegetable


>>> sum = 3+2
>>> difference = 88 - 2
>>> product = 4 * 2
>>> quotient = 16 / 4
>>> power = 3 ** 4
>>> remainder = 7 % 3
>>> print ("Sum : {0}".format(sum))
Sum : 5

print ("Sum : {0}".format(sum))

>>> a = 4
>>> b = 55
>>> str(a) + str(b)
'455'

>>> m = "101"
>>> n = "10"
>>> int(m) + int(n)


>>> f = 132
>>> float(f)
132.0

# Computes the hosting costs for one server.


""" The comment starts here.
This is another line in the comment.
Here is the last line of the comment. """


>>> True
True
>>> False
False


>>> not False
True
>>> not (8 == 1)
True
>>> not (8 == 8)
False

>>> True and True
True
>>> True or True
True


>>> if (43 < 44): print ('Yes')
...
Yes



>>> def say_hi():
...     print("x")   #this will be inside a single tab
...
>>> say_hi()
x


>>> def sayWelcome(name):
...     print("Hello {}!".format(name))
...
>>> sayWelcome("Arumugam")
Hello Arumugam!
>>> sayWelcome("Shekar")
Hello Shekar!

default parameter
-----------------
>>> def sayHi(name="Priya"):
...     print("Hello {}!".format(name))
...
>>> sayHi()
Hello Priya!
>>> sayHi("Kamal")
Hello Kamal!


>>> def sum(a,b):
...     print("{} + {} = {}".format(a,b,a+b))
...
>>> sum(4,2)
4 + 2 = 6

Named parameters:
-----------------
>>> def sayIt(first,last):
...     print ("Hello {} {}!".format(first,last))
...
>>> sayIt(first=10,last=20)
Hello 10 20!
>>> sayIt(last="Siva",first="Priya")
Hello Priya Siva!



>>> def say_hello(first, last='Carberry'):
...  print('Hello {} {}!'.format(first, last))
...
>>> say_hello('Josiah')
Hello Josiah Carberry!
>>> say_hello('Hank', 'Mobley')
Hello Hank Mobley!

File : GetAndSayName.py
------------------------
def getName():
name = input("Enter your name ")
return name

def sayName(name):
print ("Your name is {}".format(name))

def getAndSayname():
name = getName()
sayName(name)

getAndSayname()

run it:
-------
C:\Python\exercise>python GetAndSay.py
Enter your name sarega
Your name is sarega


 def function_name(parameter_name):.


 List:
 -----
 list_name = [item_1, item_2, item_N]

 >>> animals = ['toad','lion','seal']
>>> animals[0]
'toad'

>>> print("{}, {},{}".format(animals[0],animals[1],animals[2]))
toad, lion,seal

>>> print(animals[0])
toad
>>> print(animals[1])
lion
>>> print(animals[2])
seal


>>> animals[0] = "Deer"
>>> animals[1] = "Elephant"
>>> animals[2] = "Tiger"
>>> print("{}, {},{}".format(animals[0],animals[1],animals[2]))
Deer, Elephant,Tiger

 The -1 index will represent the last item on the list, with -2 representing the second to last item on the list,
 and so on.

>>> print("{}, {},{}".format(animals[-1],animals[-2],animals[-3]))
Tiger, Elephant,Deer

Add single new item (Append)
----------------------
>>> animals
['Deer', 'Elephant', 'Tiger']
>>> animals.append('fox')
>>> animals.append('Lion')
>>> animals.append('bear')
>>> animals
['Deer', 'Elephant', 'Tiger', 'fox', 'Lion', 'bear']
>>> animals[-1]
'bear'

Add multiple items to a List: (Extend)
----------------------------
>>> animals.extend(['owl','peacock'])
>>> animals
['Deer', 'Elephant', 'Tiger', 'fox', 'Lion', 'bear', 'owl', 'peacock']



>>> birds =["peacock","crow","cuckoo"]
>>> animals=["lion","deer","elephant"]
>>> mixed=[birds,animals]  // combining 2 lists without using extend
>>> mixed
[['peacock', 'crow', 'cuckoo'], ['lion', 'deer', 'elephant']]  // see here 2 different lists inside


>>> animals.extend(birds)
>>> animals


['lion', 'deer', 'elephant', 'peacock', 'crow', 'cuckoo']


insert: insert an element at the specific position:
--------------------------------------------------
>>> animals
['lion', 'deer', 'elephant', 'peacock', 'crow', 'cuckoo']
>>> animals.insert(0,"whale")
>>> animals.insert(2,"owl")
>>> animals
['whale', 'lion', 'owl', 'deer', 'elephant', 'peacock', 'crow', 'cuckoo']


slicing:   index zero based, length - 1
---------
>>> some_animals = animals[1:4]
>>> print('Some animals: {}'.format(some_animals))
Some animals: ['lion', 'owl', 'deer']

first_two = animals[0:2]

first_two_again = animals[:2]


>>> part_of_a_whale = 'whale'[1:3]     ---> 0,1,2,3  ==> w h a l e  ===> h a  (start from 1 and till 4 -1 = 3rd
>>> print(part_of_a_whale)
ha


>>> animals = ['toad', 'lion', 'seal']
>>> lion_index = animals.index('lion')
>>> print(lion_index)
1

animals = ['toad', 'lion', 'seal']
try:
sheep_index = animals.index('sheep')
except:
sheep_index = 'No sheep found.'
print(sheep_index)

C:\Python\exercise>python exception1.py
No sheep found.

Loop through foreach:
------------------------
>>> animals = ['toad', 'lion', 'seal']
>>> for animal in animals:
...  print(animal.upper())
...
TOAD
LION
SEAL


while loop:
-----------
>>> animals = ['toad', 'lion', 'seal', 'fox', 'owl', 'whale', 'elk']
>>> index = 0
>>> while index < len(animals):
...  print(animals[index])
...  index += 1
...
toad
lion
seal
fox
owl
whale
elk

exception handling:
-------------------

animals = ['toad', 'lion', 'seal']
try:
sheep_index = animals.index('sheep')
except:
sheep_index = 'No sheep found.'
print(sheep_index)

A-Z Sorting:
------------

>>> animals = ['toad', 'lion', 'seal']
>>> sorted_animals = sorted(animals)
>>> sorted_animals
['lion', 'seal', 'toad']
>>> animals.sort
<built-in method sort of list object at 0x00837508>
>>> animals.sort()
>>> animals
['lion', 'seal', 'toad']
>>>

List Concatenation:
-------------------

>>> animals = ['toad', 'lion', 'seal']
>>> more_animals = ['fox', 'owl', 'whale']
>>> all_animals = animals + more_animals
>>> print(all_animals)
['toad', 'lion', 'seal', 'fox', 'owl', 'whale']
>>>

Length:
-------
>>> animals = ['toad', 'lion', 'seal']
>>> print(len(animals))
3
>>> animals.append('fox')
>>> print(len(animals))
4


Range:
------
>>> for number in range(4):
...  print(number)
...
0
1
2
3


Range with Step :
---------------
>>> for number in range(0, 10, 2):
...  print(number)
...
0
2
4
6
8


>>> animals = ['toad', 'lion', 'seal', 'fox', 'owl', 'whale', 'elk']
>>> for number in range(0, len(animals), 2):
...  print(animals[number])
...
toad
seal
owl
elk


C:\Python\exercise>python grocery.py
Enter an item for your grocery list. Press <ENTER> when done: Milk
Item added.
Enter an item for your grocery list. Press <ENTER> when done: Curd
Item added.
Enter an item for your grocery list. Press <ENTER> when done: Tofu
Item added.
Enter an item for your grocery list. Press <ENTER> when done:

Your Grocery List:
------------------
 Milk
 Curd
 Tofu


 # Create a list to hold the grocery items.
grocery_list = []
finished = False
while not finished:
item = input('Enter an item for your grocery list. Press <ENTER> when done:')
if len(item) == 0:
finished = True
else:
grocery_list.append(item)
print('Item added.')
# Display the grocery list.
print()
print('Your Grocery List:')
print('-' * 18)
for item in grocery_list:
 print(item)



Dictionary  - k,v : Key value pairs:
--------------------------------------
>>> contacts = {'David': '555-0123', 'Tom': '555-5678'}
    >>> davids_phone = contacts['David']
>>> toms_phone = contacts['Tom']
>>> print('Dial {} to call David.'.format(davids_phone))
Dial 555-0123 to call David.
>>> print('Dial {} to call Tom.'.format(toms_phone))
Dial 555-5678 to call Tom.

>>> contacts = {"Arun":"Sanjana","Sankar":"Sudha","Venkat":"Vanitha"}
>>> contacts[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0
>>> contacts["Venkat"]
'Vanitha'
>>> contacts["Arun"]
'Sanjana'

Change the Value based on Key in Dictionary:
--------------------------------------------

contacts = {"Arun":"9933","Praba":"1233","Kana":"2345"}
>>> contacts["Arun"]="1111"
>>> contacts["Praba"]="2222"
>>> contacts["Kana"]="3333"
>>> contacts
{'Arun': '1111', 'Praba': '2222', 'Kana': '3333'}

Adding Items to a Dictionary
------------------------------
>>> contacts = {'David': '555-0123', 'Tom': '555-5678'}
>>> contacts['Nora'] = '555-2413'  // just add new item using unique key,value pair
>>> print(contacts)
{'David': '555-0123', 'Tom': '555-5678', 'Nora': '555-2413'}

Remove item in a Dictionary:
---------------------------
contacts = {'David': '555-0123', 'Tom': '555-5678'}
del contacts['David']
print(contacts)

values within a dictionary do not have to be of the same data type.

Key Lookup :
-----------
>>> if 'David' in contacts.keys(): print("Yes")

Value Lookup:
------------
>>> if ('555-5678' in contacts.values()): print("Yes")
...
Yes

Loop through iteration:
-----------------------
>>> contacts
{'David': '555-0123', 'Tom': '555-5678', 'Nora': '555-2413'}
>>> for contact in contacts: print(contact)
...
David
Tom
Nora

 Get Key and values while iteration:
 ----------------------------------
>>> for person, phone_number in contacts.items():
...  print('The number for {0} is {1}.'.format(person, phone_number))
...
The number for David is 555-0123.
The number for Tom is 555-5678.
The number for Nora is 555-2413.
Yes

Tuples:
---------
 tuple_name = (item_1, item_2, item_N)


 months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December')
 jan = months_of_the_year[0]
 print(jan)
 print()


 >>> for month in months_of_the_year:
...  print(month)
...
January
February
March
April
May
June
July
August
September
October
November
December

>>> months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June',
... 'July', 'August', 'September', 'October', 'November', 'December')
>>> print(months_of_the_year)
('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
>>> del months_of_the_year  /// delete it

 for month in months_of_the_year:
 print(month)

 print(month)



Python - Pluralsight:
---------------------
we can do :
web apps, desktop apps, do scientific computations, create scripts, AI, Home automation
Python Frameworks & libraries(Django for web dev),
TensorFlow for AI,
SciPy  for Scientific computations,
PyQt - Cross platform Desktop Apps

DataTypes : Int, Strings
Functions, Classes

Simple, Beautiful, Extremely Powerful language
Usage:
Console Applications, Scripts, Scientific Computations, Web back-ends,
desktop apps, home automations, machine learning / AI apps


Automate some boring tasks like parsing CSV files every 30 minutes / doing some regular server maintenance?
complex scientific computations, graphs
Cross-platform desktop application (native look & Feel for every OS)
Android
Web site back end - Django Python web framework
Is it Dog / cat / or something else the content of picture?
Use python with Excellent TensorFlow library (AI / machine learning)
Python & PyQt => Cross platform Desktop Apps
Django and Flask web apps
Home Automation with Python
Room Humidifier - Humidity sensor turn Rasperry Pi
So many Python Libraries

PEPS ===> Python Enhancement Proposals

PEP8 ==> To make readable code, guiding principle rule
2 empty lines before a new class declration
Function name should be all lower case with Underscores for spaces
No camelCase
No Opening and Closing Parenthesis { }

Python 2:
---------
print "Hello World"  -- statement

Python 3:
---------
print("Hello World")  -- function
New features being added
Unicode support
Released in December 2008.

Check the version:
-----------------
E:\NewTut\Pluralsight - python-getting-started\01.Introduction>python --version
Python 3.6.3

REPL - Read Evaluvate Print Loop
 - Similar to JavaScript console

Python Interpreter

Many Python IDEs come with integrated Python Console

Run the python program (filename.py) in console:
python3 hello.py
python hello.py

we can make one binary executable file and we can run it in any OS

Builtin Data Types:
------------------
Int, String, Boolean

Flow Control:
-------------
If

Loops:
------
for,while

Lists, Arrays,
Dictionaries:  (closely resemble json)

Exceptions

other data types
Sets,  Tuples, Complex


We don't have to declare variable in advance
-------------

Type declaration in C# , Java
int answer = 42;
String name = "Lorem";

Not necessary to declare the type in Python
anwer = 42
name = "Lorem"
variable = our own custom type too

Python simply doesn't have as many type as C# or Java
Don't have to deal with Longs, doubles, unsigned, signed integers, shorts etc.,

Dynamically typed language

Python 3.5 new feature helps you to add data types like below
def add_numbers(a:int, b:int) -> int:
return a+b



Integer:  (doesn't have decimal point)
answer = 42  (integer)
pi = 3.14159 (float)  unlimited precision support

answer = answer + pi ( don't worry)

Type conversion:  (Type Casting)
----------------
int(pi) == 3
float(answer) == 42.0

Complex Number Type is introduced in Python 3.0


Strings:
Text , Unicode text
Python 3 supports UniCode Text

All are same:
'Hello' == "Hello" == """Hello"""
singe, double, 3 times double quotes are same

comment:  """   """ <---- multi line comment
#  pound or hash or sharp symbol to identifiy a comment line. single line comment
"""
Hey
Nee
Romba
Alaga
Irukke
"""

Utility Methods in strings

"123".isdigit() == True    /// validation
"hello".isalpha() == True  /// validation
"hello".capitalize() == "Hello"
"hello".replace("e","a") == "hallo"

capitalize ==> Make the 1st character a Capital Letter

split a certain string into a list using a character you specify
"AAA,BBB,CCC,DDD".split(",") == ["AAA","BBB","CCC","DDD"]

csv, tab separated --- use split to make a list

string inputs:
-------------
name ="Raj"
machine ="HAL"

Result expected:
Nice To Meet You Raj!. I am HAL machine.

"Nice To Meet You {0}!. I am {1}".format(name,machine)
0,1 ==> Positions of arguments
0 => Name, 1 => Machine

Format function supports : Padding, printing class attributes

Python 3.6 Interpolation:
-------------------------
f"Nice to meet you {name}!. I am {machine}"
Prefix the whole string with the letter 'f' outside of the string iteself, in front of the string

r => raw string, Python doesn't automatically escape backslashes

String slicing


Boolean and None:
----------------
python_course = True
java_Course = False

Capitalized True, False not like true,false

int(python_course) == 1
int(java_Course) == 0
str(pythan_course) == "True"

None means NULL in other language

print("Hello World!")
aliens_found = None
print(aliens_found)

number = 5
if number == 5:
    print("Number is #5")
else:
    print("Numebr is NOT 5")

number = 5

if (number == 5):
    print("Number is #5")
else:
    print("Numebr is NOT 5")


Python uses indentation instead of curly phrases for any code block
it includes : loop, conditions, functions, classes

==   Equivality checking

is   to verify the two variables are pointing to same object in memory


truthy / falsy values:
----------------------

print("Hello World!")
aliens_found = None
print(aliens_found)

number = 5
if (number == 5):
    print("Number is #5")
else:
    print("Numebr is NOT 5")


if number:
    print ("Number is defined and truthy")

text="Python"
if text:
    print("Text is defined and truthy")




if number:
    print ("Number is defined and truthy")
else:
    print ("Number is defined and falsy")
text=""
if text:
    print("Text is defined and truthy")
else:
    print("Text is defined and falsy")



truthy means - Non Zero, Non empty


aliens_found = None
if not aliens_found:
    print("This will execute")

if number != 0:
    print ("This won't execute")

number = 3
python_course = True
if number == 3 and python_course:
    print ("This will execute")

number = 17
python_course = True
if number == 17 or python_course:
    print("This will execute")

and or not ==> all lower

Ternary If:  (? in the middle in other languages)
----------

a = 1
b = 2
"bigger" if a > b else "smaller"

a = 1
b = 33
print ("bigger") if a > b else print ("smaller")


Lists:
------
Instructor Name = "Scott Allen"
Student Names = list of students's names
 One Instructor with Many Students

 student_names = []  /// empty python list
 student_names =["Mark","Katarina","Jessica"] /// filled python list,,, zero based

 their own enclosing quotes and they're strings separated by comma.

in order to access an element in a list, we use index
index is an integer value starting from 0, which corresponds to one and just one element in the list

student_names [0] == "Mark"
student_names [1] == "Jessica"
student_names [-1] == "Jessica"  ===> Last element

names = ["Arun","Sanjana","Balaji","Murugan"]
print(names[0])
print(names[-1])
print(names[-2])

Changing / Modifying / altering data:
------------------------------------

names[3] = "Tamil God"
print(names[3])

Add new element:
---------------
names.append("Bravo")
print(names[4])

if "Bravo" in names:
    print ("Yes")

Total number of elements in the list:
print(len(names))

Total number of characters in a string:
print(len(names[0]))

names = ["Arun","Sanjana","Balaji","Murugan"]
if (len(names) == 4):  // total elements in the list
    print ("Yes")


Having multiple types in a single list is fine.

names = ["Arun","Sanjana","Balaji","Murugan"]
print(names) // before deleting
del names[0]  // delete the 1st
print(names)
names.append("Raja") // add at the last
print(names)



List slicing:
-------------
names = ["Arun","Sanjana","Balaji","Murugan"]
print(names[1:]) // ignore the 1st element till end
print(names[1:-1])  // ignore 1st and last elements

o/p:
['Sanjana', 'Balaji', 'Murugan']
['Sanjana', 'Balaji']


printing List Elements:
------------------------
names = ["Arun","Sanjana","Balaji","Murugan"]
print(names[0])
print(names[1])
print(names[2])
print(names[3])

o/p:
Arun
Sanjana
Balaji
Murugan

Loop:
------
names = ["Arun","Sanjana","Balaji","Murugan"]
for name in names:
    print(name);

Arun
Sanjana
Balaji
Murugan

names = ["Arun","Sanjana","Balaji","Murugan"]
for name in names:
    print("Student name is {}".format(name));
o/p:
Student name is Arun
Student name is Sanjana
Student name is Balaji
Student name is Murugan


Once all the names have been printed,
that is once all the list elements have been used,
the loop finishes

Other languages:
-----------------
for(var i=0: i < someArray.Length; i++)
{
var element = someArray[i];
console.log(element);
}

x = 0
for index in range(10):
    x += 10
    print (f"The value of X is {x}")


x = 0
for index in range(5,10):
    x += 10
    print(f"X is {x}")

names = ["Arun","Sanjana","Balaji","Murugan","Kalaignan","Kamal","Prabu"]
for name in names:
   if name == "Balaji":
       print (f"Found person : {name}")
   print(f'Currently testing : {name}');

O/p: (No break)
----
Currently testing : Arun
Currently testing : Sanjana
Found person : Balaji
Currently testing : Balaji
Currently testing : Murugan
Currently testing : Kalaignan
Currently testing : Kamal
Currently testing : Prabu



names = ["Arun","Sanjana","Balaji","Murugan","Kalaignan","Kamal","Prabu"]
for name in names:
    if name == "Balaji":
        print (f"Found person : {name}")
        break
    print(f'Currently testing : {name}');

Traverse until Balaji:
----------------------
Currently testing : Arun
Currently testing : Sanjana
Found person : Balaji

Everything below the continue wont executed  -- un reachable


continue example:
-----------------

names = ["Arun","Sanjana","Balaji","Murugan","Kalaignan","Kamal","Prabu"]
for name in names:
    if name == "Murugan":
        continue
        print (f"Found person : {name}")
    print(f'Currently testing : {name}');

Except Murugan:
---------------
Currently testing : Arun
Currently testing : Sanjana
Currently testing : Balaji
Currently testing : Kalaignan
Currently testing : Kamal
Currently testing : Prabu


While loop also has break and continue
Check for a condition before they even enter the loop
x = 0
while x < 10:
    print (f"Count is {x}")
    x += 1

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Count is 6
Count is 7
Count is 8
Count is 9


Dictionaries:
----------------

Allw to store key value pairs of any data
similar to JSON

Earlier List was having just names
if you want to add some more details u can go for Dictionaries

student = {
"name":"Mark",  // string
"student_id":100, //integer
"feedback":None  // NULL
}

name,student_id,feedback are Keys
"Mark", 100,None are values

Nested Dictionary:
A key can have the value of another dictionary

we can easily convert python Dictionary into JSON

List of Dictionaries:
--------------------
all_students = [
{"name":"Mark","student_id":100},
{"name":"Katarina","student_id":101},
{"name":"Jessica","student_id":102}
   ]
[ ] ==> list (square bracket)

student["name"] == "Mark"

student["last_name"] == KeyError

student.get("last_name","Unknown") == "Unknown"

student.keys() == ["name","student_id","feedback"]  // list of all the keys

student.values() = ["Mark",100,None] // list of all the values

Changing value:
--------------

student["name"] == "Harish Kalyan"

Delete the name key,value pair:
--------------------------------
del student["name"]

Add new item:
-------------
student["last_name"] = "Kowalski"

Exceptions:
Events that occur during your program's execution that normally cause your program to stop executing
Some error has encountered and that your program simply doesn't know how to deal with it

student("last_name") but there was no such key

There is a way for us to account for them and provide a graceful mechanism for handling those exceptions


student = {
    "name" : "Mark",
    "student_id" : 100,
    "feedback" : None
}

last_name = student["last_name"]

Traceback (most recent call last):
  File "C:/Users/Anbu/PycharmProjects/my1st/hello.py", line 7, in <module>
    last_name = student["last_name"]
KeyError: 'last_name'

Exception handling in python
try.. except blocks of code


student = {
    "name" : "Mark",
    "student_id" : 100,
    "feedback" : None
}

try:
    last_name = student["last_name"]  // to attempt and retrieve the last_name from the list
except KeyError:
    print("Error finding last_name")

    print("This code executes!")

o/p:
Error finding last_name
This code executes!



student = {
    "name" : "Mark",
    "student_id" : 100,
    "feedback" : None
}
student["last_name"] = "Kowalski"
try:
    last_name = student["last_name"]
    numbered_last_name = 3 + last_name
except KeyError:  // specific to KeyError
    print("Error finding last_name")
except TypeError as error:  // specific to TypeError
    print("I can't add these 2 together") // user message
    print(error)  // display the error message coming from python
    print("This code executes!")
except Exception:  /// generic and not specific to any exception
print("Unknown error")

//
I can't add these 2 together
unsupported operand type(s) for +: 'int' and 'str' // line number is not there
This code executes!
//

In order to trace the line # which causes the exception, we need to include Traceable package / module


long
bytes
bytearray

tuple = (1,2,"sare",True,None)
Immutable - we can't change the values

set, frozenset ==> unique objects
get rid of duplicate elements

set([3,2,3,3,1,1,5,5,5,5]) == (1,2,3,5)

removed all duplicates and ordered them too


print("Hello World!")

a =10
b=20
print(f"{a} + {b} = {a+b}")

#comment single line
'''
comment
multi
line
'''


a,b=33,1
if (a < b):
    print('a ({0}) is less than b ({1})'.format(a,b))
else:
    print('a ({0}) is not less than b ({1})'.format(a,b))


//////  print (a < b ? "foo" : "bar")

Ternary:
a=10
b=53
print("True" if (a<b) else "False")


While Loop:
Fibonacci series:
-----------------

a,b=0,1
while (b < 50):
    print (b)
    a,b=b,a+b

2
3
5
8
13
21
34

a,b=0,1
while (b < 50):
    print (b)
    a,b=b,a+b
print("Done")

1
1
2
3
5
8
13
21
34
Done


a,b=0,1
while (b < 50):
    print (b)
    a,b=b,a+b
    print("Done")  /// it is part of the while loop

1
Done
1
Done
2
Done
3
Done
5
Done
8
Done
13
Done
21
Done
34
Done

Reading file contents and display lines one by one:
--------------------------------------------------

fh = open("C:\\Users\\Anbu\\PycharmProjects\\my1st\\lines.txt")
for line in fh.readlines():
    print(line)

Arun kumar is not going to school today.

Priya is going to market this evening.

Who is going to buy vegetables for me?

I am not going to eat mango today.


fh = open("lines.txt")
for line in fh.readlines():
    print(line)

fh = open("lines.txt")
for line in fh.readlines():
    print(line,end='')  /// No newline will be added


UDF : User Defined Functions

def OddOrEven(n):
    if (n % 2 == 0):
        print (f"{n} is Even")
    else:
        print (f"{n} is Odd")

for n in range(1,21):
    OddOrEven(n)

 
1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
7 is Odd
8 is Even
9 is Odd
10 is Even
11 is Odd
12 is Even
13 is Odd
14 is Even
15 is Odd
16 is Even
17 is Odd
18 is Even
19 is Odd
20 is Even

Prime Number or not:
--------------------
def isPrime(n):
    if (n == 1):
        print ("1 is special")
        return False

    for x in range(2,n):
        if (n % x == 0):
            print (f"{n} equals {x} x  {n // x}")
            return False
    else:
            print(f"{n} is a prime number")
            return True

for n in range(1,20):
    isPrime(n)


1 is special
2 is a prime number
3 is a prime number
4 equals 2 x  2
5 is a prime number
6 equals 2 x  3
7 is a prime number
8 equals 2 x  4
9 equals 3 x  3
10 equals 2 x  5
11 is a prime number
12 equals 2 x  6
13 is a prime number
14 equals 2 x  7
15 equals 3 x  5
16 equals 2 x  8
17 is a prime number
18 equals 2 x  9
19 is a prime number


Generator function:
------------------
def isPrime(n):
    if (n == 1):
        return False

    for x in range(2,n):
        if (n % x == 0):
            return False
        else:
            return True

def primes(n = 1):
    while (True):
        if isPrime(n) : yield n
        n += 1

for n in primes():
    if (n > 100): break
    print(n)


3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99


Object Oriented Programming:
---------------------------
class Fibonacci():
    def __init__(self,a,b):
        self.a = a
        self.b = b

    def series(self):
        while (True):
            yield(self.b)
            self.a,self.b = self.b,self.a+self.b

f = Fibonacci(0,1)
for r in f.series():
    if (r > 100): break
    print (r,end=" ")

1 1 2 3 5 8 13 21 34 55 89


def __init__  ===> constructor
self ===> this
yield ==> return value

dot notation

class Arithmetic():
    def __init__(self,a,b):
        self.a = a
        self.b = b

    def addition(self):
        return(self.a+ self.b)

    def subtraction(self):
        return(self.a - self.b)

    def multiplication(self):
        return(self.a * self.b)

    def division(self):
        return(self.a / self.b)

calc = Arithmetic(5,10)

addresult = calc.addition()
print(f"Addition result {addresult}")

subtractionresult  = calc.subtraction()
print(f"Subtraction result {subtractionresult}")

print(f"Multiplication result {calc.multiplication()}")
print(f"Division result : {calc.division()}")

Addition result 15
Subtraction result -5
Multiplication result 50
Division result : 0.5



fh = open("lines1.txt")
for line in fh.readlines():
    print(line)

Traceback (most recent call last):
  File "C:/Users/Anbu/PycharmProjects/my1st/hello.py", line 1, in <module>
    fh = open("lines1.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'lines1.txt'


fh = open("lines.txt")
for line in fh.readlines():
    print(line)


try:
    fh = open("lines1.txt")
    for line in fh.readlines():
        print(line)
except:
    print("Something bad happend")

Result:
Something bad happend


try:
    fh = open("lines1.txt")
    for line in fh.readlines():
        print(line)
except IOError as e:
    print(f"Something bad happend {e}")
 
print ("After bad")

Result:
-------
Something bad happend [Errno 2] No such file or directory: 'lines1.txt'
After bad

Function defined initially and then called later - allowed
----------------------------------------------------------

def egg():
    print ("egg")

print("first line")
egg()


result:
first line
egg


Function called initially and defined later on - not allowed:
--------------------------------------------------------------

print("first line")
egg()

def egg():
    print ("egg")



def main():
    print("first line")
    egg()

def egg():
    print ("egg")

if __name__ == "__main__": main()

first line
egg



def superstar():
    print("Awesome - 1st line")


if __name__ == "__main__":superstar()


# single line comment
def superstar():  # single line comment

'''
multi
line
comment
'''



def superstar():
    a = 7
    print(type(a),a)
    b="super"
    print(type(b),b)

if __name__ == "__main__":superstar()

Result:
<class 'int'> 7
<class 'str'> super


def superstar():
    a = 7
    b,c=10,"sare"
    d=e=1000
    print(a)
    print(b)
    print(c)
    print(d)
    print(e)
if __name__ == "__main__":superstar()

7
10
sare
1000
1000


a= 5
b = 10 but we are going to swap them
def superstar():
    a,b = 5,10
    a,b = b,a
    print (f"a is : {a}")
    print (f"b is : {b}")
if __name__ == "__main__":superstar()


a is : 10
b is : 5


type, tuple, list

def superstar():
    a = (1,"aha",3.3,True)
    print (type(a),a)

    b=  [1,"aha",3.3,True]
    print(type(b), b)
if __name__ == "__main__":superstar()

<class 'tuple'> (1, 'aha', 3.3, True)   --- ()  Tuple
<class 'list'> [1, 'aha', 3.3, True] ---- [] List


def main():
    a,b=1,5
    if (a < b):
        print(f"{a} is less than {b}")
    else:
        print(f"{a} is not less than {b}")

if __name__ == "__main__": main()

Result:
1 is less than 5



def main():
    a,b,c=1,2,3

    if (a>b and a>c):
        print (f"{a} is big")
    elif (b>c):
        print(f"{b} is big")
    else:
        print(f"{c} is big")

if __name__ == "__main__":main()

Result:
3 is big


def main():
    a,b=1,2

    s = "Less than" if (a < b ) else "Not Less Than"
    print(s)
if __name__ == "__main__":main()

Result:
Less than


def main():
    doIt()

def doIt():
        for i in range(10):  // 10 wont be included
            print (i,end=' ')
        print()
if __name__ == "__main__":main()

Result:
0 1 2 3 4 5 6 7 8 9


def main():
    for i in range(11):
        doIt();
def doIt():
        for i in range(10):
            print (i,end=' ')
        print()
if __name__ == "__main__":main()

Result:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9


Function with Arguments:
-----------------------
def main():
    for i in range(11):
        doIt(i);
def doIt(a):
        for i in range(a,10):
            print (i,end=' ')
        print()
if __name__ == "__main__":main()


Result:
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9


class Egg:
    def __init__(self,kind="Fried"):
        self.kind = kind

    def whatKind(self):
        return self.kind


fried = Egg()
print(fried.whatKind())
scrambled=Egg("Scrambled")
print (scrambled.whatKind())


Result:
Fried
Scrambled


class Egg:
    def __init__(self,kind="Fried"):
        self.kind = kind

    def whatKind(self):
        return self.kind

def main():
    fried = Egg()
    print(fried.whatKind())
    scrambled=Egg("Scrambled")
    print (scrambled.whatKind())

if __name__ == "__main__":main()

Result:
Fried
Scrambled

Everything in Python is an object
Variables, functions, Even code - everything in python is an object

Every object has an ID, Type and Value
ID - Uniquely identifies a particular instance of an object
Cannot change for the life of the object
Type identifies the class of an object
Cannot change for the life of the object
Value is the contents of the object
Mutable object can change the value, Immutable objects cannot

>>> x=42   ----------------> check here same id for same values after changes
>>> id(x)
1816254912
>>> x=43
>>> id(x)
1816254928
>>> x=42  ---------------->
>>> id(x)
1816254912
>>> x=43
>>> id(x)
1816254928
>>> type(x)
<class 'int'>


Most fundamental types in Python are immutable
numbers,strings,tuples

Mutable objects include:
lists, dictionaries, other objects depending upon implementation

def main():
   num = 42
   print(type(num),num)

   num = 42.0
   print(type(num),num)

if __name__ == "__main__":main()

Result:
<class 'int'> 42
<class 'float'> 42.0

>>> 42/9
4.666666666666667
>>> 42/9.0
4.666666666666667
>>> 42 // 9
4


// means result will be rounded off

>>> round(42 /9, 2)
4.67
>>> round(42/9)
5

>>> 42 % 9
6

>>> float(42)
42.0


Mutable objects may change value, immutable objects may not
Distinction is visible using id()


Strings in Python are immutable
Enclosed with Single / Double Quotes


def main():
   s = "This is a String"
   print (s)
   s = "This is \n a string"   ===> Escape to next line
   print (s)
   s = r"This is a \n string"   ===> raw string
   print(s)

if __name__ == "__main__":main()

This is a String
This is
 a string
This is a \n strin

String Format:
-------------

def main():
   n = 42
   s = "This is a {} string!".format(n)
   print (s)

if __name__ == "__main__":main()

Result:
------
This is a 42 string!


def main():
   n = 42
   s = f"This is a {n} string!"
   print (s)

if __name__ == "__main__":main()

Result:
-------
This is a 42 string!



def main():
  s = """\
  I love all beautious things
  God #1
  God #2
  Finally
  reached
  destination...
  """
  print(s)
if __name__ == "__main__":main()

Result:
-------
 I love all beautious things
  God #1
  God #2
  Finally
  reached
  destination...



def main():
  s = '''\
  I love all beautious things
  God #1
  God #2
  Finally
  reached
  destination...
'''
  print(s)
if __name__ == "__main__":main()


Tuple is


def main():
 x = (1,2,3)
 print(x)
 print(type(x),x)
if __name__ == "__main__":main()

Result:
(1, 2, 3)
<class 'tuple'> (1, 2, 3)


def main():
   x = [1,"sare",True,2.3]
   x.append(5)
   x.insert(2,5)
   print(x)
if __name__ == "__main__":main()


Result:
[1, 'sare', 5, True, 2.3, 5]


def main():
  x = "mynameis"
  print(x[2])
if __name__ == "__main__":main()

Result:
n


Immutable Tuple ( )  not changeable
Mutable List [ ]  changeable

def main():
  x = (1,2,3,4,5)
  for i in x:
   print(i,end=" ")
if __name__ == "__main__":main()

Result :
---------
1 2 3 4 5

def main():
  x = "I love India"
  for i in x:
   print(i,end=" ")
if __name__ == "__main__":main()


Result:
I   l o v e   I n d i a

String is a mutable Sequence

[] -- list
() -- Tuple
{} -- Dictionary

Dictionaries:
---------------
def main():
  d = {"one":1,"two":2,"three":3,"four":4,"five":5}
  print(type(d),d)
  for k in d:
      print (k, d[k])   // d[k] subscript
if __name__ == "__main__":main()

// k ---> keys
// d[k] --> subscripted value

Result:
--------
<class 'dict'> {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
one 1
two 2
three 3
four 4
five 5

def main():
  d = {"one":1,"two":2,"three":3,"four":4,"five":5}
  print(type(d),d)
  for k in sorted(d.keys()):
      print (k, d[k])
if __name__ == "__main__":main()

A-Z Ordered values:
------------------
def main():
  d = {"one":1,"two":2,"three":3,"four":4,"five":5}
  print(type(d),d)
  for k in sorted(d.keys()):
      print (k, d[k])
if __name__ == "__main__":main()

Result:
----------
five 5
four 4
one 1
three 3
two 2

Dictionary Constructor
---------------------

def main():
  d = dict(one=1,two=2,three=3,four=4,five="five")  // no need to use quotes in keys
  print(type(d),d)
  for k in sorted(d.keys()):
      print (k, d[k])
if __name__ == "__main__":main()


Result:
five five
four 4
one 1
three 3
two 2

Dictionaries are mutable objects
I can add new values

def main():
  d = dict(one=1,two=2,three=3,four=4,five="five")
  d["Seven"]=7
  for k in sorted(d.keys()):
      print (k, d[k])
if __name__ == "__main__":main()

Result:
Seven 7
five five
four 4
one 1
three 3
two 2


In Python 3 everything is an object
An object has identity
Identity of an object is unique id - unique number is specific to the object

id is the function to find the id of an object

def main():
 x = 42
 print(id(x),x,type(x))
 y=42
 print(id(y),y,type(y))
if __name__ == "__main__":main()

Result:
see here ids are same:
1825626560 42 <class 'int'>
1825626560 42 <class 'int'>


def main():
 x=dict(x=42)
 y=dict(x=42)
 print(x,type(x),id(x))
 print(y, type(y), id(y))

 print(x == y)  // values are same
 print(x is y)  // ids are different


if __name__ == "__main__":main()

Result:
see here ids are different...
{'x': 42} <class 'dict'> 59829104
{'x': 42} <class 'dict'> 59829440
True
False

True and False  Boolean
----------------------
def main():
 a,b=0,1
 print(a==b)
 print(a < b)
 a = True
 print(a)
 print(type(a))
 print(id(a),id(b))
 print(id(True),id(False))
if __name__ == "__main__":main()

Result:
False
True
True
<class 'bool'>
1825443728 1825625904
1825443728 1825443744

Conditional if..else
-------------------

def main():
 a,b=0,1
 if (a < b):
     print("This is true")
 else:
     print("It is not true")

if (True):
    print("I like it")
else:
    print("I don't like it")

if __name__ == "__main__":main()


Result:
--------
I like it
This is true


elif
----

def main():
    v = 'seven'
    if (v == 'one'):
        print ('v is one')
    elif (v == 'two'):
        print("v is two")
    elif (v == 'three'):
        print ('v is three')
    else:
        print ('v is some other thing')

if __name__ == "__main__":main()

Result:
v is some other thing


Python doesn't have Switch Case.

def main():
   choices = dict(
       one="First",
       two="Second",
       three="Third",
       four="Fourth",
       five="Fifth"
   )
   v = "seven"
   print(choices.get(v,"Other"))

if __name__ == "__main__":main()

Result:
Other

Conditional Expressions:
------------------------

def main():
    a,b=0,1

    if (a < b):
        v = "This is True"
    else:
        v = "This is not true"
    print(v)
if __name__ == "__main__":main()


def main():
    a,b=0,1
    v = "This is True" if (a < b) else "This is not true"
    print(v)
if __name__ == "__main__":main()

Result:
This is True

While Loop:
-----------
def main():
   a,b=0,1
   while b < 150:
       print(b,end=" ")
       a,b=b,a+b
if __name__ == "__main__":main()

Result:
1 1 2 3 5 8 13 21 34 55 89 144


For Example:
-----------
def main():
    fh = open("lines.txt")
    for line in fh.readlines():
        print(line,end='')
if __name__ == "__main__":main()

Result:
Arun kumar is not going to school today.
Priya is going to market this evening.
Who is going to buy vegetables for me?
I am not going to eat mango today.
Who wants Apple?

def main():
    for n in [1,2,3,4,5]:
        print(n,end=" ")
if __name__ == "__main__":main()

Result:
1 2 3 4 5

def main():
    for n in "Arun Sanjana":
        print(n,end=" ")
if __name__ == "__main__":main()

Result:
A r u n   S a n j a n a

Enumeration:
-----------
def main():
    for index, x  in enumerate("Arun Sanjana"):
        print(index,x,end="\t")
if __name__ == "__main__":main()

Result:
------
0 A 1 r 2 u 3 n 4   5 S 6 a 7 n 8 j 9 a 10 n 11 a


def main():
    for index, c  in enumerate("arun sanjana"):
        if (c =='a'): print("index {} is an s".format(index))
if __name__ == "__main__":main()

Result:
index 0 is an s
index 6 is an s
index 9 is an s
index 11 is an s


Loop control -  continue
----------------------------------
def main():
    s = "this is a string"
    for c in s:
        if c == 's': continue
        print (c,end='')
if __name__ == "__main__":main()

Result:
thi i a tring  :: Ignored / skipped all s

Loop control - break (terminate the loop)
---------------------
def main():
    s = "this is a string"
    for c in s:
        if c == 's': break
        print (c,end='')
if __name__ == "__main__":main()

Result:
-------
thi


else in for  : when the for completes and nothing to do further, then else part will run
------------

def main():
    s = "this is a string"
    for c in s:
       print (c,end=' ')
    else:
        print(' completed')
if __name__ == "__main__":main()

Result:
t h i s   i s   a   s t r i n g  completed

else in while:
-------------
def main():
    s = "this is a string"
    i = 0
    while (i < len(s)):
        print(s[i], end='')
        i += 1
    else:
        print(' completed')
if __name__ == "__main__":main()


decimal to binary conversion using udf:
---------------------------------------
>>> def b(n): print("{:08b}".format(n))
...
>>> b(5)
00000101
>>> b(10)
00001010


>>> type(True)
<class 'bool'>
>>> a = True
>>> print(a,type(a),id(a))
True <class 'bool'> 1930760080



def main():
   list= [1,2,3,4,5,6,7,8,9,10]
   print(list[0])
   print(list[1])
   print(list[0:5])
   for i in [1,2,3,4,5,6,7,8,0,10] : print(i,end=' ')
   print(range(0,10))
   for i in range(0,10) : print (i,end=' ')
if __name__ == "__main__":main()

Result:
1
2
[1, 2, 3, 4, 5]
1 2 3 4 5 6 7 8 0 10 range(0, 10)
0 1 2 3 4 5 6 7 8 9

>>> list=[1,2,3,4,5,6,7,8,9,10]
>>> list[0:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list[:] = range(100)
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>>

slice the list
>>> list[27:42]
[27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41]

>>> list[27:43:3] = (99,99,99,99,99,99)
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 99, 28, 29, 99, 31, 32, 99, 34, 35, 99, 37, 38, 99, 40, 41, 99, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

>>> for i in list[27:43:3]: print(i)
...
99
99
99
99
99
99

change the list element value:
list[3] = 5
list[3] = 55

Regular Expression:
-------------------

 import re
def main():
   fh = open("raven.txt")
   for line in fh:
      if (re.search("(Len|Neverm)ore",line)):
         print (line,end=" ")

if __name__=="__main__": main()


Result:
Wherever we have Lenore or Nevermore, just print that line

import re
def main():
   fh = open("raven.txt")
   for line in fh:
      match = re.search('(Len|Neverm)ore',line)
      if match:
         print (match.group())

if __name__=="__main__": main()



Search and Replace a string using re:
-----------------------------------
import re
def main():
   fh = open("raven.txt")
   for line in fh:
     print(re.sub('(Len|Neverm)ore','$$$$$$$',line),end=' ')

if __name__=="__main__": main()


import re
def main():
   fh = open("raven.txt")
   for line in fh:
      match = re.search('(Len|Neverm)ore',line)
      if match:
          print(line.replace(match.group(),'###'),end='')

if __name__=="__main__": main()


Pre compiling regular expression:
---------------------------------
import re
def main():
   fh = open("raven.txt")
   pattern = re.compile('(Len|Neverm)ore')
   for line in fh:
      if re.search(pattern,line):
          print(line,end='')

if __name__=="__main__": main()


Read lines from file (before applying exception handling):
---------------------
import re
def main():
   fh = open("xlines.txt")
   for line in fh:
      print(line.strip())


if __name__=="__main__": main()



Exception handled here (which handles all):
-------------------------------------------
import re
def main():
   try:
      fh = open("xlines.txt")
   except:
      print("Could not open the file. come back tomorrow")
   else:
      for line in fh:
         print(line.strip())


if __name__=="__main__": main()


Handling specific exception:
----------------------------
import re
def main():
   try:
      fh = open("xlines.txt")
   except IOError as e:
      print(f"Could not open the file. come back tomorrow : {e}")
   else:
      for line in fh:
         print(line.strip())


if __name__=="__main__": main()



Open file with function exa:
-----------------------------
import re
def main():
  for line in readfile("lines.txt"):
     print(line.strip())

def readfile(filename):
   fh = open(filename)
   return fh.readlines()


if __name__=="__main__": main()


Specific handling:
------------------
import re
def main():
   try:
      for line in readfile("xlines.txt"):
        print(line.strip())
   except IOError as e:
      print(f"Cannot read file: {e}")

def readfile(filename):
   fh = open(filename)
   return fh.readlines()


if __name__=="__main__": main()


User Raised Exception:
---------------------
import re
def main():
   try:
      for line in readfile("lines.taxt"):
        print(line.strip())
   except IOError as e:
      print(f"Cannot read file: {e}")
   except ValueError as e:
      print(f"{e}")

def readfile(filename):
   if filename.endswith(".txt"):
      fh = open(filename)
      return fh.readlines()
   else:
      raise ValueError("Filename must end with .txt")


if __name__=="__main__": main()


Result:
Filename must end with .txt


function Example:
-*-----------------
import re
def main():
    testfunc()

def testfunc():
   print ("This is a function")


if __name__=="__main__": main()


Function with arguments:
-----------------------
import re
def main():
    testfunc(42)

def testfunc(number):
   print (f"This is a function : {number}")


if __name__=="__main__": main()


Function with multiple arguments:
----------------------------------
import re
def main():
    testfunc(42,43,75)

def testfunc(first,second,third):
   print (f"This is a function : {first},{second},{third}")


if __name__=="__main__": main()

Result:
This is a function : 42,43,75


Default values for function arguments:
--------------------------------------
import re
def main():
    testfunc(42,43,75)

def testfunc(first=3,second=4,third=5):
   print (f"This is a function : {first},{second},{third}")


if __name__=="__main__": main()

Result:
This is a function : 42,43,75


import re
def main():
    testfunc()

def testfunc(first=3,second=4,third=5):
   print (f"This is a function : {first},{second},{third}")


if __name__=="__main__": main()

Result:
This is a function : 3,4,5

None ==> NULL
-+-------------
import re
def main():
    testfunc(42)

def testfunc(first=3,second=None,third=5):
   if second is None:
      second = 112
   print (f"This is a function : {first},{second},{third}")


if __name__=="__main__": main()


Result:
This is a function : 42,112,5


args
-------
import re
def main():
    testfunc(1,2,3,42,43,44,45,46)

def testfunc(this,that,other,*args):
   print(this,that,other,args)


if __name__=="__main__": main()

Result:
1 2 3 (42, 43, 44, 45, 46)
args ==> (42, 43, 44, 45, 46)


args loop through:
------------------
import re
def main():
    testfunc(1,2,3,42,43,44,45,46)

def testfunc(this,that,other,*args):
   print(this,that,other)
   for n in args:
       print(n,end =' ')

if __name__=="__main__": main()

Result:
--------
1 2 3
42 43 44 45 46



Keyword arguments:
--------------------
import re
def main():
    testfunc(one=11,two=12,three=13,four=14)

def testfunc(**kwargs):
   print("Keyword arguments",kwargs['one'],kwargs['two'],kwargs['three'],kwargs['four'])

if __name__=="__main__": main()

Result:
Keyword arguments 11 12 13 14


All together:
--------------
def main():
    testfunc(0,-1,-2,-3,1,2,3,4,one=11,two=12,three=13,four=14)

def testfunc(this,that,other,*args,**kwargs):
    print("Regular Arguments",this,that,other)
    print("Tuple Argument",args)
    print("Keyword arguments : ",kwargs['one'],kwargs['two'],kwargs['three'],kwargs['four'])
if __name__=="__main__": main()

Result:
Regular Arguments 0 -1 -2
Tuple Argument (-3, 1, 2, 3, 4)
Keyword arguments :  11 12 13 14

Keyword arguments loop through:
----------------------------------
def main():
    testfunc(one=11,two=12,three=13,four=14)

def testfunc(**kwargs):
    for k in kwargs:
        print(k,kwargs[k])
if __name__=="__main__": main()


Result:
one 11
two 12
three 13
four 14

Function Return String:
----------------
def main():
    print(testfunc())  // calling

def testfunc(): // definition
    return "This is a test function!.."
if __name__=="__main__": main()


Result:
This is a test function!..

Function Return numeric:
-------------------------
def main():
    for n in testfunc():
print(n,end=" ")

def testfunc():
    return range(25)
if __name__=="__main__": main()

Result:
42

Function Returns a Range:
------------------------
def main():
    for n in testfunc():
        print(n,end=",")

def testfunc():
    return range(25)
if __name__=="__main__": main()


Result:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,

Class Exa:
---------class Duck:
    def quack(self):
        print("Quackkkk!")
    def walk(self):
        print("Walks like a Duck!")

def main():
    donald = Duck()
    donald.quack()
    donald.walk()

if __name__=="__main__": main()

Result:
Quackkkk!
Walks like a Duck!

Class with constructor:
-------------------------
class Duck:
    def __init__(self,value):
        print("Constructor")
        self._v = value

    def quack(self):
        print("Quackkkk!",self._v)
    def walk(self):
        print("Walks like a Duck!",self._v)

def main():
    donald = Duck(52)
    donald.quack()
    donald.walk()

if __name__=="__main__": main()

Result:
Constructor
Quackkkk! 52
Walks like a Duck! 52

Multiple instantiation of a class:
----------------------------------
class Duck:
    def __init__(self,value):
        print("Constructor")
        self._v = value

    def quack(self):
        print("Quackkkk!",self._v)
    def walk(self):
        print("Walks like a Duck!",self._v)

def main():
    donald = Duck(52)
    donald.quack()
    donald.walk()

    frank = Duck(151)
    frank.quack()
    frank.walk()

if __name__=="__main__": main()


Result:
Donald's
Constructor
Quackkkk! 52
Walks like a Duck! 52

Frank's
Constructor
Quackkkk! 151
Walks like a Duck! 151

Object Data:
-----------
class Duck:
    def __init__(self,color="white"):
        self._color=color

    def quack(self):
        print("Quackkkk!")
    def walk(self):
        print("Walks like a Duck!")

def main():
    donald = Duck()

    donald.quack()
    donald.walk()
    print(donald._color)
 
    frank = Duck()
    frank.quack()
    frank.walk()
    frank._color = "Orange"
    print(frank._color)
if __name__=="__main__": main()


Result:
--------
Quackkkk!
Walks like a Duck!
white
Quackkkk!
Walks like a Duck!
Orange

setter and getter (object data)
-------------------------------
class Duck:
    def __init__(self,color="white"):
        self._color=color

    def quack(self):
        print("Quackkkk!")
    def walk(self):
        print("Walks like a Duck!")

    def set_color(self,color):
        self._color = color

    def get_color(self):
        return self._color
def main():
    donald = Duck()
    donald.color = "Green"
    donald.quack()
    donald.walk()
    print(donald.get_color())


    frank = Duck()
    frank.set_color("Pink")
    frank.quack()
    frank.walk()
    print(frank.get_color())
if __name__=="__main__": main()



Result:
Quackkkk!
Walks like a Duck!
white
Quackkkk!
Walks like a Duck!
Pink

Keyword Arguments in constructor:
----------------------------------
class Duck:
    def __init__(self,**kwargs):
        self._color=kwargs.get('color','Green')

    def quack(self):
        print("Quackkkk!")
    def walk(self):
        print("Walks like a Duck!")

    def set_color(self,color):
        self._color = color

    def get_color(self):
        return self._color
def main():
    donald = Duck(color="Blue")
    donald.quack()
    donald.walk()
    print(donald.get_color())


    frank = Duck(color="Magenta")
    frank.quack()
    frank.walk()
    print(frank.get_color())
if __name__=="__main__": main()

Result:
--------
Quackkkk!
Walks like a Duck!
Blue
Quackkkk!
Walks like a Duck!
Magenta



Inheritance:
------------
class Animal:
    def talk(self):
        print("I have something to say!")

    def walk(self):
        print("Hey! I am walking here")

    def clothes(self):
        print("I have nice clothes")

class Duck(Animal):
    def quack(self):
        print("Quaack!")
    def walk(self):
        print("Walks like a Duck!")

def main():
    donald = Duck()
    donald.quack()
    donald.walk()
    donald.clothes()

if __name__=="__main__": main()


Result:
Quaack!
Walks like a Duck!
I have nice clothes


Super class : accessing base class method from child class
---------------------------------------------------------
class Animal:
    def talk(self):
        print("I have something to say!")

    def walk(self):
        print("Hey! I am walking here")

    def clothes(self):
        print("I have nice clothes")

class Duck(Animal):
    def quack(self):
        print("Quaack!")
    def walk(self):
        super().walk()  // calling super class method here
        print("Walks like a Duck!")

def main():
    donald = Duck()
    donald.quack()
    donald.walk()
    donald.clothes()

if __name__=="__main__": main()

Result:
-------
Quaack!
Hey! I am walking here
Walks like a Duck!
I have nice clothes


One more class:
--------------
class Animal:
    def talk(self):
        print("I have something to say!")

    def walk(self):
        print("Hey! I am walking here")

    def clothes(self):
        print("I have nice clothes")

class Duck(Animal):
    def quack(self):
        print("Quaack!")
    def walk(self):
        super().walk()
        print("Walks like a Duck!")

class Dog(Animal):
    def clothes(self):
        print("I've brown and white fur")


def main():
    donald = Duck()
    donald.quack()
    donald.walk()
    donald.clothes()

    fido = Dog()
    fido.walk()
    fido.clothes()

if __name__=="__main__": main()


Result:
--------
Quaack!
Hey! I am walking here
Walks like a Duck!
I have nice clothes
Hey! I am walking here
I've brown and white fur

class Duck:
    def quack(self):
        print("Quaaaack!")
    def walk(self):
        print("Walks like a duck!")

class Dog:
    def bark(self):
        print("Woof!")
    def fur(self):
        print("The dog has brown and white fur")

def main():
    donald = Duck()
    donald.quack()
    donald.walk()

    fido = Dog()
    fido.bark()
    fido.fur()

if __name__=="__main__": main()


Result:
-------
Quaaaack!
Walks like a duck!
Woof!
The dog has brown and white fur



class Duck:
    def quack(self):
        print("Quaaaack!")
    def walk(self):
        print("Walks like a duck!")
    def bark(self):
        print("The duck cannot bark")
    def fur(self):
        print("The duck has feathers")
class Dog:
    def bark(self):
        print("Woof!")
    def fur(self):
        print("The dog has brown and white fur")
    def walk(self):
        print("Walks like a dog")
    def quack(self):
        print("The Dog can't quack")

def main():
    donald = Duck()
    fido = Dog()

    for o in (donald,fido):
        o.quack()
        o.walk()
        o.bark()
        o.fur()

if __name__=="__main__": main()

Result:
-------
Quaaaack!
Walks like a duck!
The duck cannot bark
The duck has feathers
The Dog can't quack
Walks like a dog
Woof!
The dog has brown and white fur


class Duck:
    def quack(self):
        print("Quaaaack!")
    def walk(self):
        print("Walks like a duck!")
    def bark(self):
        print("The duck cannot bark")
    def fur(self):
        print("The duck has feathers")
class Dog:
    def bark(self):
        print("Woof!")
    def fur(self):
        print("The dog has brown and white fur")
    def walk(self):
        print("Walks like a dog")
    def quack(self):
        print("The Dog can't quack")

def main():
    donald = Duck()
    fido = Dog()

    in_the_forest(donald)
    in_the_pond(fido)



def in_the_forest(dog):  /// interface
    dog.bark()
    dog.walk()
    dog.fur()

def in_the_pond(duck):  //interface
    duck.quack()
    duck.walk()
    duck.fur()

if __name__=="__main__": main()

Result:
------
The duck cannot bark
Walks like a duck!
The duck has feathers
The Dog can't quack
Walks like a dog
The dog has brown and white fur

def main():
    o = range(25)
    for i in o:
        print(i,end=' ')
if __name__=="__main__": main()


Result:
-------
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

def main():
    o = range(0,25,2)
    for i in o:
        print(i,end=' ')
if __name__=="__main__": main()

Result:
0 2 4 6 8 10 12 14 16 18 20 22 24

def main():
    o = range(5,25,2)
    for i in o:
        print(i,end=' ')
if __name__=="__main__": main()

Result:
5 7 9 11 13 15 17 19 21 23


Generator Function:
-------------------
class inclusive_range:
    def __init__(self,*args):
        numargs = len(args)
        if numargs < 1:
            raise TypeError("Requires at least one argument")
        elif numargs == 1:
            self.stop = args[0]
            self.start = 0
            self.step = 1
        elif numargs == 2:
            (self.start,self.stop) = args
            self.step=1
        elif numargs == 3:
            (self.start,self.stop,self.step) = args
        else:
            raise TypeError("Expected at most 3 arguments, got {}",format(numargs))

    def __iter__(self):
        i = self.start
        while i <= self.stop:
            yield i
            i += self.step

def main():
    o = inclusive_range(25)
    for i in o:
        print(i,end=' ')
if __name__=="__main__": main()


Result:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

o = inclusive_range(5,100,12)

Result:
--------
5 17 29 41 53 65 77 89


class Duck:
    def __init__(self,**kwargs):
        self.properties = kwargs

    def get_properties(self):
        return self.properties

    def get_property(self,key):
        return self.properties.get(key,None)
 
    @property
    def Color(self):
        return self.properties.get('Color',None)

    @Color.setter
    def Color(self,c):
        self.properties['Color'] = c

    @Color.deleter
    def Color(self):
        del self.properties['Color']


def main():
    donald = Duck()
    donald.Color = 'Blue'
    print(donald.Color)

if __name__=="__main__": main()


Result:
Blue


>>> "This is a string".upper()
'THIS IS A STRING'
>>> "this is a STRING".lower()
'this is a string'
>>> a= "Hi"
>>> print(f"{a} all!")
Hi all!
>>> print("{} all".format(a))
Hi all

>>> "THIS IS A STRING".capitalize()
'This is a string'


>>> "is this a is".find('is')
0
>>> "this is a string".find("is")
2

>>> s = "This is a string"
>>> s.replace("This","That")
'That is a string'

// Remove leading and trailing spaces
>>> a = "     This is a string     "
>>> a.strip()
'This is a string'
// Strip only on right side
>>> a.rstrip()
'     This is a string'
// Strip only on left side
>>> a.lstrip()
'This is a string     '



>>> s1 = "This is a string\n"
>>> s1.rstrip("\n")
'This is a string'
>>> "Thisisastring".isalnum()
True
>>> "1234".isdigit()
True

>>> "  ".isprintable()  ---> alt 255
False
>>> " ".isprintable()
True


class Duck:
    a,b = 5,42
    print(a,b)
    print("This is {}, That is {}".format(a,b))

    s = "This is {}, That is {}"
    print(s.format(a,b))

    print(id(s))

    new = s.format(a,b)
    print(id(new))

//Dictionary
    d = dict(bob = a,fred=b)
    print("this is {bob}, that is {fred}".format(**d))
 

def main():
    print("All is well")
if __name__=="__main__": main()

Result:
--------
5 42
This is 5, That is 42
This is 5, That is 42
44362592
44362688
this is 5, that is 42
All is well


Split and Joins:
-----------------

>>> s = "This is a string of words"
>>> s.split()
['This', 'is', 'a', 'string', 'of', 'words']
>>> "This           is         a    string     of     words".split()  /// split ignores all the white spaces
['This', 'is', 'a', 'string', 'of', 'words']
>>>
>>> s = "This is a string of words"
>>> s.split('i')
['Th', 's ', 's a str', 'ng of words']


>>> words = s.split()
>>> words
['This', 'is', 'a', 'string', 'of', 'words']
>>> for w in words: print(w,end=' ')
...
This is a string of words >>>
>>> for w in words: print(w)
...
This
is
a
string
of
words
>>>



>>> s = "This is a string of words!"
>>> new = ":".join(words)
>>> new1 =",".join(words)
>>> new
'This:is:a:string:of:words'
>>> new1
'This,is,a,string,of,words'


Tuples are immutable

List are mutable

Tuple:
------
>>> t = 1,2,3,4,5
>>> t[0]
1
>>> t[4]
5
>>> t[-1
... ]
5
>>> len(t)
5
>>> min(t)
1
>>> max(t),min(t)
(5, 1)
>>> type(t)
<class 'tuple'>
>>> t=(1,)
>>> type(t)
<class 'tuple'>


>>> l = [1,2,3,4,5]
>>> type(l)
<class 'list'>
>>> l[0]
1
>>> l[-1]
5
>>> len(l)
5
>>> max(l),min(l)
(5, 1)
>>> t = tuple(range(25))
>>> t
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)
>>> t[5] = 34
Traceback (most recent call last):   // not changeable
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment



>>> x = list(range(25))
>>> x
[0, 1, 2, 3, 4, 5 , 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>> x[5] = 34  // changeable
>>> x
[0, 1, 2, 3, 4, 34, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>>



>>> t = tuple(range(25))
>>> t
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)
>>> type(t)
<class 'tuple'>
>>> 10 in t, 50 in t, 50 not in t
(True, False, True)

 >>> for i in t: print(i,end=' ')
...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 >>>


>>> x = list(range(20))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> 10 in x
True
>>> 20 in x
False
>>> 20 not in x
True
>>> 10 not in x
False
>>> for i in x: print(i)
...
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>>


>>> x = (1,2,3,4,5,6,7,8,9,10)
>>> x[10]=25
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> x = list(range(26))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
>>> x.append(100)
>>>
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 100]
>>> x[18] = 3333
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100]
>>>



>>> x.extend(range(33))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 11, 12, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>> x.count(5)
2


>>> x.insert(0,555)
>>> x
[555, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 11, 12, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>>


>>> x.remove(12)
>>> x.remove(12)
>>> x
[555, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 11, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>> del x[12]
>>> x
[555, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>> del x[0]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>>

>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 33, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
>>> x.pop()
32
>>> x.pop()
31
>>> x.pop()
30
>>> x.pop()
29
>>> x.pop()
28
>>> x.pop(0)
0
>>> x.pop(1)
2
>>> x.pop(2)
4
>>> x
[1, 3, 5, 6, 7, 8, 9, 33, 13, 14, 15, 16, 17, 3333, 19, 20, 21, 22, 23, 24, 25, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
>>>

Dictionaries:
------------

>>> d = {"one":1,"two":2,"three":3}
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d = dict(one = 1, two = 2, three = 3, four = 4)
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> type(d)
<class 'dict'>
>>>



Combining 2 dictionaries:
------------------------
>>> d = {"one":1,"two":2,"three":3}
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d = dict(one = 1, two = 2, three = 3, four = 4)
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> type(d)
<class 'dict'>
>>> x = dict (five=5, six=6,seven=7)
>>> y = dict(**d, **x)  // here we combine them using double asterisk
>>> y
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}
>>>


>>> 'four' in y, 'four' in x
(True, False)

>>> for k in y: print(k,end = ' ')
...
one two three four five six seven >>>

>>> for k,v in d.items(): print(k,v)
...
one 1
two 2
three 3
four 4
>>>

>>> d.get("three")
3
>>> d.get("twelve","Not Found")
'Not Found'


>>> x
{'five': 5, 'six': 6, 'seven': 7}
>>> del x["five"]

>>> x.pop("seven")
7
>>> x
{'six': 6}



def main():
    f = open("lines.txt","r")
    for line in f.readlines():
        words = line.split(' ')
        for word in words:
            print(word,end = '   ')


if __name__ == "__main__":main()

Result:
-------
Arun   kumar   is   not   going   to   school   today.
   Priya   is   going   to   market   this   evening.
   Who   is   going   to   buy   vegetables   for   me?
   I   am   not   going   to   eat   mango   today.
   Who   wants   Apple?


import sqlite3

def main():
   db = sqlite3.connect('test.db')
   db.execute("drop table if exists test")
   db.execute("create table test (t1 text, i1 int)")
   db.execute("insert into test(t1,i1) values(?,?)",('one',1))
   db.execute("insert into test(t1,i1) values(?,?)", ('two', 2))
   db.execute("insert into test(t1,i1) values(?,?)", ('three', 3))
   db.execute("insert into test(t1,i1) values(?,?)", ('four', 4))
   db.commit()
   cursor = db.execute("select * from test order by t1")
   for row in cursor:
       print(row)

if __name__ == "__main__":main()

Result:
('four', 4)
('one', 1)
('three', 3)
('two', 2)


import sqlite3

def main():
   db = sqlite3.connect('test.db')
   db.execute("drop table if exists test")
   db.execute("create table test (t1 text, i1 int)")
   db.execute("insert into test(t1,i1) values(?,?)",('one',1))
   db.execute("insert into test(t1,i1) values(?,?)", ('two', 2))
   db.execute("insert into test(t1,i1) values(?,?)", ('three', 3))
   db.execute("insert into test(t1,i1) values(?,?)", ('four', 4))
   db.commit()
   cursor = db.execute("select * from test order by i1")
   for row in cursor:
       print(row)

if __name__ == "__main__":main()


Result:
('one', 1)
('two', 2)
('three', 3)
('four', 4)

Row Object:
-----------
import sqlite3

def main():
   db = sqlite3.connect('test.db')
   db.row_factory = sqlite3.Row
   db.execute("drop table if exists test")
   db.execute("create table test (t1 text, i1 int)")
   db.execute("insert into test(t1,i1) values(?,?)",('one',1))
   db.execute("insert into test(t1,i1) values(?,?)", ('two', 2))
   db.execute("insert into test(t1,i1) values(?,?)", ('three', 3))
   db.execute("insert into test(t1,i1) values(?,?)", ('four', 4))
   db.commit()
   cursor = db.execute("select * from test order by i1")
   for row in cursor:
       print(dict(row))

if __name__ == "__main__":main()


Result:
--------
{'t1': 'one', 'i1': 1}
{'t1': 'two', 'i1': 2}
{'t1': 'three', 'i1': 3}
{'t1': 'four', 'i1': 4}



import sqlite3

def main():
   db = sqlite3.connect('test.db')
   db.row_factory = sqlite3.Row
   db.execute("drop table if exists test")
   db.execute("create table test (t1 text, i1 int)")
   db.execute("insert into test(t1,i1) values(?,?)",('one',1))
   db.execute("insert into test(t1,i1) values(?,?)", ('two', 2))
   db.execute("insert into test(t1,i1) values(?,?)", ('three', 3))
   db.execute("insert into test(t1,i1) values(?,?)", ('four', 4))
   db.commit()
   cursor = db.execute("select * from test order by i1")
   for row in cursor:
       print(row["t1"],row["i1"])

if __name__ == "__main__":main()

Result:
-------
one 1
two 2
three 3
four 4

CRUD:
------

import sqlite3

def insert(db,row):
   db.execute("insert into test (t1,i1) values(?,?)",(row['t1'],row['i1']))
   db.commit()

def retrieve(db,t1):
   cursor = db.execute("select * from test where t1 = ?",(t1,))
   return cursor.fetchone()

def update(db,row):
   db.execute("update test set i1 = ? where t1 = ?",(row['i1'],row['t1']))
   db.commit()

def delete(db,t1):
   db.execute("delete from test where t1 = ?",(t1,))
   db.commit()

def disp_rows(db):
   cursor = db.execute("select * from test order by t1")
   for row in cursor:
      print("{} : {}".format(row["t1"],row["i1"]))

def main():
   db = sqlite3.connect("test.db")
   db.row_factory = sqlite3.Row
   print("Create table test")
   db.execute("drop table if exists test")
   db.execute("create table test (t1 text, i1 int)")

   print("Insert Rows")
   insert(db, dict(t1="one",i1=1))
   insert(db, dict(t1="two", i1=2))
   insert(db, dict(t1="three", i1=3))
   insert(db, dict(t1="four", i1=4))
   insert(db, dict(t1="five", i1=5))

   disp_rows(db)

   print("Retrieve Rows")
   print(dict(retrieve(db,"one")),dict(retrieve(db,"two")))

   print("Update Rows")
   update(db,dict(t1 = "one",i1=101))
   update(db,dict(t1="three",i1=103))
   disp_rows(db)

   print("Delete Rows")
   delete(db,"one")
   delete (db,"three")
   disp_rows(db)

if __name__ == "__main__":main()


Result:
-------
Create table test
Insert Rows
five : 5
four : 4
one : 1
three : 3
two : 2
Retrieve Rows
{'t1': 'one', 'i1': 1} {'t1': 'two', 'i1': 2}
Update Rows
five : 5
four : 4
one : 101
three : 103
two : 2
Delete Rows
five : 5
four : 4
two : 2

Python Standard Libraries: (Python Packages import)
-------------------------
import sys
import os
import urllib.request

def main():
   print("Python Version {}.{}.{}".format(*sys.version_info))
   print("Platform {}".format(sys.platform))
   print("OS ",os.name)
   print("Path :",os.getenv("PATH"))
   print("Current Working Directory : ",os.getcwd())

if __name__ == "__main__":main()

Result:
Python Version 3.6.3
Platform win32
OS  nt
Path : C:\Python\Scripts\;C:\Python\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Spark\bin;C:\Program Files\Java\jdk1.8.0_151\bin;C:\Program Files\Java\jdk1.8.0_151\bin;C:\scala\bin;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Users\Anbu\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Users\Anbu\AppData\Local\Microsoft\WindowsApps;C:\Users\Anbu\AppData\Local\atom\bin;C:\Program Files\Microsoft VS Code\bin;C:\winutils\bin
Current Working Directory :  C:\Users\Anbu\PycharmProjects\my1st



Randomize:
------------
def main():
   import random
   print(random.randint(1,1000))
if __name__ == "__main__":main()

Result:
423


Shuffle:
-------
def main():
   import random
   x = list(range(26))
   print(x)
   random.shuffle(x)
   print(x)
if __name__ == "__main__":main()

Result:
-------
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[12, 10, 14, 20, 1, 17, 25, 15, 6, 19, 8, 2, 13, 3, 9, 18, 24, 4, 21, 0, 16, 7, 22, 5, 11, 23]


DateTime Example:
-----------------
def main():
 import datetime

 now = datetime.datetime.now()
 print(now)
 print(f"{now.year},{now.month}, {now.day}, {now.hour}, {now.minute}, {now.second}, {now.microsecond}")
if __name__ == "__main__":main()

Result:
2017-12-26 06:20:51.122249
2017,12, 26, 6, 20, 51, 122249



PyPi - Python Package Index

 http://pypi.python.org

 download a package from : https://pypi.python.org/pypi/bitstring

 bitstring-xxxxx.zip (md5) download the zip file

download and extract it into : c:\python\exercise

Run the following command:   python setup.py install within that folder where you extracted the .zip
C:\Python\exercise\bitstring-3.1.5>\python\python setup.py install

Result:
running install
running build
running build_py
creating build
creating build\lib
copying bitstring.py -> build\lib
running install_lib
copying build\lib\bitstring.py -> C:\python\Lib\site-packages
byte-compiling C:\python\Lib\site-packages\bitstring.py to bitstring.cpython-36.pyc
running install_egg_info
Writing C:\python\Lib\site-packages\bitstring-3.1.5-py3.6.egg-info


use bitstring in python program:

def main():
  import bitstring
  a = bitstring.BitString(bin = "1000")
  print(a.hex, a.bin, a.uint)
if __name__ == "__main__":main()

Result:
8 1000 8


Create, Read file
write json content to file
read json data from file
parse json

import json

def main():
  book = {}
  book["tom"] = {
    "name" : "tom",
    "address":"1 red street, NY",
    "phone":9119191
  }
  book["bob"] = {
    "name" :"bob",
    "address":"1 green street, NY",
    "phone" : 91919234
  }


  s = json.dumps(book)

  #print(str(s))

  with open("c://data/book.txt","w") as f:
    f.write(s)

  f = open("c://data/book.txt","r")
  s = f.read()
  #print(s)
  book = json.loads(s)
  #print(book)
  #print(book["bob"]["phone"])
  for person in book:
    print(book[person])
if __name__ == "__main__":main()


Result:
{'name': 'tom', 'address': '1 red street, NY', 'phone': 9119191}
{'name': 'bob', 'address': '1 green street, NY', 'phone': 91919234}




package:
mathop.py

#put all the functions here

def addition(a,b):
    return a+b

def subtraction(a,b):
    return a-b

def multiplication(a,b):
    return a*b

def division(a,b):
    return a/b

def power(a,b):
    return a**b


call package:

import mathop

def main():
    a = int(input("Enter first number"))
    b = int(input("Enter Second number"))

    add = mathop.addition(a,b)
    subtraction = mathop.subtraction(a,b)
    multiplication = mathop.multiplication(a,b)
    division = mathop.division(a,b)
    power = mathop.power(a,b)

    print(f"{a} + {b} = {add}")
    print(f"{a} - {b} = {subtraction}")
    print(f"{a} * {b} = {multiplication}")
    print(f"{a} / {b} = {division}")
    print(f"{a} ** {b} = {power}")
if __name__ == "__main__":main()


Result:
Enter first number 3
Enter Second number 3
3 + 3 = 6
3 - 3 = 0
3 * 3 = 9
3 / 3 = 1.0
3 ** 3 = 27

Exception Handling:
------------------
x=input("Enter number1: ")
y=input("Enter number2: ")
try:
    z = int(x) / int(y)
except ZeroDivisionError as e:
    print('Division by zero exception')
    z = None
except TypeError as e:
    print('Type error exception')
    z = None
print("Division is: ", z)


Result:
-------
Enter number1: 3
Enter number2: 0
Division by zero exception
Division is:  None


Class Example:
-------------
class Human:
    def __init__(self, n, o):
        self.name = n
        self.occupation = o

    def do_work(self):
        if self.occupation == "tennis player":
            print(self.name, "plays tennis")
        elif self.occupation == "actor":
            print(self.name, "shoots film")

    def speaks(self):
        print(self.name, "says how are you?")

def main():
    tom = Human("tom cruise","actor")
    tom.do_work()
    tom.speaks()

    maria = Human("maria sharapova","tennis player")
    maria.do_work()
    maria.speaks()

if __name__ == "__main__":main()

Result:
-------
tom cruise shoots film
tom cruise says how are you?
maria sharapova plays tennis
maria sharapova says how are you?


print(r"c:\bucky\desktop\nudepictures")  //  raw string

user="Tuna McFish"
print(user[0])

print(user[-1])

print(user[-3])

print(user[2:7)

print(user[:7)
beginning from zeroth place

print(user[2:)
till last character

print(len("Bucky Roberts"))



List:
--------
 players = [29,58,66,71,87]
 players[2] ==> 66

 players[2] = 68 // we are changing 66 to 68

 players.append(120)

 display:
players[:2] ==> [29,58]

 change:
players[:2] = [0,0]
players

[0,0,68,71,87,120]

remove 2 elements:
players[:2] = []

first 2 elements removed
[68,71,87,120]

age = 13
if age <= 21:
    print("No Beer For You!")


name  = "Lucy"
if name is "Bucky":
    print("Hey There Bucky!")
elif name is "Lucy":
    print("Whats aup Lucy!")
elif name is "Sammy":
    print("Hey! Dude Sammy!")

Result:
Whats aup Lucy!


name  = "Alfa"

if name is "Bucky":
    print("Hey There Bucky!")
elif name is "Lucy":
    print("Whats aup Lucy!")
elif name is "Sammy":
    print("Hey! Dude Sammy!")
else:
    print("Please Sign up for the site!")

Result:
Please Sign up for the site!



 For Loop:
 -------
foods = ["bacon","tuna","ham","beef","goat","lamb"]
for item in foods:
    print(item,len(item))

Result:
--------
bacon 5
tuna 4
ham 3
beef 4
goat 4
lamb 4

foods = ["bacon","tuna","ham","beef","goat","lamb"]
for item in foods[2:4]:
    print(item,len(item))

Result:
-------
ham 3
beef 4

foods = ["bacon","tuna","ham","beef","goat","lamb"]
for item in foods[:3]:
    print(item,len(item))

Result:
-------
bacon 5
tuna 4
ham 3


Range:
-----
for x in range(10):  // first number is 0 (zero) to 10 -1 (Nine)
    print("Bucky is Awesome : ",x)

Result:
-------
Bucky is Awesome :  0
Bucky is Awesome :  1
Bucky is Awesome :  2
Bucky is Awesome :  3
Bucky is Awesome :  4
Bucky is Awesome :  5
Bucky is Awesome :  6
Bucky is Awesome :  7
Bucky is Awesome :  8
Bucky is Awesome :  9


 for x in range(5,12): // first number is 5, last number is 12-1 (eleven)
    print(x)

Result:
5 6 7 8 9 10 11


 for x in range(10,100,8):  // first number is 10, last number is 100-8, increment factor is : 8
    print(x,end=" ")

Result:
10 18 26 34 42 50 58 66 74 82 90 98



x = 5
while (x <= 10):
    print(x,end=" ")
    x = x+1

Result:
5 6 7 8 9 10

break example:
-------------
magicNumber = 26
for n in range(100):
    if n is magicNumber:
        print(n , " is magic number")
        break
    else:
        print(n)

Result:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26  is magic number

 continue example:
 ---------------
// exclude the list values from the given range
numbersTaken = [2,5,12,13,17]
print("Here are the numbers that are still available")
for n in range(1,20):
    if n in numbersTaken:
        continue
    print(n,end=" ")

Result:
Here are the numbers that are still available
1 3 4 6 7 8 9 10 11 14 15 16 18 19


Functions  (No return):
------------

def beef():
    print("Dayam, Functions are cool!")

def bitcoin_to_usd(btc):
    print (btc * 527)

beef()
bitcoin_to_usd(1)
bitcoin_to_usd(23)
bitcoin_to_usd(132)


Result:
Dayam, Functions are cool!
527
12121
69564

Function with Return value:
---------------------------
def allowed_dating_age(my_age):
    girls_age = my_age / 2 + 7
    return girls_age

buckys_limit = allowed_dating_age(27)
creepy_joe_limit = allowed_dating_age(49)
print("Bucky can date girls ",buckys_limit, " or older")
print("Creepy Joe can date girls ",creepy_joe_limit, " or older")



Result:
Bucky can date girls  20.5  or older
Creepy Joe can date girls  31.5  or older


Default value for Function Argument:
-------------------------------------
def get_gender(sex = "Unknown"):
    if sex is 'm':
        sex='Male'
    elif sex is 'f':
        sex='Female'

    print(sex)

get_gender('m')
get_gender('f')
get_gender()


Result:
Male
Female
Unknown

Variable Scope:
-------------
a = 2333  // variable is defined and assigned above the function
  // it is accessible anywhere

def corn():
    print(a)

def fudge():
    print(a)

corn()
fudge()

Result:
2333
2333



def corn():
    a = 2333  // selfish.. it can be accessible within the function
    print(a)

def fudge():
    print(a)  // What????? I don't know the value of 'a'

corn()
fudge()

Result:
2333
Traceback (most recent call last):
  File "C:/Users/Anbu/PycharmProjects/my1st/hello.py", line 11, in <module>
    fudge()
  File "C:/Users/Anbu/PycharmProjects/my1st/hello.py", line 8, in fudge
    print(a)
NameError: name 'a' is not defined



named arguments and changing the order / position of arguments:
----------------------------------------------------------------
def dumb_sentence(name="Bucky",action="ate",item="tuna"):
    print(name,action,item)

dumb_sentence()
dumb_sentence("Sankara","studying","Python")

Result:
Bucky ate tuna
Sankara studying Python


Flexible Arguments - We don't know how many arguments we are going to pass
--------------------

def add_numbers(*args):
    sum = 0
    for item in args:
        sum += item
    print(sum)

add_numbers(1,2,3,4,5)
add_numbers(10,20,30)
add_numbers(1,10,2,20,3,30,4,40,5,50)

Result:
15
30
165

Unpacking Arguments:
---------------------
def health_calculator(age,apples_ate,cigs_smoked):
    answer = (100-age) + (apples_ate * 3.5) - (cigs_smoked * 2)
    print(answer)

buckys_data = [27,20,0]
health_calculator(buckys_data[0],buckys_data[1],buckys_data[2]) # difficult approach

health_calculator(*buckys_data) #easy way of unpacking arguments

Result:
143.0
143.0



groceries  = {"cereal","milk","starcrunch","beer","duct tape","lotion","beer"}
print(groceries)

if "milk" in groceries:
    print("You already have Milk!")
else:
    print("You need milk!")

Result:
-------
{'starcrunch', 'cereal', 'beer', 'duct tape', 'milk', 'lotion'}
You already have Milk!

Dictionaries:
--------------
classmates={"Tony":" cool but smells!", "Emma":" Sits behind me", "Lucy":" asks too many questions"}

for k,v in classmates.items():
    print(k+v)
Result:
-------
Tony cool but smells!
Emma Sits behind me
Lucy asks too many questions

Modules:
--------
File#1: tuna.py

def fish():
print("I am a tuna fish")

File#2 : hello.py

import tuna
tuna.fish()

Result:
I am a tuna fish



call builtin function / module:
------------------------------
import random  (using a package / module)
x = random.randrange(0,1000)
print(x)

Result:
622

Package Manager , Package Installation in PyCharm:
------------------------------------------------------------
(Similar to NPM, Nuget Package Manager)
File -> Settings -> Project:<name> ->
 -> Project Interpreter -> [ + ]
 -> search for Beautiful
 -> select Beautifulscraper
 -> Install Package

Download Image:
---------------

import random
import urllib.request

def download_web_image(url):
    name=random.randrange(1,1000)
    full_name=str(name) + ".jpg"
    urllib.request.urlretrieve(url,full_name)

download_web_image("http://tamilnenjam.com/wp-content/uploads/2016/03/cropped-tamilnenjam_logo-2.jpg")


Write into a file:
-----------------
fw = open("sample.txt","w")
fw.write("Line #1\n")
fw.write("Line #2\n")
fw.close()

fr = open("sample.txt","r")
text = fr.read()
print(text)
fr.close()

Result:
-------
Line #1
Line #2

download csv file from internet:
-------------------------------

from urllib import request

google_url="http://www.sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv"

def download_stock_data(csv_url):
    response = request.urlopen(csv_url)
    csv = response.read()
    csv_str = str(csv)
    lines = csv_str.split("\\n")
    dest_url = r"goog.csv"
    fx = open(dest_url,"w")
    for line in lines:
        fx.write(line + "\n")
    fx.close()

download_stock_data(google_url)


Exception : ValueError
---------------------
tuna = int(input("What's your fav number? \t"))
print(tuna)

Result:
What's your fav number?  3
3

What's your fav number?  sare
Traceback (most recent call last):
  File "C:/Users/Anbu/PycharmProjects/my1st/hello.py", line 1, in <module>
    tuna = int(input("What's your fav number? \t"))
ValueError: invalid literal for int() with base 10: 'sare'


Exception Handling:
---------------------
while True:
    try:
        number = int(input("What's your fav number?\t"))
        print(18/number)
        break
    except ValueError:
        print("Make Sure and enter a number.")


Result:
-------
What's your fav number? sare
Make Sure and enter a number.
What's your fav number? sarega
Make Sure and enter a number.
What's your fav number?
Make Sure and enter a number.
What's your fav number? 33
0.5454545454545454

while True:
    try:
        number = int(input("What's your fav number?\t"))
        print(18/number)
        break
    except ValueError:
        print("Make Sure and enter a number.")
    except ZeroDivisionError:
        print("Don't pick Zero")
    except:
        break
    finally:
        print("Aha")




Result:
What's your fav number? s
Make Sure and enter a number.
Aha
What's your fav number? 0
Don't pick Zero
Aha
What's your fav number? 3
6.0
Aha


class Enemy:
    life = 3

    def attack(self):
        print("Ouch!")
        self.life -= 1

    def checkLife(self):
        if self.life <= 0:
            print("I'm Dead!")
        else:
            print(str(self.life) + " life left..")

enemy1 = Enemy()
enemy2 = Enemy()

enemy1.checkLife()
enemy1.attack()
enemy1.attack()
enemy1.checkLife()
enemy1.attack()
enemy1.attack()

enemy1.checkLife()

enemy2.checkLife()

Result:
3 life left..
Ouch!
Ouch!
1 life left..
Ouch!
Ouch!
I'm Dead!
3 life left..

Constructor in classes
----------------------
class Tuna:
    def __init__(self):
        print("Blurp")

    def swim(self):
        print("I am swimming!")

flipper = Tuna() // constructor automatically called no explicit calling
clipper = Tuna()
flipper.swim() // regular function called and explicit calling




Result:
Blurp  // constructor automatically called no explicit calling
Blurp
I am swimming!


Constructor:
-----------
class Enemy:
    def __init__(self,energyLevel):
        self.energy  = energyLevel

    def get_energy(self):
        print(self.energy)

jason = Enemy(5)
sandy = Enemy(18)

jason.get_energy()
sandy.get_energy()

Result:
5
18

Difference between Class Variable vs instance variable:
-------------------------------------------------------
class Girl:
    gender="Female"

    def __init__(self,name):
        self.name = name

r = Girl("Rachel")
print(r.gender)
print(r.name)

s=Girl("Sara")
print(s.gender)
print(s.name)



Result:
Female
Rachel
Female
Sara


Inheritance:
-----------

class Parent():
    def print_last_name(self):
        print("Roberts")

class Child(Parent):
    def print_first_name(self):
        print("Bucky")

c = Child()
c.print_first_name()
c.print_last_name()

Result:
-------
Bucky
Roberts


Inheritance with Overriding in Child Class:
------------------------------------------
class Parent():
    def print_last_name(self):
        print("Roberts")

class Child(Parent):
    def print_first_name(self):
        print("Bucky")

    def print_last_name(self):
        print("Snitzleberg")
c = Child()
c.print_first_name()
c.print_last_name()


Result:
Bucky
Snitzleberg

Multiple inheritance:
---------------------
class Mario():
    def move(self):
        print("I am moving")

class Shroom():
    def eat_shroom(self):
        print("Now I am big")

class BigMario(Mario,Shroom):
    pass  #in order to avoid indentation error or whatever
  #nothing is in the body of the function

bm = BigMario()
bm.move()
bm.eat_shroom()


Result:
I am moving
Now I am big


Threading Example:
-------------------
import threading

class BuckysMessenger(threading.Thread):
    def run(self):
        for _ in range(10):   # I am not going to use counter variable anywhere. so instead of variable _ is enough
            print(threading.current_thread().getName())

x = BuckysMessenger(name="Sending...")
y = BuckysMessenger(name="Receiving...")

x.start()
y.start()

Result:
---------
Sending...
Sending...
Sending...
Receiving...
Sending...
Receiving...
Sending...
Receiving...
Receiving...
Receiving...
Receiving...
Receiving...
Sending...
Receiving...
Sending...
Receiving...
Sending...
Receiving...
Sending...
Sending...


List and Items Unpacking (V1.0)
------------------------
item = ["December 23,2017","Bread Gloves",8.51]

date = item[0]
name = item[1]
price = item[2]

print("Date : {}, Name : {}, Price : {}".format(date,name,price))

Result:
Date : December 23,2017, Name : Bread Gloves, Price : 8.51

V2.0
----
item = ["December 23,2017","Bread Gloves",8.51]

date,name,price = item

print("Date : {}, Name : {}, Price : {}".format(date,name,price))

Result:
------
Date : December 23,2017, Name : Bread Gloves, Price : 8.51

V3.0
-----
def drop_first_last(grades):
    first,*middle,last = grades
    avg = sum(middle)/len(middle)
    print("First : {},Middle : {}, Last : {}, Average : {}".format(first,middle,last,avg))

drop_first_last([1,2,3,4,5,6,7,8,9,10])
drop_first_last([100,80,30])

Result:
--------
First : 1,Middle : [2, 3, 4, 5, 6, 7, 8, 9], Last : 10, Average : 5.5
First : 100,Middle : [80], Last : 30, Average : 80.0


Zip lists to make easy retrieve:
-------------------------------
first = ["Bucky","Tom","Taylor"]
last = ["Roberts","Hanks","Swift"]

names=zip(first,last)
    #[("Bucky","Roberts"),("Tom","Hanks"),("Taylor","Swift")]
for f,l in names:
    print(f,l)

Result:
Bucky Roberts
Tom Hanks
Taylor Swift


Lambda Function:
-----------------
square = lambda x: x*x
print(square(5))


Result:
25


Max, Min, Sorted:
----------------
stocks = {
    "GOOG":520.54,
    "FB": 76.45,
    "YAHOO":39.28,
    "AMZN":306.21,
    "AAPL":99.76
}

result = zip(stocks.values(),stocks.keys())
print(max(result))
result = zip(stocks.values(),stocks.keys())
print(min(result))
result = zip(stocks.values(),stocks.keys())
print(sorted(result))

Result:
(520.54, 'GOOG')
(39.28, 'YAHOO')
[(39.28, 'YAHOO'), (76.45, 'FB'), (99.76, 'AAPL'), (306.21, 'AMZN'), (520.54, 'GOOG')]

Variable length arguments:
-------------------------
def func1(*mylist):
    for n in mylist:
        print(n,end=' ')
    print ("\n")

func1(1,2,3,4,5,6)
func1(2,3,4)
func1(1,-1,-2,-3)

Result:
-------
1 2 3 4 5 6

2 3 4

1 -1 -2 -3

abs(-5) ==> 5

Distance of the value from Zero in both -ve and +ve sides

>>> round(3.2374234234,3)
3.237

>>> import math
>>> math.e
2.718281828459045
>>> math.exp(4)
54.598150033144236
>>> math.exp(0)
1.0
>>> math.exp(0)
1.0
>>> math.e**4
54.59815003314423

>>> math.sqrt(8)
2.8284271247461903
>>> math.sqrt(81)
9.0

>>> x = max(x for x in range(100))
>>> x
99

>>> x = min(x for x in range(100))
>>> x
0

>>> math.log(10)
2.302585092994046
>>> math.log10(10)
1.0

modf : separate fractional and integer parts
>>> math.modf(234.0899)
(0.08990000000000009, 234.0)


>>> math.pow(8,2)  ==> 8**2
64.0

>>> 8**2
64

>>> math.pi
3.141592653589793
>>> math.modf(math.pi)
(0.14159265358979312, 3.0)

Radians to Degree:
------------------
>>> math.degrees(math.pi)
180.0


Degrees to Radians:
-------------------
>>> math.radians(180)
3.141592653589793


print with alignment
--------------------
>>> print(format("sarega","<40"))
sarega
>>> print(format("sarega",">40"))
                                  sarega
>>> print(format("sarega","^40"))
                 sarega
< left alignment
> right alignment
^ center alignment

Capitalize:
-----------
>>> str1 = "amuls"
>>> print(str1.capitalize())
Amuls


>>> str1 = "amuls academy for free python course online"
>>> str1.capitalize()
'Amuls academy for free python course online'
>>>

Multiline text:
--------------
>>> str1 ="""enjoy the world
... with
... full of happiness"""
>>> str1
'enjoy the world\nwith \nfull of happiness'

>>> str1.count("n")
2

How many times 'n' repeated in str1

>>> str1.count("p")
2

EndsWith:
---------
>>> str1.endswith("ness")
True

StartsWith:
-----------
>>> str1.startswith("enj")
True

>>> len(str1)
39
>>> tuple1 = (1,2,3,4,"sare",323.34)
>>> len(tuple1)
6
>>> list1=[1,2,3,"sare",32.23,34234,234,"amuls"]
>>> len(list1)
8

Positions of "j"
----------------
>>> str1.find("j")
2

split the given string with space delimiter (default)
-----------------------------------------------------
>>> split1 = str1.split()
>>> split1
['enjoy', 'the', 'world', 'with', 'full', 'of', 'happiness']

>>> x = str1.split(";")
>>> x
['1', '2', '3', '4', '5', '6', '7', '8']

capitalize:
------------
capitalize only the first letter of a given string

title:
------
capitalize each words of a given string


>>> str1 ="""enjoy the world
... with full
... of happiness"""

>>> print(str1.title())
Result:
---------
Enjoy The World
With Full
Of Happiness


>>> print(str1.lower())
enjoy the world
with full
of happiness

>>> print(str1.upper())
ENJOY THE WORLD
WITH FULL
OF HAPPINESS

All the letters present in the string lower or upper?
>>> str = "HARI"
>>> print(str.islower())
False
>>> print(str.isupper())
True

>>> "HAri".isupper()
False
>>> "HAri".islower()
False

Replace part of string:
----------------------
str1 = "Enjoy The world with Full of Happiness"
>>> print(str1.replace("world","globe"))
Enjoy The globe with Full of Happiness

IsDigit
------- contains only digits

>>> print("234".isdigit())
True

>>> print("sarega234".isdigit())
False

IsAlpha
-------- contains only alphbet (space also excluded)
>>> print("234".isalpha())
False
>>> print("sare23".isalpha())
False
>>> print("234".isalpha())
False
>>> print("sare".isalpha())
True


strip - remove the specific characters
>>> str1 = "!!!!!!!!!!!!!!!Hello!!!!!!!!!!!!!!"
>>> print(str1.strip("!"))
Hello



Python Fundamentals
Beyond the Basics
Advanced

django Flask Pyramid

astropy
biopython
NumPy

Ansible
Boto3
Azure SDK for Python

Data Analysis
Visualization
Machine Learning

pandas
matplotlib
Bokeh
TensorFlow
SciKit

Quickly, Safely, Efficiently

REPL : Read Eval Print Loop

No comments:

Post a Comment

Flume - Simple Demo

// create a folder in hdfs : $ hdfs dfs -mkdir /user/flumeExa // Create a shell script which generates : Hadoop in real world <n>...