x = 1
myint = 7
myfloat=7.0
mystring="Amit Bhar’tiya"
print ('Hello World')
print(myint)
print(myfloat)
print(myint,myfloat)
print(mystring)
if x == 1:
print('output is 1')
input
Hello World
7
7.0
7 7.0
Amit Bhar’tiya
output is 1
==================
x=1
mystring="hello"
myfloat=10.12
print ('Hello World')
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.12:
print("Float: %f" % myfloat)
if myfloat== 10.12:
print("float: %f" % myfloat)
Hello World
String: hello
Float: 10.120000
float: 10.120000
lists:
print ('Hello World')
mylist= []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0])
print(mylist[1])
print(mylist[2])
for x in mylist:
print (x)
Hello World
print ('Hello World')
mynumber= []
mystring= []
names= ["Amit","Tanvi","Sweety"]
mynumber.append(20)
mynumber.append(10)
mynumber.append(5)
mystring.append("amit")
mystring.append("bhartiya")
print(mystring)
print(mynumber)
print(sum(mynumber))
print(names[1])
for x in mynumber:
print(mystring)
Hello World
['amit', 'bhartiya']
[20, 10, 5]
35
Tanvi
['amit', 'bhartiya']
['amit', 'bhartiya']
['amit', 'bhartiya']
print ('Hello World')
lotsofhellos = "hello" * 10
print(lotsofhellos)
print([1,2,3] * 3)
Hello World
Hellohellohellohellohellohellohellohellohellohello
[1, 2, 3, 1, 2, 3, 1, 2, 3]
print('A\nB\nC')
2 print('D\tE\tF')
3 print('WX\bYZ')
4 print('1\a2\a3\a4\a5\a6')
D E F
WYZ
123456
print("please enter some text")
x=input()
print("text entered is:", x)
Hello World
please enter some text
->I am learning python
text entered is: I am learning python
print("please enter first number")
x=input()
print("please enter second number")
y=input()
num1 =int(x)
num2=int(y)
print("sum is :" , num1 + num2)
Hello World
please enter first number
12
please enter second number
21
sum is : 33
x=float(input('Please enter a number'))
What if we wish x to be of type integer if the user enters 2 and x to be floating point if the user enters
2.0? P
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))
x2 = eval(input('Entry x2? '))
print('x2 =', x2, ' type:', type(x2))
x3 = eval(input('Entry x3? '))
print('x3 =', x3, ' type:', type(x3))
x4 = eval(input('Entry x4? '))
print('x4 =', x4, ' type:', type(x4))
x5 = eval(input('Entry x5? '))
print('x5 =', x5, ' type:', type(x5))
Entry x1? 4 x1 = 4 type: <class ‘int’>
Entry x2? 4.0 x2 = 4.0 type: <class ‘float’>
Entry x3? ’x1’ x3 = x1 type:<’str’>
Entry x4? x1 x4 = 4 type: Entry x5? x6
print("please enter first number")
x=input()
print("please enter second number")
y=input()
num1 =int(x)
num2=int(y)
print("sum is :" , num1 + num2)
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')
Hello World
please enter first number
12
please enter second number
21
sum is : 33
ABC
print ('Hello World')
print("please enter first number")
x=input()
print("please enter second number")
y=input()
num1 =int(x)
num2=int(y)
print("sum is :" , num1 + num2)
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
Hello World
please enter first number
12
please enter second number
21
sum is : 33
ABC
10 15 20 25
10,15,20,25
10152025
10:15:20:25
If /else
value= eval(input("enter a number between 0..10 "))
if value>=0:
if value <=10:
print(value,"in range")
else:
print(value,"out of range")
Hello World
enter a number between 0..10 56
56 out of range
========================
print ('Hello World')
value= eval(input("enter a number between 0..10 "))
if value>=0:
if value <=10:
print(value,"in range")
else:
print(value,"out of range")
value = eval(input("Please enter an integer in the range 0...5: "))
if value < 0:
print("Too small")
elif value == 0:
print("zero")
elif value == 1:
print("one")
elif value == 2:
print("two")
else:
print("Too large")
print("Done")
Hello World
enter a number between 0..10 45
45 out of range
Please enter an integer in the range 0...5: 5
Too large
Done
String formatting:
print ('Hello World')
name="Amit"
name1="Tanvi"
age=31
my_list=[1,2,3]
print("name is %s" %name)
print("Husband %s Wife %s" %(name,name1))
print("Age is %d Name is %s" %(age,name))
print("list details: %s" %my_list)
Hello World
name is Amit
Husband Amit Wife Tanvi
Age is 31 Name is Amit
list details: [1, 2, 3]
astring = "Hello world!"
print(astring.index("o"))
print(astring.count("e"))
print(astring[3:7])
print(astring[-10:3])
print(astring[3:7:3])
print(astring[::-1])—reverse string
print(astring.upper())
print(astring.lower())
print(astring.startswith("He"))
print(astring.endswith("myfg"))
print(astring.startswith(“he”))
print(astring.split(" "))
s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = %d" % len(s))
print("The first occurrence of the letter a = %d" % s.index("a"))
4
lo w
lw
!dlrow olleH
HELLO WORLD!
hello world!
True
False
False
['Hello', 'world!']
Length of s = 38
The first occurrence of the letter a = 13
print ('Hello World')
stre = "Hey there! what should this string be?"
print("a occurs %d number of times" %stre.count("a"))
print(" the first 5 char are %s" %stre[:5])
print(" the char from 5 to 10 are '%s' " %stre[5:10])
print("The characters with odd index are '%s'" %stre[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % stre[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % stre.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % stre.lower())
# Check how a string starts
if stre.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if stre.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % stre.split(" "))
Hello World
a occurs 1 number of times
the first 5 char are Hey t
the char from 5 to 10 are 'here!'
The characters with odd index are 'e hr!wa hudti tigb?'
The last five characters are 'g be?'
String in uppercase: HEY THERE! WHAT SHOULD THIS STRING BE?
String in lowercase: hey there! what should this string be?
Split the words of the string: ['Hey', 'there!', 'what', 'should', 'this', 'string', 'be?']
========
num1 = 10
num2 = 20
arr1 = [1,2]
arr2 = [1,2,3]
if len(arr1) == 2:
print(3)
if len(arr2) ==2:
print(4)
if len(arr1) + len(arr2) == 5:
print("4")
For loop:
It is for optimization reasons.
range(): range(1, 10) returns a list from 1 to 10 numbers & hold whole list in memory.
xrange(): Like range(), but instead of returning a list, returns an object that generates the
numbers in the range on demand. For looping, this is lightly faster than range() and more
memory efficient. xrange() object like an iterator and generates the numbers on demand.
(Lazy Evaluation)
xrange is removed in python 3
primes = [2, 3, 5, 7,8]
for prime in primes:
print(prime)
for x in range(5):
print(x)
for x in range(1,3):
print(x)
for x in range(3, 10, 3):
print(x)
for x in range(5):
print(x)
for x in range(1,3):
print(x)
for x in range(3, 10, 3):
print(x)
9
items = [8, 23, 45, 12, 78]
for index, item in enumerate(items):
print(index, item)
items1 = [8, 23, 45, 12, 78]
for index, item in enumerate(items1,start=1):
print(index, item)
08
1 23
2 45
3 12
4 78
--
18
2 23
3 45
4 12
5 78
'''
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
'''
print ('Hello World')
#count=0
#while count<5:
# print(count)
# count +=1
count =0
while True:
print(count)
count += 1
if count >= 5:
break
Hello World
for x in range(10):
if x%2 == 0:
continue
print(x)
numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,
743, 527
for number in numbers:
if number == 237:
break
if number % 2 == 1:
continue
print(number)
402
984
360
408
980
544
390
984
592
236
942
386
462
418
344
236
566
978
328
162
758
918
def bigdata_benefits():
return "more versatile", "more velocity", "more volume", "more veracity"
def build_sentence(benefit):
return "%s is a benefit of big data" %benefit
def benefit_definition():
list_of_benefits= bigdata_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
benefit_definition()
more versatile is a benefit of big data
more velocity is a benefit of big data
more volume is a benefit of big data
more veracity is a benefit of big data
Class and object
class my_class:
variable= "xyz"
def my_func(desc):
return "description is %s" %desc.variable
my_object= my_class()
my_object.variable
print(my_object.variable)
print(my_object.my_func())
xyz
description is xyz
class vehicle:
name= "sdf"
kind= "car"
color= ""
price= "100.00"
model= ""
def func_details_car1(desc):
desc_str ="name is %s kind is %s color is %s price is $%.2f model is %s" %
(desc.name,desc.kind,desc.color,desc.price,desc.model)
return desc_str
car1=vehicle()
car1.name="mercedes"
car1.kind="car"
car1.color="red"
car1.price=60000.00
car1.model="versatile"
car2=vehicle()
car2.name="hummer"
car2.kind="truck"
car2.color="black"
car2.price=80000.00
car2.model="convertible"
#print(car1.name)
print(car1.func_details_car1())
print(car2.func_details_car1())
xyz
description is xyz
name is mercedes kind is car color is red price is $60000.00 model is versatile
name is hummer kind is truck color is black price is $80000.00 model is convertible
Dictionaries
A dictionary is a data type similar to arrays, but works with keys and
values instead of indexes. Each value stored in a dictionary can be
accessed using a key, which is any type of object (a string, a number, a
list, etc.) instead of using its index to address it.
phonebook= {}
phonebook["john"]= 987645500
phonebook["jack"]= 894657599
phonebook["ryan"]= 548469745
print(phonebook)
#to iterate through the dict
phonebook1={ "john":846575999,"gary":466557580, "susan":644797597 }
print(phonebook1)
for name,number in phonebook1.items():
print("phone number of %s is %d" %(name,number))
# to remove a phone number
del phonebook["john"]
phonebook.pop("ryan")
#to add a phone number
phonebook["Jake"] = 938273443
print(phonebook)
{'john': 987645500, 'jack': 894657599, 'ryan': 548469745}
{'susan': 644797597, 'john': 846575999, 'gary': 466557580}
phone number of susan is 644797597
phone number of john is 846575999
phone number of gary is 466557580
{'Jake': 938273443, 'jack': 894657599}
Writing modules
Modules in Python are simply Python files with a .py extension. The
name of the module will be the name of the file. A Python module can
have a set of functions, classes or variables defined and implemented.
In the example above, we will have two files, we will have:
mygame/
mygame/game.py
mygame/draw.py
The Python script game.py will implement the game. It will use the
function draw_game from the file draw.py , or in other words, the draw module,
that implements the logic for drawing the game on the screen.
Modules are imported from other modules using the import command. In
this example, the game.py script may look something like this:
# game.py
# import the draw module
import draw
def play_game():
...
def main():
result = play_game()
draw.draw_game(result)
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main()
The draw module may look something like this:
# draw.py
def draw_game():
...
def clear_screen(screen):
In this example, the game module imports the load module, which enables it to
use functions implemented in that module. The main function would use the
local function play_game to run the game, and then draw the result of the game
using a function implemented in the draw module called draw_game . To use the
function draw_game from the draw module, we would need to specify in which
module the function is implemented, using the dot operator. To reference
the draw_game function from the game module, we would need to import
the draw module and only then call draw.draw_game() .
When the import draw directive will run, the Python interpreter will look for a
file in the directory which the script was executed from, by the name of the
module with a .py prefix, so in our case it will try to look for draw.py . If it will
find one, it will import it. If not, he will continue to look for built-in modules
You may have noticed that when importing a module, a .pyc file appears,
which is a compiled Python file. Python compiles files into Python bytecode
so that it won't have to parse the files each time modules are loaded. If
a .pyc file exists, it gets loaded instead of the .py file, but this process is
transparent to the user.
Importing module objects to the current
namespace
We may also import the function draw_game directly into the main script's
namespace, by using the from command.
# game.py
# import the draw module
from draw import draw_game
def main():
result = play_game()
draw_game(result)
You may have noticed that in this example, draw_game does not precede with
the name of the module it is imported from, because we've specified the
module name in the import command.
The advantages of using this notation is that it is easier to use the functions
inside the current module because you don't need to specify which module
the function comes from. However, any namespace cannot have two objects
with the exact same name, so the import command may replace an existing
object in the namespace.
Importing all objects from a module
# game.py
# import the draw module
from draw import *
def main():
result = play_game()
draw_game(result)
Extending module load path
There are a couple of ways we could tell the Python interpreter where
to look for modules, aside from the default, which is the local directory
and the built-in modules. You could either use the environment
variable PYTHONPATH to specify additional directories to look for modules
in, like this:
PYTHONPATH=/foo python game.py
Another method is the sys.path.append function. You may execute
it before running an import command:
sys.path.append("/foo")
Exploring built-in modules
Check out the full list of built-in modules in the Python standard
library here.
Two very important functions come in handy when exploring modules
in Python - the dir and help functions.
If we want to import the module urllib , which enables us to create read
data from URLs, we simply import the module:
# import the library
import urllib
# use it
urllib.urlopen(...)
We can look for which functions are implemented in each module by using
the dir function:
import urllib
>>> dir(urllib)
When we find the function in the module we want to use, we can read about it
more using the help function, inside the Python interpreter:
help(urllib.urlopen)
Numpy library:
lst_height= [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
lst_weight= [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
import numpy as np
arr= np.array(lst_height)
arr1=np.array(lst_weight)
print(arr)
print(arr1)
print(type(lst_height))
bmi= arr/arr1 *2
print(bmi)
arr=arr+5
print(arr)
print(np.arange(0, 27, 1))
print(np.arange(0, 27, 2))
print(np.linspace(0, 90, 3))
print(np.linspace(0, 100, 4))
ar_mat= np.array([1,2,3,4,5,6,7,8]).reshape(2,4)
print(ar_mat)
matrix= np.matrix([[1,2,3], [4,5,6], [7,8,9]])
print(matrix)
[1.87 1.87 1.82 1.91 1.9 1.85]
[81.65 97.52 95.25 92.98 86.18 88.45]
<class 'list'>
[0.04580527 0.03835111 0.03821522 0.0410841 0.04409376 0.04183154]
[6.87 6.87 6.82 6.91 6.9 6.85]
[ 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]
[ 0 2 4 6 8 10 12 14 16 18 20 22 24 26]
[ 0. 45. 90.]
[ 0. 33.33333333 66.66666667 100. ]
[[1 2 3 4]
[5 6 7 8]]
[[1 2 3]
[4 5 6]
[7 8 9]]
Data frame
import pandas as pd
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98] }
brics = pd.DataFrame(dict)
print(brics)
import pandas as pd
dict= {"2012":["Techmahindra","Bhubaneswar","GE","Sister Wedding"],
"2015":["Capgemini","Pune","Talwade","Barclays"],
"2016":["Cognizant","Data Quality","STC","Saudi Onsite"],
"2018":["Infosys","Hinjewadi","Campus","Schwab"]
Memories= pd.DataFrame(dict)
print(Memories)
# Set the index for brics
brics.index = ["BR", "RU", "IN", "CH", "SA"]
# Print out brics with new index values
print(brics)
Memories.index=["TechM","Capgemini","Cognizant","Infosys"]
print(Memories)
area capital country population
0 8.516 Brasilia Brazil 200.40
1 17.100 Moscow Russia 143.50
2 3.286 New Dehli India 1252.00
3 9.597 Beijing China 1357.00
4 1.221 Pretoria South Africa 52.98
2012 2015 2016 2018
0 Techmahindra Capgemini Cognizant Infosys
1 Bhubaneswar Pune Data Quality Hinjewadi
2 GE Talwade STC Campus
3 Sister Wedding Barclays Saudi Onsite Schwab
area capital country population
0 8.516 Brasilia Brazil 200.40
1 17.100 Moscow Russia 143.50
2 3.286 New Dehli India 1252.00
3 9.597 Beijing China 1357.00
4 1.221 Pretoria South Africa 52.98
2012 2015 2016 2018
0 Techmahindra Capgemini Cognizant Infosys
1 Bhubaneswar Pune Data Quality Hinjewadi
2 GE Talwade STC Campus
3 Sister Wedding Barclays Saudi Onsite Schwab
area capital country population
BR 8.516 Brasilia Brazil 200.40
RU 17.100 Moscow Russia 143.50
IN 3.286 New Dehli India 1252.00
CH 9.597 Beijing China 1357.00
SA 1.221 Pretoria South Africa 52.98
2012 2015 2016 2018
TechM Techmahindra Capgemini Cognizant Infosys
Capgemini Bhubaneswar Pune Data Quality Hinjewadi
Cognizant GE Talwade STC Campus
Infosys Sister Wedding Barclays Saudi Onsite Schwab
Another way to create a DataFrame is by importing a csv file using Pandas.
Now, the csv cars.csv is stored and can be imported using pd.read_csv :
# Import pandas as pd
import pandas as pd
# Import the cars.csv data: cars
cars = pd.read_csv('cars.csv')
# Print out cars
print(cars)
Indexing DataFrames
There are several ways to index a Pandas DataFrame. One of the
easiest ways to do this is by using square bracket notation.
In the example below, you can use square brackets to select one
column of the cars DataFrame. You can either use a single bracket or a
double bracket. The single bracket with output a Pandas Series, while
a double bracket will output a Pandas DataFrame.
# Import pandas and cars.csv
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out country column as Pandas Series
print(cars['cars_per_cap'])
# Print out country column as Pandas DataFrame
print(cars[['cars_per_cap']])
# Print out DataFrame with country and drives_right columns
print(cars[['cars_per_cap', 'country']])
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out first 4 observations
print(cars[0:4])
# Print out fifth, sixth, and seventh observation
print(cars[4:6])
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out observation for Japan
print(cars.iloc[2])
# Print out observations for Australia and Egypt
print(cars.loc[['AUS', 'EG']])
Generators
Generators are very easy to implement, but a bit difficult to
understand.
Generators are used to create iterators, but with a different approach.
Generators are simple functions which return an iterable set of items,
one at a time, in a special way.
When an iteration over a set of item starts using the for statement, the
generator is run. Once the generator's function code reaches a "yield"
statement, the generator yields its execution back to the for loop,
returning a new value from the set. The generator function can
generate as many values (possibly infinite) as it wants, yielding each
one in its turn
import random as rd
def lottery():
for i in range(6):
yield rd.randint(1,100)
yield rd.randint(1,5)
for random_number in lottery():
print("And the next number is %d!" %(random_number))
And the next number is 44!
And the next number is 13!
And the next number is 85!
And the next number is 71!
And the next number is 32!
And the next number is 96!
And the next number is 1!
Fibonacci using generator
def fibonacci():
"""Fibonacci numbers generator"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
f = fibonacci()
counter = 0
for x in f:
print (x)
counter += 1
if (counter > 10): break
print
13
21
34
55
Fibonacci using while loop
count=0
n1=0
n2=1
nterms=10
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while (count<nterms):
print(n1,end=' , ')
n3=n1+n2
n1=n2
n2=n3
count +=1
factorial using generator:
def factorial(x):
a=1
for i in range(1,x+1):
a *=i
yield a
for x in factorial(5):
print(x)
To understand what yield does, you must understand what generators are. And before
generators come iterables.
Iterables
When you create a list, you can read its items one by one. Reading its items one by one is
called iteration:
>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i)
1
2
3
mylist is an iterable. When you use a list comprehension, you create a list, and so an
iterable:
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
... print(i)
0
1
4
Everything you can use "for... in..." on is an iterable; lists, strings, files...
These iterables are handy because you can read them as much as you wish, but you store
all the values in memory and this is not always what you want when you have a lot of
values.
Generators
Generators are iterators, a kind of iterable you can only iterate over once.
Generators do not store all the values in memory, they generate the values on the
fly:
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
... print(i)
0
1
4
It is just the same except you used () instead of []. BUT, you cannot perform for i in
mygenerator a second time since generators can only be used once: they calculate 0, then
forget about it and calculate 1, and end calculating 4, one by one.
Yield
yield is a keyword that is used like return, except the function will return a generator.
>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4
Here it's a useless example, but it's handy when you know your function will return a huge
set of values that you will only need to read once.
To master yield, you must understand that when you call the function, the code
you have written in the function body does not run. The function only returns
the generator object, this is a bit tricky :-)
Then, your code will continue from where it left off each time for uses the generator.
Now the hard part:
The first time the for calls the generator object created from your function, it will run the
code in your function from the beginning until it hits yield, then it'll return the first value of
the loop. Then, each other call will run the loop you have written in the function one more
time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs, but does not hit yield anymore.
It can be because the loop had come to an end, or because you do not satisfy
an "if/else" anymore.
Controlling a generator exhaustion
>>> class Bank(): # Let's create a bank, building ATMs
... crisis = False
... def create_atm(self):
... while not self.crisis:
... yield "$100"
>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # Crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business
>>> for cash in brand_new_atm:
... print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...
Note: For Python 3,
useprint(corner_street_atm.__next__()) or print(next(corner_street_atm))
It can be useful for various things like controlling access to a resource.
Itertools, your best friend
The itertools module contains special functions to manipulate iterables. Ever wish to
duplicate a generator? Chain two generators? Group values in a nested list with a one-
liner? Map / Zip without creating another list?
Then just import itertools.
An example? Let's see the possible orders of arrival for a four-horse race:
>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4),
(1, 2, 4, 3),
(1, 3, 2, 4),
(1, 3, 4, 2),
(1, 4, 2, 3),
(1, 4, 3, 2),
(2, 1, 3, 4),
(2, 1, 4, 3),
(2, 3, 1, 4),
(2, 3, 4, 1),
(2, 4, 1, 3),
(2, 4, 3, 1),
(3, 1, 2, 4),
(3, 1, 4, 2),
(3, 2, 1, 4),
(3, 2, 4, 1),
(3, 4, 1, 2),
(3, 4, 2, 1),
(4, 1, 2, 3),
(4, 1, 3, 2),
(4, 2, 1, 3),
(4, 2, 3, 1),
(4, 3, 1, 2),
(4, 3, 2, 1)]
List Comprehensions is a very powerful tool, which creates a new list
based on another list, in a single, readable line.
For example, let's say we need to create a list of integers which
specify the length of each word in a certain sentence, but only if the
word is not the word "the".
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
words_length=[]
for word in words:
if word!='the':
words_length.append(len(word))
#print(words)
#print(words_length)
#Simply the above using List of comprehension
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)
print(word_lengths)
# Postive numbers out of a List
all_list=[10,-23,-45, 100,23,43,0,74,-99]
new_list=[number for number in all_list if number>0]
print (all_list)
print(new_list)
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[5, 5, 3, 5, 4, 4, 3]
[10, -23, -45, 100, 23, 43, 0, 74, -99]
[10, 100, 23, 43, 74]
#multiple arguments inside function
def func(first,second,third,*rest):
print(" first is %s" %first)
print("second is %s" %second)
print("Third is %s" %third)
print("Rest is %s" %list(rest))
func(1,2,3,4,5,6,7,9,10)
first is 1
second is 2
Third is 3
Rest is [4, 5, 6, 7, 9, 10]
Regular Expression
Use this code --> Import re
What are various methods of Regular Expressions?
The ‘re’ package provides multiple methods to perform queries on an input string. Here are
the most commonly used methods, I will discuss:
1. re.match()
2. re.search()
3. re.findall()
4. re.split()
5. re.sub()
6. re.compile()
re.match(pattern, string):
This method finds match if it occurs at start of the string. For example, calling match() on
the string ‘AV Analytics AV’ and looking for a pattern ‘AV’ will match. However, if we look for
only Analytics, the pattern will not match. Let’s perform it in python now.
Code
import re
result = re.match(r'AV', 'AV Analytics Vidhya AV')
print result
Output:
<_sre.SRE_Match object at 0x0000000009BE4370>
Above, it shows that pattern match has been found. To print the matching string
we’ll use method group (It helps to return the matching string). Use “r” at the start of the
pattern string, it designates a python raw string.
result = re.match(r'AV', 'AV Analytics Vidhya AV')
print result.group(0)
This is because the match function only returns the first match
found.
text = "The film Titanic was released in 1998"
res=re.match(r".*",text)
type(res)
print(res.group(0))
We
None
The film Titanic was released in 1998
Since we specified to match the string with any length and any
character, even an empty string is being matched.
Here the plus sign specifies that the string should have at
least one character
import re
result= re.match(r'We', 'We are all we indians ')
result1= re.match(r'indians', 'We are all we indians all indians')
print(result.group(0))
print(result1)
text = "The film Titanic was released in 1998"
res=re.match(r".*",text)
res1=re.match(r".+",text)
res2=re.match(r"[a-zA-Z]+",text)
type(res)
print(res.group(0))
print(res1.group(0))
print(res2.group(0))
We
None
The film Titanic was released in 1998
The film Titanic was released in 1998
The
The is returned. This is because the match function only returns
the first match found. In the regex we specified that find the
patterns with both small and capital alphabets from a to z. The
first match found was The. After the word The there is a space,
which is not treated as an alphabet letter, therefore the
matching stopped and the expression returned just The, which
is the first match.
The search Function
The search function is similar to the match function i.e. it tries to
match the specified pattern. However, unlike the match function,
it matches the pattern globally instead of matching only the
first element
text = "1998 was the year when the film titanic was released"
if re.search(r"^1998", text):
print("Match found")
else: print("Match not found")
text = "1998 was the year when the film titanic was released" if re.search(r"1998$",
text): print("Match found") else: print("Match not found")
re.split(pattern, string, [maxsplit=0]):
This methods helps to split string by the occurrences of given pattern.
result=re.split(r'y','Analytics')
result
Output:
['Anal', 'tics']
re.sub(pattern, repl, string):
It helps to search a pattern and replace with a new sub string. If the pattern is
not found, string is returned unchanged.
Code
result=re.sub(r'India','the World','AV is largest Analytics community of India')
result
Output:
'AV is largest Analytics community of the World'
Operators Description
. Matches with any single character except newline ‘\n’.
? match 0 or 1 occurrence of the pattern to its left
+ 1 or more occurrences of the pattern to its left
* 0 or more occurrences of the pattern to its left
Matches with a alphanumeric character whereas \W (upper case W) matches non alphanum
\w
character.
\d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
Matches with a single white space character (space, newline, return, tab, form) and \S (uppe
\s
matches any non-white space character.
\b boundary between word and non-word and /B is opposite of /b
Matches any single character in a square bracket and [^..] matches any single character not
[..]
bracket
\ It is used for special meaning characters like \. to match a period or \+ for plus sign.
^ and $ ^ and $ match the start or end of the string respectively
Matches at least n and at most m occurrences of preceding expression if we write it as {,m}
{n,m}
return at least any minimum occurrence to max m preceding expression.
a| b Matches either a or b
() Groups regular expressions and returns matched text
\t, \n, \r Matches tab, newline, return
For more details on meta characters “(“, “)”,”|” and others details , you can refer this link
(https://docs.python.org/2/library/re.html).
import re
result= re.match(r'We', 'We are all we indians ')
result1= re.match(r'indians', 'We are all we indians all indians')
print(result.group(0))
print(result1)
text = "The film Titanic was released in 1998"
res=re.match(r".*",text)
res1=re.match(r".+",text)
res2=re.match(r"[a-zA-Z]+",text)
type(res)
#match
print(res.group(0))
print(res1.group(0))
print(res2.group(0))
text1 = "1998 was the year when the film titanic was released"
if re.search(r"^1998", text1):
print("Match found")
else:
print("Match not found")
#search
res3=re.search(r"the",text1)
print(res3.group(0))
#Findall
res4=re.findall(r"the",text1)
print(res4)#no group here
#Split
res5=re.split(r" ",text1)
print(res5)
res6=re.split(r"the",text1)
print(res6)
res7=re.split(r"the",text1,maxsplit=1)
print(res7)
#Sub
res8=re.sub(r"titanic","Spiderman",text1)
print(res8)
html="He was carefully disguised but captured quickly by police and speedily"
regex=r"\w+ly"
pattern=re.compile(regex)
search = pattern.search(html)
print(search.group(0))
print("search result above:")
finditer=pattern.finditer(html)
for match in re.finditer(pattern,html):
s_start=match.start()
s_end=match.end()
s_group=match.group()
print(s_start)
print(s_end)
print(s_group)
findall1=re.findall(pattern,html)
print(findall1)
We
None
The film Titanic was released in 1998
The film Titanic was released in 1998
The
Match found
the
['the', 'the']
['1998', 'was', 'the', 'year', 'when', 'the', 'film', 'titanic', 'was', 'released']
['1998 was ', ' year when ', ' film titanic was released']
['1998 was ', ' year when the film titanic was released']
1998 was the year when the film Spiderman was released
carefully
search result above:
16
carefully
40
47
quickly
62
70
speedily
['carefully', 'quickly', 'speedily']
Append Vs Extend
x = [1, 2, 3]
x.append([4, 5])
print (x)
x1 = [1, 2, 3]
x1.extend([4, 5])
print (x1)
[1, 2, 3, [4, 5]]
[1, 2, 3, 4, 5]