Saturday, June 22, 2019

python Object and Datastructure Basics-List Dictionaries and Methods Available,List Dictionaries and Methods Available

python Object and Datastructure Basics-List Dictionaries and Methods Available
l=[1,2,0,'abc']
l[1]
l[0]
l[3]
len(l)
type(l)
List concat:
l1=[1,2,66]
l=1+l1
l*2
[1, 2, 0, 'abc', 1, 2, 66, 1, 2, 0, 'abc', 1, 2, 66]
l[0]='changed'
['changed', 2, 0, 'abc', 1, 2, 66]
l[22]='new string'
print(l)
l.append('new element1')
l[4].lower()
l[4].capitalize()
l[:3]
['changed', 2, 0]
l[-2]
66
b=set(l)
print(b)
{0, 1, 2, 66, 'new element1', 'changed', 'abc'}
Searcing :
s='name'
l=['string','something.'name']
if s in l:
  print('its found')
else
  print('not found')
 
for x in l:
  if x==s:
    print('not found')
  esle:
    print('not found')

Nested list:
 l=[1,2,0,'string',[1,2,3]]
 l.extend([5,6,7])
 print(l)
 l.append([8,9,0])

 slice if nested list
 l[1][0]
type(l[1])

l=[1,2,3,4,4,5]
l.count(2)
l.index(1)
l.insert(0,'Starting')
print(l)
l.pop()
print(l)
l.pop(0)
l.remove(3)
print(l)
l.clear()
print(l)
import copy
new 1=copy.deepcopy(l)

Dictionary:
my_dict={'key1':'value'}
len(my_dict)
my_dict={'number':1,'string':'am a string'}
di=dict(x=5,x=6)
print(di)
my_dict['number']
my_dict['you']='some value'
my_dict.update(new_dict)
my_dict.items()
from collections import OrderedDict
dict=OrderedDict([])
my_dict.get('string','element is not present')
>>> my_dict.get('string','element is not present')
'am a string'
>>> my_dict.get('strings','element is not present')
'element is not present'

Python Object and Datastructure Basics:Tuples,Sets,Frozen sets,Comparision Operator:
Tuple is immutable
my_tuple=(1,2,'string')
my_tuple[2].upper()
print(my_tuple)
my_tuple[0]+2
my_tuple.index('string')
t=(1)  ====t(1,)-->it is called as tuple
type(t)
my_set=set()
my_set={'k1',1,1,1}
type(my_set)
set()-mutable
frozenset-immutable
frozenset
1<2 p="">String-immutable
list-mutable,It hold any type of object
dict-mutable,no slicing and indexing..we can use keys to grab the values
tuple is immutable
set()-mutable,duplicate removal
frozenset-immutable

Tuesday, June 4, 2019

MAC Shortcuts

KeyFunction
Command+ASelects all items in the active window (icon view), all items
in the column (column view), or all items in the list (cover flow
view)
Command+CCopies selected items
Command+DDuplicates the selected item(s)
Command+EEjects the selected volume
Command+FDisplays the Find dialog
Command+HHides All Finder windows
Command+IShows info for selected item or items
Command+JShows the view options for the active window
Command+KDisplays the Connect to Server dialog
Command+LCreates an alias for the selected item
Command+MMinimizes the active window
Command+NOpens a new Finder window
Command+OOpens (or launches) the selected item
Command+RShows the original for selected alias
Command+TAdds the selected item to the Sidebar
Command+VPastes items from the Clipboard
Command+WCloses the active window
Command+XCuts the selected items
Command+ZUndoes the last action (if possible)
Command+,Displays Finder Preferences
Command+1Shows the active window in icon mode
Command+2Shows the active window in list mode
Command+3Shows the active window in column mode
Command+4Shows the active window in cover flow mode
Command+[Moves back to the previous Finder location
Command+]Moves forward to the next Finder location
Command+DelMoves selected items to the Trash
Command+up-arrowShow enclosing folder
Command+`Cycles through windows
Command+?Displays the Mac OS X Help Viewer
Command+Shift+ATakes you to your Applications folder
Command+Shift+CTakes you to the top-level Computer location
Command+Shift+GTakes you to a folder that you specify
Command+Shift+HTakes you to your Home folder
Command+Shift+IConnects you to your iDisk
Command+Shift+QLogs you out
Command+Shift+NCreates a new untitled folder in the active window
Command+Shift+UTakes you to your Utilities folder
Command+Shift+DelDeletes the contents of the Trash
Command+Option+HHides all windows except the Finder’s window(s)
Command+Option+NCreates a new Smart Folder
Command+Option+THides the Finder window toolbar
Command+Option+SpaceOpens the Spotlight window
Command+SpaceOpens the Spotlight menu
F8Choose another desktop using Spaces
Control+up-arrow (or F3, depending on your keyboard model)Displays the Mission Control screen
Control+down-arrow (or Control+F3, depending on your keyboard
model)
Shows all open windows for the current application using
Mission Control
F11 (or Command+F3, depending on your keyboard model)Hides all windows to display the Desktop using Mission
Control
F12 (or F4, depending on your keyboard model)Displays your Dashboard widgets
SpaceQuick Look

STRANGE-LOOKING KEYS ON THE MACBOOK KEYBOARD


image0.jpg

Monday, May 27, 2019

Python Object and Datastructure Basics:Strings,Print Formatting

Python Object and Datastructure Basics:Strings,Print Formatting
jupyter notebook
print("Hello")
Hello

Comment the code #
This is actually a mark down cell wont execute  ==>mark down
l=[1,2,3,4]

l.tab(shift+tab==> show the comment)
comment the code==>ctrl+forward slash

a=1
type(a)
int

a=0.2
type(a)
float

#Order of the Execution
PEMDAS==paranthaesis,exp,mul,div,add,sub

a,b=1,2
print("Hello \t how are you")
Hello   how are you

#Concatenation:
s='string'+'new string'
print(s)
stringnew string

#Repeat the string:
letter='A'
letter *5
'AAAAA'

#String Indexing:
s='Hello how are you'
s[0]===>'H'
s[0:4]==>'Hell'
s[starting index:ending index(not including):step size]

s[6:9]=>'how'
s[-1]=>'u'
s[-2]=>:'o'
s[:]=>'Hello how are you'
s[0:10:2]=>'Hlohw'

reverse the string:
s[::-1]  =>'uoy era woh olleH'
s[::-2]  =>'uyeawholH'

len(s)==>17
s[0]='K'
s='her'

#string is immutable
id(s)-->memory id (70477056L)
a=10
print('a value is',a)
('a value is', 10)
a=10
print('a value is',format(a))

s='Hello how are you'
s.count('o')==>3
s='Hello how are you'

s.isdigit()==>False






Monday, April 29, 2019

Python MongoDB Integeration with Examples

You can download a free MongoDB database at https://www.mongodb.com.

Install the python mangodb driver:

C:\Users\Nethra>python -m pip install pymongo
Collecting pymongo
  Downloading https://files.pythonhosted.org/packages/92/d2/6993655f5c46755cf3385ef8cec78f49909e035777724a0bf02251de733f/pymongo-3.8.0-cp37-cp37m-win32.whl (312kB)
    100% |████████████████████████████████| 317kB 729kB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.8.0
You are using pip version 19.0.3, however version 19.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Creating a Database
Important: In MongoDB, a database is not created until it gets content!
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb=myclient["mydatabase"]
Check if Database Exists
>>> print(myclient.list_database_names())
['admin', 'config', 'local']
>>> dblist=myclient.list_database_names()
>>> if "mydatabase" in dblist:
...     print("The database exists.")

Create a collection:
A collection in MongoDB is the same as a table in SQL databases.
Important: In MongoDB, a collection is not created until it gets content!
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol=mydb["customes"]
>>> print(mydb.list_collection_names())
[]
>>> collist=mydb.list_collection_names()
>>> if "customers" in collist:
...     print("The collection exists")

Insert Into Collection

A document in MongoDB is the same as a record in SQL databases
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> mydict = { "name": "John", "address": "Highway 37" }
>>> x=mycol.insert_one(mydict)
Return the _id Field
>>> x = mycol.insert_one(mydict)
>>> print(x.inserted_id)
5cc74f3ae1ceb9d5e0930979

Insert Multiple Documents
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> mylist = [
...   { "name": "Amy", "address": "Apple st 652"},
...   { "name": "Hannah", "address": "Mountain 21"},
...   { "name": "Michael", "address": "Valley 345"},
...   { "name": "Sandy", "address": "Ocean blvd 2"},
...   { "name": "Betty", "address": "Green Grass 1"},
...   { "name": "Richard", "address": "Sky st 331"},
...   { "name": "Susan", "address": "One way 98"},
...   { "name": "Vicky", "address": "Yellow Garden 2"},
...   { "name": "Ben", "address": "Park Lane 38"},
...   { "name": "William", "address": "Central st 954"},
...   { "name": "Chuck", "address": "Main Road 989"},
...   { "name": "Viola", "address": "Sideway 1633"}
... ]
>>>
>>> x = mycol.insert_many(mylist)
>>>
>>> #print list of the _id values of the inserted documents:
... print(x.inserted_ids)

Insert Multiple Documents, with Specified IDs
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> mylist = [
...   { "_id": 1, "name": "John", "address": "Highway 37"},
...   { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
...   { "_id": 3, "name": "Amy", "address": "Apple st 652"},
...   { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
...   { "_id": 5, "name": "Michael", "address": "Valley 345"},
...   { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
...   { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
...   { "_id": 8, "name": "Richard", "address": "Sky st 331"},
...   { "_id": 9, "name": "Susan", "address": "One way 98"},
...   { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
...   { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
...   { "_id": 12, "name": "William", "address": "Central st 954"},
...   { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
...   { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
... ]
>>>
>>> x = mycol.insert_many(mylist)
>>>
>>> #print list of the _id values of the inserted documents:
... print(x.inserted_ids)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Python MongoDB Find(Select)
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> x = mycol.find_one()
>>>
>>> print(x)
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}

Findall:
>>> import pymongo
>>>
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> for x in mycol.find():
...   print(x)
...
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}

Return Only Some Fields

>>> for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
...     print(x)
...
{'name': 'John', 'address': 'Highway 37'}
{'name': 'Peter', 'address': 'Lowstreet 27'}
{'name': 'Amy', 'address': 'Apple st 652'}
{'name': 'Hannah', 'address': 'Mountain 21'}
{'name': 'Michael', 'address': 'Valley 345'}
{'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'name': 'Betty', 'address': 'Green Grass 1'}
{'name': 'Richard', 'address': 'Sky st 331'}
{'name': 'Susan', 'address': 'One way 98'}
{'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'name': 'Ben', 'address': 'Park Lane 38'}
{'name': 'William', 'address': 'Central st 954'}
{'name': 'Chuck', 'address': 'Main Road 989'}
{'name': 'Viola', 'address': 'Sideway 1633'}
{'name': 'John', 'address': 'Highway 37'}
{'name': 'Peter', 'address': 'Lowstreet 27'}
{'name': 'Amy', 'address': 'Apple st 652'}
{'name': 'Hannah', 'address': 'Mountain 21'}
{'name': 'Michael', 'address': 'Valley 345'}
{'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'name': 'Betty', 'address': 'Green Grass 1'}
{'name': 'Richard', 'address': 'Sky st 331'}
{'name': 'Susan', 'address': 'One way 98'}
{'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'name': 'Ben', 'address': 'Park Lane 38'}
{'name': 'William', 'address': 'Central st 954'}
{'name': 'Chuck', 'address': 'Main Road 989'}
{'name': 'Viola', 'address': 'Sideway 1633'}

Excluding the Address:
>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>>
>>> for x in mycol.find({},{ "address": 0 }):
...   print(x)
...
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola'}
{'_id': 1, 'name': 'John'}
{'_id': 2, 'name': 'Peter'}
{'_id': 3, 'name': 'Amy'}
{'_id': 4, 'name': 'Hannah'}
{'_id': 5, 'name': 'Michael'}
{'_id': 6, 'name': 'Sandy'}
{'_id': 7, 'name': 'Betty'}
{'_id': 8, 'name': 'Richard'}
{'_id': 9, 'name': 'Susan'}
{'_id': 10, 'name': 'Vicky'}
{'_id': 11, 'name': 'Ben'}
{'_id': 12, 'name': 'William'}
{'_id': 13, 'name': 'Chuck'}
{'_id': 14, 'name': 'Viola'}

Filter the Result:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": "Park Lane 38" }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}

Advanced Query
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$gt": "S" } }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

Filter With Regular Expressions
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$regex": "^S" } }
>>> mydoc = mycol.find(myquery)
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}

Sort the Result:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> mydoc = mycol.find().sort("name")
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}

Sort Descending

sort("name", 1) #ascending
sort("name", -1) #descending 


>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> mydoc = mycol.find().sort("name", -1)
>>>
>>> for x in mydoc:
...   print(x)
...
{'_id': ObjectId('5cc75008e1ceb9d5e0930984'), 'name': 'William', 'address': 'Central st 954'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930986'), 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930982'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930981'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097e'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930980'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc74f3ae1ceb9d5e0930979'), 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097d'), 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': ObjectId('5cc74eebe1ceb9d5e0930978'), 'name': 'John', 'address': 'Highway 37'}
{'_id': 1, 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097c'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930985'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097f'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc75008e1ceb9d5e0930983'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc75008e1ceb9d5e093097b'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}

Delete Document
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": "Mountain 21" }
>>> mycol.delete_one(myquery)


Delete Many Documents
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": {"$regex": "^S"} }
>>> x = mycol.delete_many(myquery)
>>> print(x.deleted_count, " documents deleted.")
4  documents deleted.

Delete All Documents in a Collection
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> x = mycol.delete_many({})
>>> print(x.deleted_count, " documents deleted.")
23  documents deleted.

Delete collection:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> mycol.drop()
Update Collection:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": "Valley 345" }
>>> newvalues = { "$set": { "address": "Canyon 123" } }
>>> mycol.update_one(myquery, newvalues)

>>>
>>> #print "customers" after the update:
... for x in mycol.find():
...   print(x)
...
{'_id': ObjectId('5cc7589de1ceb9d5e0930997'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930998'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930999'), 'name': 'Michael', 'address': 'Canyon 123'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099a'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099b'), 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099c'), 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099d'), 'name': 'Susan', 'address': 'One way 98'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099e'), 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099f'), 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a0'), 'name': 'William', 'address': 'Central st 954'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a1'), 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': ObjectId('5cc7589de1ceb9d5e09309a2'), 'name': 'Viola', 'address': 'Sideway 1633'}


Update Many:
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myquery = { "address": { "$regex": "^S" } }
>>> newvalues = { "$set": { "name": "Minnie" } }
>>> x = mycol.update_many(myquery, newvalues)
>>> print(x.modified_count, "documents updated.")
2 documents updated.

Limit the Result
>>> import pymongo
>>> myclient = pymongo.MongoClient("mongodb://localhost:27017/")
>>> mydb = myclient["mydatabase"]
>>> mycol = mydb["customers"]
>>> myresult = mycol.find().limit(5)
>>> #print the result:
... for x in myresult:
...   print(x)
...
{'_id': ObjectId('5cc7589de1ceb9d5e0930997'), 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930998'), 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': ObjectId('5cc7589de1ceb9d5e0930999'), 'name': 'Michael', 'address': 'Canyon 123'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099a'), 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': ObjectId('5cc7589de1ceb9d5e093099b'), 'name': 'Betty', 'address': 'Green Grass 1'}
>>>





Python Important business operation(Reverse the string and Remove the duplicates)

How to remove the duplicates:
>>> mylist=["a","b","a","c","c"]
>>> mylist=list(dict.fromkeys(mylist))
>>> print(mylist)
['a', 'b', 'c']

How to remove duplicates through Function
>>> def my_function(x):
...     return list(dict.fromkeys(x))
...
>>> mylist=my_function(["a","b","a","c","c"])
>>> print(mylist)
['a', 'b', 'c']

Reverse the String:
>>> txt="Hello World"[::-1]
>>> print(txt)
dlroW olleH

Reverse a String through Function:
>>> def my_function(x):
...     return x[::-1]
...
>>> mytxt=my_function("I wonder how this text looks like backwards")
>>> print(mytxt)
sdrawkcab ekil skool txet siht woh rednow I

Monday, April 15, 2019

Python Keywords Examples


Python Keywords

and A logical operator

x = (5 > 3 and 5 < 10)

print(x)



if 5 > 3 and 5 < 10:

  print("Both statements are True")

else:

  print("At least one of the statements are False")



True

Both statements are True

as To create an alias

import calendar as c

print(c.month_name[1])



January

assert For debugging

x = "hello"

#if condition returns True, then nothing happens:

assert x == "hello"



#if condition returns False, AssertionError is raised:

assert x == "goodbye", "x should be 'hello'"



Traceback (most recent call last):

  File "main.py", line 6, in

    assert x == "goodbye", "x should be 'hello'"

AssertionError: x should be 'hello'

break To break out of a loop

for i in range(9):

  if i > 3:

    break

  print(i)

0

1

2

3

i = 1

while i < 9:

  print(i)

  if i == 3:

    break

  i += 1

1

2

3

class To define a class

class Person:

  name = "John"

  age = 36



p1 = Person()

print(p1.name)

John

continue To continue to the next iteration of a loop

for i in range(9):

  if i == 3:

    continue

  print(i)

0

1

2

4

5

6

7

8

i = 0

while i < 9:

  i += 1

  if i == 3:

    continue

  print(i)

1

2

4

5

6

7

8

9

def To define a function

def my_function():

  print("Hello from a function")

my_function()



Hello from a function



del To delete an object

class MyClass:

  name = "John"

del myClass

print(myClass)

Traceback (most recent call last):

  File "main.py", line 3, in

    del myClass

NameError: name 'myClass' is not defined



x = "hello"

del x

print(x)

Traceback (most recent call last):

  File "main.py", line 3, in

    print(x)

NameError: name 'x' is not defined



x = ["apple", "banana", "cherry"]

del x[0]

print(x)

['banana', 'cherry']



elif Used in conditional statements, same as else if

for i in range(-5, 5):

  if i > 0:

    print("YES")

  elif i == 0:

    print("WHATEVER")

  else:

    print("NO")

NO

NO

NO

NO

NO

WHATEVER

YES

YES

YES

YES



else Used in conditional statements

x = 2

if x > 3:

  print("YES")

else:

  print("NO")

NO



x = 5

try:

  x > 10

except:

  print("Something went wrong")

else:

  print("The 'Try' code was executed without raising any errors!")

The 'Try' code was executed without raising any errors!



except Used with exceptions, what to do when an exception occurs

try:

  x > 3

except:

  print("Something went wrong")

Something went wrong



x = "hello"



try:

  x > 3

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

You are comparing values of different type



try:

  x = 1/0

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

except:

  print("Something else went wrong")



Something else went wrong



x = 1



try:

  x > 10

except NameError:

  print("You have a variable that is not defined.")

except TypeError:

  print("You are comparing values of different type")

else:

  print("The 'Try' code was executed without raising any errors!")

The 'Try' code was executed without raising any errors!



False Boolean value, result of comparison operations

print(5 > 6)



print(4 in [1,2,3])



print("hello" is "goodbye")



print(5 == 6)



print(5 == 6 or 6 == 7)



print(5 == 6 and 6 == 7)



print("hello" is not "hello")



print(not(5 == 5))



print(3 not in [1,2,3])

False

False

False

False

False

False

False

False

False



finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not

try:

  x > 3

except:

  print("Something went wrong")

else:

  print("Nothing went wrong")

finally:

  print("The try...except block is finished")

Something went wrong

The try...except block is finished



for To create a for loop

for x in range(1, 9):

  print(x)

1

2

3

4

5

6

7

8

fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

apple

banana

cherry



from To import specific parts of a module

from datetime import time

x = time(hour=15)

print(x)

15:00:00



global To declare a global variable



def myfunction():

  global x

  x = "hello"



#execute the function:

myfunction()



#x should now be global, and accessible in the global scope.

print(x)

hello

if  make a conditional statement

x = 5

if x > 3:

  print("YES")

YES x = 5

if x > 6:

  print("YES")

else:

  print("NO")

NO

import To import a module

import datetime

x = datetime.datetime.now()

print(x)

2019-04-15 20:41:05.252261

in To check if a value is present in a list, tuple, etc.

fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:

  print("yes")

yes

fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

apple

banana

cherry

is To test if two variables are equal

x = ["apple", "banana", "cherry"]



y = x



print(x is y)

True

x = ["apple", "banana", "cherry"]



y = ["apple", "banana", "cherry"]



print(x is y)

False

lambda To create an anonymous function

x = lambda a : a + 10



print(x(5))

15

x = lambda a, b, c : a + b + c



print(x(5, 6, 2))

13

None Represents a null value

x = None

print(x)



x = None

if x:

  print("Do you think None is True")

else:

  print("None is not True...")

None

None is not True...

nonlocal To declare a non-local variable

def myfunc1():

  x = "John"

  def myfunc2():

    x = "hello"

  myfunc2()

  return x



print(myfunc1())

John

not A logical operator

x = False

print(not x)

True

or A logical operator

x = (5 > 3 or 5 > 10)

print(x)

if 5 > 3 or 5 > 10:

  print("At least one of the statements are True")

else:

  print("None of the statements are True")

True

At least one of the statements are True

pass A null statement, a statement that will do nothing

class Person:

  pass



raise To raise an exception

x = -1

if x < 0:

  raise Exception("Sorry, no numbers below zero")

Traceback (most recent call last):

  File "main.py", line 3, in

    raise Exception("Sorry, no numbers below zero")

Exception: Sorry, no numbers below zero

x = "hello"



if not type(x) is int:

  raise TypeError("Only integers are allowed")

Traceback (most recent call last):

  File "main.py", line 4, in

    raise TypeError("Only integers are allowed")

TypeError: Only integers are allowed

return To exit a function and return a value

def myfunction():

  return 3+3



print(myfunction())

6

def myfunction():

  return 3+3

  print("Hello, World!")



print(myfunction())



6

True Boolean value, result of comparison operations

print(5 < 6)



print(2 in [1,2,3])



print(5 is 5)



print(5 == 5)



print(5 == 5 or 6 == 7)



print(5 == 5 and 7 == 7)



print("hello" is not "goodbye")



print(not(5 == 7))



print(4 not in [1,2,3])

True

True

True

True

True

True

True

True

True

try To make a try...except statement

try:

  x > 3

except:

  print("Something went wrong")

Something went wrong

try:

  x > 3

except:

  Exception("Something went wrong")



while To create a while loop

x = 0



while x < 9:

  print(x)

  x = x + 1

0

1

2

3

4

5

6

7

8


Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...