myTuple = tuple( ("Apple","Orange","Mango"))
print(myTuple)
('Apple', 'Orange', 'Mango')
myTuple = ("Apple","Orange","Mango")
print(myTuple)
('Apple', 'Orange', 'Mango')
myTuple = ("Apple","Orange","Mango")
print(myTuple[0])
print(myTuple[1])
print(myTuple[2])
Apple
Orange
Mango
myTuple = ("Apple","Orange","Mango")
print(myTuple[:2])
('Apple', 'Orange')
myTuple = ("Apple","Orange","Mango")
print(myTuple[-1])
Mango
// change the tuple values - indirect approach. create a list with the same contents of tuple
fruitsTuple=("Kiwi","Banana","Mango") #Not Changeable
fruitsList = list(fruitsTuple) #Now It is changeable
fruitsList[0]="Lichi"
fruitsTuple = tuple(fruitsList)
print(fruitsTuple)
('Lichi', 'Banana', 'Mango')
fruitsTuple=("Kiwi","Banana","Mango")
for fruit in fruitsTuple:
print(fruit)
Kiwi
Banana
Mango
fruitsTuple=("Kiwi","Banana","Mango")
for fruit in fruitsTuple:
if ('a' not in fruit):
print(fruit)
Kiwi
fruitsTuple=("Kiwi","Banana","Mango")
for fruit in fruitsTuple:
print("Fruit : {}, Length : {}".format(fruit,len(fruit)))
Fruit : Kiwi, Length : 4
Fruit : Banana, Length : 6
Fruit : Mango, Length : 5
#delete a given list
fruitsTuple=("Kiwi","Banana","Mango")
del fruitsTuple
print(fruitsTuple)
NameError: name 'fruitsTuple' is not defined
fruits1 = ("Apple","Kiwi","Grapes")
fruits2 = tuple(( "Mango","PineApple","Orange" ))
myBasket = fruits1 + fruits2
print(myBasket)
('Apple', 'Kiwi', 'Grapes', 'Mango', 'PineApple', 'Orange')
fruits1 = ("Apple","Kiwi","Grapes")
fruits2 = tuple(( "Mango","PineApple","Orange" ))
myBasket = fruits1 + fruits2
print(myBasket.count("Mango"))
1
Set: #No duplicates
mySet = {1,2,3}
print(mySet)
{1, 2, 3}
mySet = {"Arun","Prasad","Shiva","Raman"}
for name in mySet:
if 'a' not in name:
print(name)
Arun
mySet = {"Arun","Prasad","Shiva","Raman","Raman","Prasad","Arun"}
print(mySet)
{'Raman', 'Prasad', 'Shiva', 'Arun'}
names = set(( "A","B","C" ))
names.add("D")
print(names)
{'B', 'D', 'A', 'C'}
names = set(( "A","B","C" ))
names.add("D")
names.remove("A")
names.discard("B")
print(names)
{'C', 'D'}
#remove last item : pop
names = set(( "A","B","C" ))
names.pop() --C
names.pop() --B
names.pop() --A - not it empties
print(names)
set()
// remove all
names = set(( "A","B","C" ))
names.clear()
print(names)
set()
names = set(( "A","B","C" ))
del names
print(names)
NameError: name 'names' is not defined
fruits1 = {"Apple","Orange","Mango"}
fruits2 = set( ("Grapes","Kiwi","Lichi") )
myFruitsBasket = fruits1.union(fruits2)
print(myFruitsBasket)
{'Apple', 'Grapes', 'Mango', 'Orange', 'Kiwi', 'Lichi'}
fruits1 = {"Apple","Orange","Mango"}
fruits2 = set( ("Grapes","Kiwi","Lichi") )
myBasket=set( ("Pine","Custard"))
myBasket.update(fruits1)
myBasket.update(fruits2)
print(myBasket)
{'Orange', 'Mango', 'Kiwi', 'Custard', 'Grapes', 'Pine', 'Lichi', 'Apple'}
//Dictionary
coucaps = {
"India":"Delhi",
"Pakistan":"Islamabad",
"China":"Beijing",
"Srilanka":"Colombo"
}
print(coucaps)
{'India': 'Delhi', 'Pakistan': 'Islamabad', 'China': 'Beijing', 'Srilanka': 'Colombo'}
coucaps = {
"India":"Delhi",
"Pakistan":"Islamabad",
"China":"Beijing",
"Srilanka":"Colombo"
}
for k in coucaps.keys():
print(k)
India
Pakistan
China
Srilanka
coucaps = {
"India":"Delhi",
"Pakistan":"Islamabad",
"China":"Beijing",
"Srilanka":"Colombo"
}
print(coucaps["India"])
for capitals in coucaps.values():
print(capitals)
Delhi
Delhi
Islamabad
Beijing
Colombo
coucaps = {
"India":"Delhi",
"Pakistan":"Islamabad",
"China":"Beijing",
"Srilanka":"Colombo"
}
print(coucaps.get("India"))
Delhi
coucaps = {
"India":"Delhi",
"Pakistan":"Islamabad",
"China":"Beijing",
"Srilanka":"Colombo"
}
print(coucaps.get("NewZealand"))
None
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
print(filmdict["actor"])
print(filmdict.get("actor"))
அரவிந்த் சாமி
அரவிந்த் சாமி
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
for k in filmdict.keys():
print(k)
for v in filmdict.values():
print(v)
name
actor
year
Roja
அரவிந்த் சாமி
1992
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
for k in filmdict.keys():
print(filmdict[k])
Roja
அரவிந்த் சாமி
1992
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
for k, v in filmdict.items():
print(k,v)
name Roja
actor அரவிந்த் சாமி
year 1992
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
if "actor" in filmdict:
print(True)
True
print(len(filmdict)) ==> 3
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
#adding new element
filmdict["director"] = "ManiRatnam" #adding new key value pair
filmdict["actor"] = "AravindSwamy" #updating existing value
print(filmdict)
{'name': 'Roja', 'actor': 'AravindSwamy', 'year': 1992, 'director': 'ManiRatnam'}
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
filmdict.pop("actor") #remove specific item
del filmdict["name"] #delete specific item
print(filmdict)
{'year': 1992}
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
del filmdict
print(filmdict)
NameError: name 'filmdict' is not defined
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
filmdict.clear() // clear all values
print(filmdict) ==> {}
filmdict["name"] = "Kadhal Kottai"
filmdict["actor"] = "Ajith Kumar"
filmdict["year"] = 1996
print(filmdict)
{'name': 'Kadhal Kottai', 'actor': 'Ajith Kumar', 'year': 1996}
filmdict = {
"name": "Roja",
"actor": "அரவிந்த் சாமி",
"year": 1992
}
f = filmdict.copy()
print(f)
{'name': 'Roja', 'actor': 'அரவிந்த் சாமி', 'year': 1992}
Nested:
boy = {
"name":"Vijay Balaji",
"year" : 2001
}
girl = {
"name":"Aishvarya",
"year":2006
}
mykids = {
"boy" : boy,
"girl" : girl
}
print(boy)
print(girl)
print(mykids)
{'name': 'Vijay Balaji', 'year': 2001}
{'name': 'Aishvarya', 'year': 2006}
{'boy': {'name': 'Vijay Balaji', 'year': 2001}, 'girl': {'name': 'Aishvarya', 'year': 2006}}
boy = {
"name":"Vijay Balaji",
"year" : 2001
}
girl = {
"name":"Aishvarya",
"year":2006
}
mykids = {
"boy" : boy,
"girl" : girl
}
print(mykids["boy"]["name"])
print(mykids["girl"]["name"])
Vijay Balaji
Aishvarya
boy = {
"name":"Vijay Balaji",
"year" : 2001
}
girl = {
"name":"Aishvarya",
"year":2006
}
mykids = {
"boy" : boy,
"girl" : girl
}
print(boy.get("name"))
print(mykids.get("boy"))
print(mykids.get("boy").get("name"))
Vijay Balaji
{'name': 'Vijay Balaji', 'year': 2001}
Vijay Balaji
for x in range(6):
print(x)
0
1
2
3
4
5
for x in range(2, 6):
print(x)
2
3
4
5
for x in range(2, 30, 3):
print(x)
2
5
8
11
14
17
20
23
26
29
for x in range(6):
print(x)
else:
print("Finally finished!")
0
1
2
3
4
5
Finally finished!
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
def samplefunctionWithoutParameters():
print("Sample Function without parameters")
samplefunctionWithoutParameters()
Sample Function without parameters
def Hello(name):
print("Hello {}".format(name))
Hello("Raja")
Hello("Santhosh")
Hello("Udayappan")
Hello Raja
Hello Santhosh
Hello Udayappan
def Hello(name,city):
print("{} is coming from {}".format(name,city))
Hello("Sankara","Pallathur")
Hello("SenthilKumar","Kothamangalam")
Sankara is coming from Pallathur
SenthilKumar is coming from Kothamangalam
def Hello(name,city):
print("{} is coming from {}".format(name,city))
#Named parameters
Hello(city="Trichy",name="Ramesh")
Ramesh is coming from Trichy
#unknown number of length of parameters
def multiCount(*numbers):
print("First number : {}".format(numbers[0]), "Last number : {}".format(numbers[-1]))
multiCount(31,2,5,2,6,45)
First number : 31 Last number : 45
#default values passed
def multiNames(name1 = "Sara",name2="Lara", name3="Kala"):
print("Names #1 : {}, #2 : {}, #3 : {}".format(name1,name2,name3))
multiNames()
multiNames(name1="Sankara")
multiNames(name1="Suresh",name2="Rajesh")
multiNames(name3="Neela",name1="Laila",name2="Ashiq")
def myCars(cars):
for x in cars:
print(x)
listOfCars = list(("Lexus","Toyota", "Mazda","Subaru", "Kia","Infiniti","Audi","BMW"))
myCars(listOfCars)
Lexus
Toyota
Mazda
Subaru
Kia
Infiniti
Audi
BMW
def calculateCube(a):
return a * a * a
aCube = calculateCube(3)
print(aCube)
print(calculateCube(10))
print(calculateCube(9))
27
1000
729
result = lambda x : x + 10
print (result(3))
result = lambda a,b : a + b
print (result(1,2))
result = lambda a,b,c : a + b + c
print (result(1,2,3))
13
3
6
object oriented programming..
class MyClass:
name = "Siva"
age = 33
print("name : {}, age : {}".format(MyClass.name, MyClass.age))
name : Siva, age : 33
class Person:
name = "Siva" #Properties
age = 33
p = Person() #object
print("name : {}, age : {}".format(p.name, p.age))
name : Siva, age : 33
class Person:
def __init__(self, city,pin): # Constructor
self.city=city
self.pin=pin
p1 = Person("Pallathur",630107)
p2 = Person("Bangalore",560093)
p3 = Person("Hyderabad",500501)
p = list ((p1,p2,p3)) # Creating a list with 3 objects
for x in p:
print("City : {}, Pin : {}".format(x.city, x.pin))
City : Pallathur, Pin : 630107
City : Bangalore, Pin : 560093
City : Hyderabad, Pin : 500501
class Person:
def __init__(self, city,pin): # Constructor
self.city=city
self.pin=pin
def printTheValues(self):
print("City : {}, pin : {}".format(self.city,self.pin))
p1 = Person("Pallathur",630107)
p2 = Person("Bangalore",560093)
p3 = Person("Hyderabad",500501)
myList = list(( p1, p2, p3))
for p in myList:
p.printTheValues()
City : Pallathur, pin : 630107
City : Bangalore, pin : 560093
City : Hyderabad, pin : 500501
class Person:
def __init__(this, name, age):
this.name = name
this.age = age
def myfunc(this):
print("Hello my name is " + this.name)
p1 = Person("John", 36)
p1.myfunc()
Hello my name is John
class Person:
def __init__(self, city,pin): # Constructor
self.city=city
self.pin=pin
def printTheValues(self):
print("City : {}, pin : {}".format(self.city,self.pin))
p1 = Person("Pallathur",630107)
p2 = Person("Bangalore",560093)
p3 = Person("Hyderabad",500501)
p1.city="Chennai" # forcefully changing
p1.pin=600028 # changing
myList = list(( p1, p2, p3))
for p in myList:
p.printTheValues()
City : Chennai, pin : 600028
City : Bangalore, pin : 560093
City : Hyderabad, pin : 500501
names = ("Aishwarya", "Soundharya", "Latha")
myit = iter(names)
print(next(myit))
print(next(myit))
print(next(myit))
Aishwarya
Soundharya
Latha
city="Pallathur"
myIter = iter(city)
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
print(next(myIter))
P
a
l
l
a
t
h
u
r
names = ("Aishwarya", "Soundharya", "Latha")
for n in names:
print(n)
Aishwarya
Soundharya
Latha
city = "Pallathur"
for c in city:
print(c)
P
a
l
l
a
t
h
u
r
inheritance exa:
class Person:
def __init__(self, name, city):
self.name = name
self.city = city
def displayOutput(self):
print("Name : {}, City = {}".format(self.name,self.city))
x = Person("Sankara","Pallathur")
x.displayOutput()
Name : Sankara, City = Pallathur
class Person:
def __init__(self, name, city):
self.name = name
self.city = city
def displayOutput(self):
print("Name : {}, City = {}".format(self.name,self.city))
class Employee(Person): #inherting Person class
pass #inherit all properties, functions
objEmp = Employee("Raja","Kottaiyur") # creating instance of derived class
objEmp.displayOutput() #calling parent function
Name : Raja, City = Kottaiyur
class Person:
def __init__(self, name, city):
self.name = name
self.city = city
def displayOutput(self):
print("Name : {}, City = {}".format(self.name,self.city))
class Employee(Person):
def displayOutput(self): #overriding parent function within child
print("Cool Name : {}, Cool City = {}".format(self.name,self.city))
objEmp = Employee("Raja","Kottaiyur")
objEmp.displayOutput()
Cool Name : Raja, Cool City = Kottaiyur
scope example:
local variable within a function
def myfunc():
name="Raja"
print(name)
myfunc()
Raja
def myfunc():
name="Raja"
print("name : {}".format(name))
def insideFunc():
print("name within a function : {}".format(name))
insideFunc()
myfunc()
name : Raja
name within a function : Raja
name="Raja" #global variable declared outside of any function
print("name - global access outside function : {}".format(name))
def myfunc():
print("name : {}".format(name))
def insideFunc():
print("name within a function : {}".format(name))
insideFunc()
myfunc()
name - global access outside function : Raja
name : Raja
name within a function : Raja
name="Raja" #global variable declared outside of any function
print("name - global access outside function : {}".format(name))
def myfunc():
name = "Sanjay" #local 1
print("name : {}".format(name))
def insideFunc():
name = "Saro" #local 2
print("name within a function : {}".format(name))
insideFunc()
myfunc()
name - global access outside function : Raja
name : Sanjay
name within a function : Saro
global variable declared within a function:
def myfunc():
global name
name = "Sanjay" #local 1
print("name : {}".format(name))
def insideFunc():
print("name within a function : {}".format(name))
insideFunc()
myfunc()
print("name - global access outside function : {}".format(name))
name : Sanjay
name within a function : Sanjay
name - global access outside function : Sanjay
def myfunc():
global name
name = "Sanjay" #local 1
print("name : {}".format(name))
def insideFunc():
name = "Roja" #overriding global variable
print("name within a function : {}".format(name))
insideFunc()
myfunc()
print("name - global access outside function : {}".format(name))
name : Sanjay
name within a function : Roja
name - global access outside function : Sanjay
Python builtin module
import platform
x = dir(platform) #get sub functions of a given module
for y in x:
print(y)
DEV_NULL
_UNIXCONFDIR
_WIN32_CLIENT_RELEASES
_WIN32_SERVER_RELEASES
__builtins__
__cached__
__copyright__
__doc__
__file__
__loader__
__name__
__package__
__spec__
__version__
_codename_file_re
_comparable_version
_component_re
_default_architecture
_dist_try_harder
_distributor_id_file_re
_follow_symlinks
_ironpython26_sys_version_parser
_ironpython_sys_version_parser
_java_getprop
_libc_search
_linux_distribution
_lsb_release_version
_mac_ver_xml
_node
_norm_version
_parse_release_file
_platform
_platform_cache
_pypy_sys_version_parser
_release_file_re
_release_filename
_release_version
_supported_dists
_sys_version
_sys_version_cache
_sys_version_parser
_syscmd_file
_syscmd_uname
_syscmd_ver
_uname_cache
_ver_output
_ver_stages
architecture
collections
dist
java_ver
libc_ver
linux_distribution
mac_ver
machine
node
os
platform
popen
processor
python_branch
python_build
python_compiler
python_implementation
python_revision
python_version
python_version_tuple
re
release
subprocess
sys
system
system_alias
uname
uname_result
version
warnings
win32_ver
#builtin module example
import platform
print("OS : {}".format(platform.system()))
print("OS Version : {}".format(platform.version()))
print("Python Version : {}".format(platform.python_version()))
User defined modules:
create a module and store it in a file system and name it as : hello.py
# stored in : C:\pyEx\hello.py
def SayHai(name):
print("Hai : {}".format(name))
Create a python program and store it in a file system and name it as : silva.py
# stored in : C:\pyEx\silva.py
import hello # importing a module
hello.SayHai("Silva")
import hello as h #alias name for the imported module
h.SayHai("Lara")
run the program in console
C:\pyEx>python silva.py
Hai : Silva
Hai : Lara
vars.py:
#all variables declared and assigned here
name="Raja"
city="Kottaiyur"
raja.py
#import and use vars.py
import vars
print("Name : {}, City : {}".format(vars.name,vars.city))
import vars as v
print("Name : {}, City : {}".format(v.name,v.city))
C:\pyEx>python raja.py
Name : Raja, City : Kottaiyur
Name : Raja, City : Kottaiyur
partial import example:
myModule.py:
name = "Silva"
city="Colombo"
def printThis(msg,n):
for i in range(n):
print("Message#{} : {}".format(i,msg))
called.py:
from myModule import printThis #partial import
printThis("Super Cool",10)
C:\pyEx>python called.py
Message#0 : Super Cool
Message#1 : Super Cool
Message#2 : Super Cool
Message#3 : Super Cool
Message#4 : Super Cool
Message#5 : Super Cool
Message#6 : Super Cool
Message#7 : Super Cool
Message#8 : Super Cool
Message#9 : Super Cool
import json
# some JSON:
person ='{ "name":"Sankara","age":"20","city":"Singapore","network":"StarHub"}'
# parse x:
y = json.loads(person)
# the result is a Python dictionary:
print(y)
name = y['name']
age = y['age']
city = y['city']
network = y['network']
print("Name : {}, Age : {}, City : {}, Network : {}".format(name,age,city,network))
{'name': 'Sankara', 'age': '20', 'city': 'Singapore', 'network': 'StarHub'}
Name : Sankara, Age : 20, City : Singapore, Network : StarHub
import json
# a Python object (dict):
Person = [
{
"name": "Siva",
"age": 35,
"city": "Chennai"
},
{
"name": "Arun",
"age": 23,
"city": "Bangalore"
}
]
# convert into JSON:
x = json.dumps(Person)
print(x)
x = json.dumps(Person,indent=4,, sort_keys=True)
print(x)
[{"name": "Siva", "age": 35, "city": "Chennai"}, {"name": "Arun", "age": 23, "city": "Bangalore"}]
[
{
"age": 35,
"city": "Chennai",
"name": "Siva"
},
{
"age": 23,
"city": "Bangalore",
"name": "Arun"
}
]
Install a package:
pip install camelcase
C:\Users\tamil>pip install camelcase
Collecting camelcase
Downloading https://files.pythonhosted.org/packages/24/54/6bc20bf371c1c78193e2e4179097a7b779e56f420d0da41222a3b7d87890/camelcase-0.2.tar.gz
Building wheels for collected packages: camelcase
Running setup.py bdist_wheel for camelcase ... done
Stored in directory: C:\Users\tamil\AppData\Local\pip\Cache\wheels\b1\fe\08\84d2143069bc44c20127c38cc1bf202332319b3da7315ca766
Successfully built camelcase
Installing collected packages: camelcase
Successfully installed camelcase-0.2
camelExa.py:
import camelcase
c = camelcase.CamelCase()
inputStr = "i love all beautious things"
result = c.hump(inputStr)
print(result)
C:\pyEx>python camelExa.py
I Love All Beautious Things
C:\pyEx>python camelExa.py
I Love All Beautious Things
Uninstall a package:
C:\pyEx>pip uninstall camelcase
Uninstalling camelcase-0.2:
Would remove:
c:\programdata\anaconda3\lib\site-packages\camelcase-0.2.dist-info\*
c:\programdata\anaconda3\lib\site-packages\camelcase\*
Proceed (y/n)? y
Successfully uninstalled camelcase-0.2
List packages:
C:\pyEx>pip list
Package Version
---------------------------------- ----------
alabaster 0.7.12
anaconda-client 1.7.2
anaconda-navigator 1.9.12
anaconda-project 0.8.2
....
XlsxWriter 1.1.2
xlwings 0.15.1
xlwt 1.3.0
xmltodict 0.12.0
zict 0.1.3
Try.. catch.. finally is now : try... except... finally
try:
a = 10
b = 0
c = a/b
print(c)
except:
print("Generic Error message")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Generic Error message
This is always executed
try:
a = 10
b = 0
c = a/b
print(c)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Can't divide by zero
This is always executed
try:
a = 10
b = 3
c = a/b
print(c)
except:
print("Generic Error message") #no exception occured.
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
3.3333333333333335
This is always executed
#The try block will generate an error, because x is not defined:
try:
print(a)
except:
print("An exception occurred")
An exception occurred
try:
print(a)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Variable x is not defined
try:
print("Welcome to India")
except:
print("Something went wrong")
else:
print("Nothing went wrong") # this will get executed
Welcome to India
Nothing went wrong
try:
print(a)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Something went wrong
The 'try except' is finished
sample.txt:
I love India
fileExa.py:
try:
f = open("C:\pyEx\sample.txt")
f.write("I love Singapore")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
C:\pyEx>python fileExa.py
Something went wrong when writing to the file
Raise:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
x = "Roja"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
Read inputs from user:
>>> first_name = input("Enter first name : ")
Enter first name : Sankara
>>> last_name = input("Enter last name : ")
Enter last name : Narayanan
>>> print("{} {}".format(first_name,last_name))
Sankara Narayanan
inputExa.py:
a = input("Enter first number : ")
b = input("Enter second number : ")
c = input("Enter 3rd number : ")
result = int(a) + int(b) + int(c)
print("{}+{}+{}={}".format(a,b,c,result))
C:\pyEx>python inputExa.py
Enter first number : 1
Enter second number : 3
Enter 3rd number : 6
1+3+6=10
PersonExa.py:
class Person:
def __init__(self,name,age,city):
self.name = name
self.age=age
self.city=city
def printPerson(self):
print("Name : {}, Age : {}, City : {}".format(self.name,self.age,self.city))
n = input("Enter name : ")
a = input("Enter age : ")
c = input("Enter city : ")
p = Person(n,a,c)
p.printPerson()
C:\pyEx>python PersonExa.py
Enter name : sara
Enter age : 33
Enter city : Pallathur
Name : sara, Age : 33, City : Pallathur
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
I have a Ford, it is a Mustang.
read a file located in a folder:
f = open("C:\pyEx\story.txt","r")
result = f.read()
print(result)
C:\pyEx>python file1.py
Deep in Kansas, darkly dressed, William S. Burroughs, a man who shot his
wife in the head and waged war against a lifetime of guilt, who has sucked
up every drug imaginable and survived, and who has made a fine career out
of depravity, can't on this particular afternoon take another moment of a
simple midwestern housefly buzzing around his head. ``I can't stand
flies,'' grumbles the seventy-seven-year-old author in that distinctively
sepulchral voice, which retains a vestige of his St. Louis roots despite
his many years on another planet. The fly swoops down onto Burroughs's
plate of cookies. ``Terrible,'' Burroughs exclaims, exasperated, attempting
to backhand the fly into oblivion.
``William, that's my pet fly!'' cries David Cronenberg, a man who may love
insects but not necessarily people, the director who is perhaps best known
for turning Jeff Goldblum from scientist into bug in the 1986 remake of
~The Fly~.
``Now, Julius, I told you not to bother people,'' Cronenberg commands the
fly. ``Not everyone likes flies.''
Not everyone likes giant meat-eating Brazilian aquatic centipedes either,
but they're featured prominently in Cronenberg's current film of
Burroughs's chilling masterpiece of a novel, ~Naked Lunch~. Now that the
movie is in the can and Burroughs is out of the hospital after having
undergone triple-bypass heart surgery, Cronenberg has showed up in
Lawrence, Kansas, Burroughs's hometown of the last ten years, to pay his
respects to the laconic sage. With two examples of evil incarnate wandering
around town at the same time, Lawrence suddenly seems like a haven for
drug-crazed refugees escaping the Interzone, the fictional horrorscape of
Burroughs's ~Naked Lunch~.
f = open("C:\pyEx\story.txt","r")
result = f.read((5))
print(result)
C:\pyEx>python file1.py
Deep
f = open("C:\pyEx\story.txt","r")
print(f.readline())
C:\pyEx>python file1.py
Deep in Kansas, darkly dressed, William S. Burroughs, a man who shot his
f = open("C:\pyEx\story.txt","r")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
C:\pyEx>python file1.py
Deep in Kansas, darkly dressed, William S. Burroughs, a man who shot his
wife in the head and waged war against a lifetime of guilt, who has sucked
up every drug imaginable and survived, and who has made a fine career out
of depravity, can't on this particular afternoon take another moment of a
simple midwestern housefly buzzing around his head. ``I can't stand
f = open("C:\pyEx\story.txt","r")
for line in f:
print(line)
f = open("C:\pyEx\story.txt","r")
print(f.readline())
f.close()
C:\pyEx>python file1.py
Deep in Kansas, darkly dressed, William S. Burroughs, a man who shot his
f = open("awesomefile.txt", "a") #append mode
f.write("Sample line content...")
f.close()
#open and read the file after the appending:
f = open("awesomefile.txt", "r")
print(f.read())
C:\pyEx>python file1.py
Sample line content...
f = open("awesomefile.txt", "w") #overwrite mode3
f.write("Something interesting")
f.close()
#open and read the file after the appending:
f = open("awesomefile.txt", "r")
print(f.read())
C:\pyEx>python file1.py
Something interesting
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file doesn't exist!")
f = open("myfile.txt","x") #create a file
f.write("New content ")
f.close()
f = open("myfile.txt","r")
print(f.read())
f.close()
C:\pyEx>python file1.py
The file doesn't exist!
New content
import os #delete a folder
os.rmdir("myfolder")
No comments:
Post a Comment