Ignore this, this is just to apply styple to this notebook
by sukhbinder singh
plot([1,2,3,4])
[<matplotlib.lines.Line2D at 0x7319fd0>]
2+3
5
3**3
27
2+3*4+56+67
137
#practice one
#practice two
a=2
b=3
print a,b
2 3
type(a)
int
print a,'\n',b
2 3
print a**b # Notice the double ** for power
8
print a*b
6
print a-b
-1
print a+b
5
print a,b
2 3
print b/a
1
print 3/2
1
print type(a),type(b)
<type 'int'> <type 'int'>
but....
print 3.0/2
1.5
logical = False # logical variable
print logical
logical = True
print logical
False True
print type(logical)
<type 'bool'>
name="python"
print name
python
phase=" is cool!"
So what's the output for this command.
print name+phase
print name+phase
python is cool!
# try a=10**4 and b=10**100 and check their types
So we have learnt how to declare python variables, lets try some exercises.
# define varible cost_price, sale_price and profit
# and calculate and display the profit percentage
# define variable width, length, area and circum and
# calculate the area and circumference of the rectangle
pi=3.14
# define a variable "name" and assign it with your name...
# + concatenates a string "is learnig python!" , now check
# what happens when you do name * 5
name='''python
venkat
'''
# Created using square brackets
alist=[1,2,3,4,5]
print alist
[1, 2, 3, 4, 5]
alist.append(6)
print alist
[1, 2, 3, 4, 5, 6]
alist.pop()
6
alist[1]=666
print alist
[1, 666, 3, 4, 5]
# add some more numbers
alist.append(60 )
alist.append(23)
print alist
[1, 666, 3, 4, 5, 60, 23]
# find out how many numbers in a list
print len(alist)
7
# sort the list
print sorted(alist)
[1, 3, 4, 5, 23, 60, 666]
alist[0]
1
# plot this list
plot(alist)
[<matplotlib.lines.Line2D at 0x7d0c550>]
# to insert multiple items in the list
alist.extend([101,202,303,404])
print alist
[1, 666, 3, 4, 5, 60, 23, 101, 202, 303, 404]
# add a string variable in above list
alist.append("Derby")
print alist
[1, 666, 3, 4, 5, 60, 23, 101, 202, 303, 404, 'Derby']
alist.append("value of pi")
alist.append(3.14)
print alist
[1, 666, 3, 4, 5, 60, 23, 101, 202, 303, 404, 'Derby', 'value of pi', 3.14]
print sorted(alist)
[1, 3, 3.14, 4, 5, 23, 60, 101, 202, 303, 404, 666, 'Derby', 'value of pi']
alist.append("Apple") # added apple, it should come before sukhbinder
print sorted(alist)
[1, 3, 3.14, 4, 5, 23, 60, 101, 202, 303, 404, 666, 'Apple', 'Derby', 'value of pi']
print alist
[1, 666, 3, 4, 5, 60, 23, 101, 202, 303, 404, 'Derby', 'value of pi', 3.14, 'Apple']
print alist
[1, 666, 3, 4, 5, 60, 23, 101, 202, 303, 404, 'Derby', 'value of pi', 3.14, 'Apple']
# so the to get the first item
print alist[0]
1
# to get the value of pi
print alist[17]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-61-6c233d3ca464> in <module>() 1 # to get the value of pi ----> 2 print alist[17] IndexError: list index out of range
print alist[-1]
print alist[-2]
# create a list containg squares of the number from 2 to 8
# append squares of the number 9 and 10 to it.
# plot the list
# create a list of your favourite fruits in order of your preference
# print the name of the least favorite fruit using the indices.
# create a newlist called **combined** and put the above two list together
# sort and print the new list
True and False
True or False
not False
{key1 : value1, ...}
:¶Dictionaries are unordered lists of objects stored with reference to a key.
#Created with curly brackets {}
PriceList = {"apples" : 100.0,
"Mango" : 200.0,
"Pineapple" : 30.0,}
print(type(PriceList))
print(PriceList)
print PriceList["Mango"]
PriceList.keys()
# How can you create an empty dictionary and a list and add something to it
The Python syntax for conditional execution of code use the keywords if
, elif
(else if), else
:
statement1 = True
statement2 = False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False")
{
and }
. And the level of indentation (white space before the code statements) does not matter (completely optional).¶for x in [1,2,3]:
print(x)
for x in range(-3,3):
print(x)
things = ['tv', 'laptop', 'chair', 'mobile', 'table']
for name in things:
print name
# find the square of first 1 to 10 numbers using for loop
# Write a program to iterate find len of each word from the below text
text = "Do what is right not what is easy"
# Write a program to find if text contains the word "hard"
text = "Do what is right not what is easy"
print [num**2 for num in range(1,11)]
a= [(word,len(word)) for word in text.split()]
print a
print type(a[0])
while
loop:¶i = 0
while i < 5:
print(i)
i = i + 1
print("done")
# another example
i=0
while True:
print i,
i+=1
if (i >5):
break
print "done!"
def
, followed by a function name, a signature within parentheses ()
, and a colon :
.¶# Defined using the def keyword
def testFunction():
print("If at first you don’t succeed; call it version 1.0.!!")
testFunction()
def func1(s):
"""
Print a string 's' and tell how many characters it has
"""
print(s + " has " + str(len(s)) + " characters")
help(func1)
func1("Python is cool")
help(testFunction)
def square(x):
"""
Return the square of x.
"""
return x ** 2
square(4)
# Functions can return multiple values
def powers(x):
"""
Return a few powers of x.
"""
return x ** 2, x ** 3, x ** 4
powers(4)
# Calling function using keywords
powers(x=2)
# write a function to write out times tables for a given number
# 9 x 1 = 9
# 9 x 2 = 18
# etc
# write a function that calculates distance between two points (x1,y1) (x2,y2)
x1,y1 = 0.0,0.0
x2,y2 = 10.0,10.0
# Lets open a file and write out our alist one line at a time into the file
fp=open('ourfile.txt',"w")
for word in alist:
fp.write(str(word)+'\n')
fp.close()
!type ourfile.txt
# Lets write out the dictionary keys PriceList that we created earlier
fp=open('ourfile2.txt',"w")
fp.writelines(PriceList.keys())
fp.close()
!type ourfile2.txt
class
keyword, and the class definition usually contains a number of class method definitions (a function in a class).¶Each class method should have an argument self
as it first argument. This object is a self-reference.
Some class method names have special meaning, for example:
__init__
: The name of the method that is invoked when the object is first created.__str__
: A method that is invoked when a simple string representation of the class is needed, as for example when printed.class Point:
"""
Simple class for representing a point in a Cartesian coordinate system.
"""
def __init__(self, x, y):
"""
Create a new Point at x, y.
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point by dx and dy in the x and y direction.
"""
self.x += dx
self.y += dy
def __str__(self):
return("Point at [%f, %f]" % (self.x, self.y))
p1 = Point(0, 0) # this will invoke the __init__ method in the Point class
print(p1) # this will invoke the __str__ method
print (type(p1))
dir(p1)
p2 = Point(1, 1)
p1.translate(0.25, 1.5)
print(p1)
print(p2)
# Create a class rectangle, implement area and perimeter calculation as its methods
class rectangle:
"""
Simple class for representing a rectangle.
"""
where
# Cantilever class
import math
x = math.cos(2 * math.pi)
print(x)
# print the value of pi
print math.pi
# Second method of importing (not recommended)
from math import *
x = cos(2 * pi)
print(x)
# Third method of importing a module
from math import cos,pi
x=cos(2*pi)
print x
import json
# Find what are its available methods
print dir(json)
import tarfile
def untar(fname):
if (fname.endswith("tar.gz")):
tar = tarfile.open(fname)
tar.extractall()
tar.close()
print "Extracted in Current Directory"
else:
print "Not a tar.gz file: '%s '" % fname