pythonlearningpot
Monday, 21 August 2017
Sunday, 6 August 2017
Tuesday, 4 July 2017
python programs on basic datatypes operators conditionals and loops
Basic data types
Questions
1. a=4
b='string'
print a+b
what is the error in the above program? Please correct the error.
Find out the output and its type of the following statements.
int(5.0)
float(5)
str(7)
int("")
str(7.0)
float("5.0")
int("five")
Write a program to check a character in a string.
Note: Take a string of your wish.
Consider you have 22 apples,20 bananas,30 carrots. Create variables for each fruit and print the output as follows,
I have 22 apples 20 bananas 30 carrots.
Note:In place of number use the variable.
Answer the following questions.
Which function used for the address of a variable?
Which function used to know whether a given variable is keyword?
Which function used to convert object into an expression string?
Which function used to find maximum size that integer can take?
Answers:
1.
cannot concatenate string with integer.
print str(a)+b
2.
Ans :
5 integer
5.0 floating point
7 string
error (invalid literal for int)
7.0 string
5.0 float
error
3.
#!/usr/bin/python
x="python"
ch='t'
print ch in x
Note: Output will be 'True' if character found otherwise 'False'
4.
#!/usr/bin/python
apple=22
banana=20
carrot=30
print "I have "+str(apple)+" apples "+str(banana)+" bananas "+str(carrot)+" carrots."
5.
id(variablename)
keyword.iskeyword(name)
repr(word)
sys.maxint
------------------------------------------------------------------------------------------------------------------
How user interact with the application? - I/O operations
Write a program to print absolute value of a given number.
Write a program to find the type of the given input.
Write a program to to take input and convert it into cube at input() function only and print the output.
Write a program to check whether given input is a prime number.
Write a program that prints output in the same line each value seperated by -.
like 1-4-5-g-6-8.0 e.t.c.,
---------------------------------------------------------------------------------------------------------------------------
Answers:
1.
#!/usr/bin/python
x=float(input('enter input'))
if x>=0:
print ("absolute value of", x ,"is",x)
else:
print ("absolute value of", x, "is",-x)
2.
#!/usr/bin/python
x=input('Enter input':)
print (type(x))
if type(x)==type(""):
print ("It is a string")
elif type(x)==type(1):
print ("It is an integer")
elif type(x)==type(1.0):
print ("It is a floating point")
else:
print ("It is other than integer,floating point and string")
3.
#!/usr/bin/python
x=(lambda x:x*x*x)(input('enter'))
print x
4.
#!/usr/bin/python
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
s='False'
break
else:
s='True'
else:
print(num,"is not a positive number")
if s=='False':
print(num,"is not a prime number")
else:
print(num,"is a prime number")
5.
#!/usr/bin/python
li=[1,4,5,'g',6,8.0]
i=0
for k in li:
if i!=(len(li)-1):
print (k,end="-")
i+=1
else:
print (k)
-----------------------------------------------------------------------------------------------------
how to execute a block of statements repetitively – loop structures
Write a program to print even numbers less than 100
Write a program to print prime numbers less than 100 using for else statement
Write a program to print output as following
^ ^ ^ ^ ^
^ ^ ^ ^
^ ^ ^
^ ^
^
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^
-----------------------------------------------------------------------------------------------------------------------
Write a program to find whether a given number is palindrome or not
Write a program to display multiplicaion table for a given number
Ex: number is 12
Then 12*1=12
12*2=24
and so on.
Answers:
1.
#!/usr/bin/python
for x in range(2,101,2):
print (x)
2.
#!/usr/bin/python
for num in range(1,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
break
3.
#!/usr/bin/python
for i in range(5,0,-1):
for j in range(0,i):
print '^',
print
for i in range(1,6):
for j in range(0,i):
print '^',
print
4.
#!/usr/bin/python
x=int(input('Enter number'))
z=""
p=x
while x!=0:
y=x%10
z+=str(y)
print (z)
x=int(x/10)
if str(p)==z:
print ("It is a palindrome")
else:
print ("It is not a palindrome")
5.
#!/usr/bin/python
x=int(input('enter number'))
for i in range(1,11):
print (x,"*",i,"=",x*i)
Questions
1. a=4
b='string'
print a+b
what is the error in the above program? Please correct the error.
Find out the output and its type of the following statements.
int(5.0)
float(5)
str(7)
int("")
str(7.0)
float("5.0")
int("five")
Write a program to check a character in a string.
Note: Take a string of your wish.
Consider you have 22 apples,20 bananas,30 carrots. Create variables for each fruit and print the output as follows,
I have 22 apples 20 bananas 30 carrots.
Note:In place of number use the variable.
Answer the following questions.
Which function used for the address of a variable?
Which function used to know whether a given variable is keyword?
Which function used to convert object into an expression string?
Which function used to find maximum size that integer can take?
Answers:
1.
cannot concatenate string with integer.
print str(a)+b
2.
Ans :
5 integer
5.0 floating point
7 string
error (invalid literal for int)
7.0 string
5.0 float
error
3.
#!/usr/bin/python
x="python"
ch='t'
print ch in x
Note: Output will be 'True' if character found otherwise 'False'
4.
#!/usr/bin/python
apple=22
banana=20
carrot=30
print "I have "+str(apple)+" apples "+str(banana)+" bananas "+str(carrot)+" carrots."
5.
id(variablename)
keyword.iskeyword(name)
repr(word)
sys.maxint
------------------------------------------------------------------------------------------------------------------
How user interact with the application? - I/O operations
Write a program to print absolute value of a given number.
Write a program to find the type of the given input.
Write a program to to take input and convert it into cube at input() function only and print the output.
Write a program to check whether given input is a prime number.
Write a program that prints output in the same line each value seperated by -.
like 1-4-5-g-6-8.0 e.t.c.,
---------------------------------------------------------------------------------------------------------------------------
Answers:
1.
#!/usr/bin/python
x=float(input('enter input'))
if x>=0:
print ("absolute value of", x ,"is",x)
else:
print ("absolute value of", x, "is",-x)
2.
#!/usr/bin/python
x=input('Enter input':)
print (type(x))
if type(x)==type(""):
print ("It is a string")
elif type(x)==type(1):
print ("It is an integer")
elif type(x)==type(1.0):
print ("It is a floating point")
else:
print ("It is other than integer,floating point and string")
3.
#!/usr/bin/python
x=(lambda x:x*x*x)(input('enter'))
print x
4.
#!/usr/bin/python
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
s='False'
break
else:
s='True'
else:
print(num,"is not a positive number")
if s=='False':
print(num,"is not a prime number")
else:
print(num,"is a prime number")
5.
#!/usr/bin/python
li=[1,4,5,'g',6,8.0]
i=0
for k in li:
if i!=(len(li)-1):
print (k,end="-")
i+=1
else:
print (k)
-----------------------------------------------------------------------------------------------------
how to execute a block of statements repetitively – loop structures
Write a program to print even numbers less than 100
Write a program to print prime numbers less than 100 using for else statement
Write a program to print output as following
^ ^ ^ ^ ^
^ ^ ^ ^
^ ^ ^
^ ^
^
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^
-----------------------------------------------------------------------------------------------------------------------
Write a program to find whether a given number is palindrome or not
Write a program to display multiplicaion table for a given number
Ex: number is 12
Then 12*1=12
12*2=24
and so on.
Answers:
1.
#!/usr/bin/python
for x in range(2,101,2):
print (x)
2.
#!/usr/bin/python
for num in range(1,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
break
3.
#!/usr/bin/python
for i in range(5,0,-1):
for j in range(0,i):
print '^',
for i in range(1,6):
for j in range(0,i):
print '^',
4.
#!/usr/bin/python
x=int(input('Enter number'))
z=""
p=x
while x!=0:
y=x%10
z+=str(y)
print (z)
x=int(x/10)
if str(p)==z:
print ("It is a palindrome")
else:
print ("It is not a palindrome")
5.
#!/usr/bin/python
x=int(input('enter number'))
for i in range(1,11):
print (x,"*",i,"=",x*i)
Saturday, 1 July 2017
FILE OPERATIONS WITH JSON TEXT EXCEL OBJECT DATA
file object = open(file_name [, access_mode][, buffering])
Modes:
r read
r+ read,write
rb read binary
rw read,write
w write
w+ write,read
wb write binary
a append
a+ append,read
---------------------------------
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
--------------------------------------
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
---------------------------------
There are two important sources, which provide a wide range of utility methods to handle and manipulate files and directories on Windows and Unix operating systems. They are as follows:
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
1. file.close() Close the file.
A closed file cannot be read or written any more.
2 file.flush() Flush the internal buffer, like stdio's fflush.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O operations
from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
5 file.next() Returnss the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
7 file.readline([size]) Reads one entire line from the file.
A trailing newline character is kept in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines.
9 file.seek(offset[,whence]) Sets the file's current position.
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
13 file.writelines
>>> os.getcwd()
'C:\\Python27'
>>> os.path.abspath("bdps.txt")
'C:\\Python27\\bdps.txt'
>>> os.path.isdir("prog")
True
>>> os.listdir(cwd)
>>> os.listdir('c:\\Python27')
----------------------------------------------------------------------------------
Syntax
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
----------------------------------------------------------------------
You need to read or write text data, possibly in different text encodings such as ASCII, UTF-8, or
UTF-16.
with open('somefile.txt', 'rt') as f:
data = f.read()
-------------------------------------------------------------------------------
By default, files are read/written using the system default text encoding, as can be found in
sys.getdefaultencoding(). On most machines, this is set to utf-8. If you know that the text you are
reading or writing is in a different encoding, supply the optional encoding parameter to open().
binary data:
>>> import array
>>> nums=array.array('i',[1,2,3,4])
>>> with open('data.bin','wb') as f:
f.write(nums)
The gzip and bz2 modules make it easy to work with such files. Both modules provide an alternative
implementation of open() that can be used for this purpose.
# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
Use the os.listdir() function to obtain a list of files in a directory:
import os
names = os.listdir('somedir')
pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')]
import glob
pyfiles = glob.glob('somedir/*.py')
-----------------------------------------------------------------------------
You want to read and write data over a serial port, typically to interact with some kind of hardware
device (e.g., a robot or sensor).
serial communication is to use the pySerial package.
Getting started with the package is very easy.
You simply open up a serial port using code like this:
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
The device name will vary according to the kind of device and operating system. For instance, on
Windows, you can use a device of 0, 1, and so on, to open up the communication ports such as
“COM0” and “COM1.” Once open, you can read and write data using read(), readline(), and write()
calls.
-------------------------------------
You need to serialize a Python object into a byte stream so that you can do things such as save it to a
file, store it in a database, or transmit it over a network connection.
-----------------------------------------------------
>>> import pickle
>>> data={'sno':1,'sname':"ww"}
>>> f=open('dump2','wb')
>>> pickle.dump(data,f)
>>> s=pickle.dumps(data)
>>> f=open('dump2','rb')
>>> data=pickle.load(f)
>>> print data
{'sno': 1, 'sname': 'ww'}
>>> data=pickle.loads(s)
>>> print data
{'sno': 1, 'sname': 'ww'}
-------------------------------------------------------------
>>> import pickle
>>> f = open('somedata', 'wb')
>>> pickle.dump([1, 2, 3, 4], f)
>>> pickle.dump('hello', f)
>>> pickle.dump({'Apple', 'Pear', 'Banana'}, f)
>>> f.close()
>>> f = open('somedata', 'rb')
>>> pickle.load(f)
[1, 2, 3, 4]
>>> pickle.load(f)
'hello'
>>> pickle.load(f)
{'Apple', 'Pear', 'Banana'}
>>>
--------------------------------------------------------
process csv data::
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.reader(f)
headers=next(f1)
for row in f1:
print row
---------------------------------------------------------
-----------------------
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.DictReader(f)
for row in f1:
print row
------------------------------------------------
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
--------------------------------------------------
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
--------------------------------------------------------------
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
------------------------------------------------
with open('data.json', 'w') as f:
json.dump(data, f)
---------------------------------------
with open('data.json', 'r') as f:
data = json.load(f)
----------------------------------------------------------
>>> from urllib.request import urlopen
>>> import json
>>> u = urlopen('http://search.twitter.com/search.json?q=python&rpp=5')
>>> resp = json.loads(u.read().decode('utf-8'))
>>> from pprint import pprint
>>> pprint(resp)
---------------------------------------------------
>>> s = '{"name": "ACME", "shares": 50, "price": 490.1}'
>>> from collections import OrderedDict
>>> data = json.loads(s, object_pairs_hook=OrderedDict)
>>> data
OrderedDict([('name', 'ACME'), ('shares', 50), ('price', 490.1)])
-------------------------------------------------------
xml data::
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
print()
Modes:
r read
r+ read,write
rb read binary
rw read,write
w write
w+ write,read
wb write binary
a append
a+ append,read
---------------------------------
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
--------------------------------------
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
---------------------------------
There are two important sources, which provide a wide range of utility methods to handle and manipulate files and directories on Windows and Unix operating systems. They are as follows:
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
1. file.close() Close the file.
A closed file cannot be read or written any more.
2 file.flush() Flush the internal buffer, like stdio's fflush.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O operations
from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
5 file.next() Returnss the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
7 file.readline([size]) Reads one entire line from the file.
A trailing newline character is kept in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines.
9 file.seek(offset[,whence]) Sets the file's current position.
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
13 file.writelines
>>> os.getcwd()
'C:\\Python27'
>>> os.path.abspath("bdps.txt")
'C:\\Python27\\bdps.txt'
>>> os.path.isdir("prog")
True
>>> os.listdir(cwd)
>>> os.listdir('c:\\Python27')
----------------------------------------------------------------------------------
Syntax
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
----------------------------------------------------------------------
You need to read or write text data, possibly in different text encodings such as ASCII, UTF-8, or
UTF-16.
with open('somefile.txt', 'rt') as f:
data = f.read()
-------------------------------------------------------------------------------
By default, files are read/written using the system default text encoding, as can be found in
sys.getdefaultencoding(). On most machines, this is set to utf-8. If you know that the text you are
reading or writing is in a different encoding, supply the optional encoding parameter to open().
binary data:
>>> import array
>>> nums=array.array('i',[1,2,3,4])
>>> with open('data.bin','wb') as f:
f.write(nums)
The gzip and bz2 modules make it easy to work with such files. Both modules provide an alternative
implementation of open() that can be used for this purpose.
# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
Use the os.listdir() function to obtain a list of files in a directory:
import os
names = os.listdir('somedir')
pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')]
import glob
pyfiles = glob.glob('somedir/*.py')
-----------------------------------------------------------------------------
You want to read and write data over a serial port, typically to interact with some kind of hardware
device (e.g., a robot or sensor).
serial communication is to use the pySerial package.
Getting started with the package is very easy.
You simply open up a serial port using code like this:
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
The device name will vary according to the kind of device and operating system. For instance, on
Windows, you can use a device of 0, 1, and so on, to open up the communication ports such as
“COM0” and “COM1.” Once open, you can read and write data using read(), readline(), and write()
calls.
-------------------------------------
You need to serialize a Python object into a byte stream so that you can do things such as save it to a
file, store it in a database, or transmit it over a network connection.
-----------------------------------------------------
>>> import pickle
>>> data={'sno':1,'sname':"ww"}
>>> f=open('dump2','wb')
>>> pickle.dump(data,f)
>>> s=pickle.dumps(data)
>>> f=open('dump2','rb')
>>> data=pickle.load(f)
>>> print data
{'sno': 1, 'sname': 'ww'}
>>> data=pickle.loads(s)
>>> print data
{'sno': 1, 'sname': 'ww'}
-------------------------------------------------------------
>>> import pickle
>>> f = open('somedata', 'wb')
>>> pickle.dump([1, 2, 3, 4], f)
>>> pickle.dump('hello', f)
>>> pickle.dump({'Apple', 'Pear', 'Banana'}, f)
>>> f.close()
>>> f = open('somedata', 'rb')
>>> pickle.load(f)
[1, 2, 3, 4]
>>> pickle.load(f)
'hello'
>>> pickle.load(f)
{'Apple', 'Pear', 'Banana'}
>>>
--------------------------------------------------------
process csv data::
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.reader(f)
headers=next(f1)
for row in f1:
print row
---------------------------------------------------------
-----------------------
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.DictReader(f)
for row in f1:
print row
------------------------------------------------
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
--------------------------------------------------
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
--------------------------------------------------------------
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
------------------------------------------------
with open('data.json', 'w') as f:
json.dump(data, f)
---------------------------------------
with open('data.json', 'r') as f:
data = json.load(f)
----------------------------------------------------------
>>> from urllib.request import urlopen
>>> import json
>>> u = urlopen('http://search.twitter.com/search.json?q=python&rpp=5')
>>> resp = json.loads(u.read().decode('utf-8'))
>>> from pprint import pprint
>>> pprint(resp)
---------------------------------------------------
>>> s = '{"name": "ACME", "shares": 50, "price": 490.1}'
>>> from collections import OrderedDict
>>> data = json.loads(s, object_pairs_hook=OrderedDict)
>>> data
OrderedDict([('name', 'ACME'), ('shares', 50), ('price', 490.1)])
-------------------------------------------------------
xml data::
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
print()
BASIC DATA TYPES AND OPERATORS SUPPORTED IN PYTHON
Questions
1. a=4
b='string'
print a+b
what is the error in the above program? Please correct the error.
Find out the output and its type of the following statements.
int(5.0)
float(5)
str(7)
int("")
str(7.0)
float("5.0")
int("five")
Write a program to check a character in a string.
Note: Take a string of your wish.
Consider you have 22 apples,20 bananas,30 carrots. Create variables for each fruit and print the output as follows,
I have 22 apples 20 bananas 30 carrots.
Note:In place of number use the variable.
Answer the following questions.
Which function used for the address of a variable?
Which function used to know whether a given variable is keyword?
Which function used to convert object into an expression string?
Which function used to find maximum size that integer can take?
Answers:
1.
cannot concatenate string with integer.
print str(a)+b
2.
Ans :
5 integer
5.0 floating point
7 string
error (invalid literal for int)
7.0 string
5.0 float
error
3.
#!/usr/bin/python
x="python"
ch='t'
print ch in x
Note: Output will be 'True' if character found otherwise 'False'
4.
#!/usr/bin/python
apple=22
banana=20
carrot=30
print "I have "+str(apple)+" apples "+str(banana)+" bananas "+str(carrot)+" carrots."
5.
id(variablename)
keyword.iskeyword(name)
repr(word)
sys.maxint
Operators supported for data manipulation and comparison
Consider a=4,b=6,c=10.Now write a program to have all the arithmetic operations(+,-,*,/,%,**,//) between them. For ex:a+b+c and also find the output.
Consider a=27,b=63.Now write a program that has all bitwise operations and also find the output.
Consider a=7,b=5. Now,check whether a is greater than b if so increment it by 1.
Consider a=5 What is the output of the following a<<3,a>>3,a>>2 and a<<2.
A man has taken a debt of 200 R.S. Write a program to find simple interest after 2 years with rate of interest=3% and what is the Interest?
Answers:
1 Ans.
Operator Output
+ 20
- -12
* 240
/ 0
% 4
** Infinity
// 0
2 Ans.
Operator Output
& 27
| 63
^ 36
~a -28
a<<2 108
a>>2 6
3 Ans.
#!/usr/bin/python
a=7
b=5
if a>b:
print "a is greater than b and the value of a becomes",a+1
elif a==b:
print "a is equal to b"
else:
print "a is smaller than b"
4 Ans.
0
40
1
20
5.
#!/usr/bin/python
p=200
t=2
r=3
si=p*t*r/100
print si
The interest is 12 R.S.
1. a=4
b='string'
print a+b
what is the error in the above program? Please correct the error.
Find out the output and its type of the following statements.
int(5.0)
float(5)
str(7)
int("")
str(7.0)
float("5.0")
int("five")
Write a program to check a character in a string.
Note: Take a string of your wish.
Consider you have 22 apples,20 bananas,30 carrots. Create variables for each fruit and print the output as follows,
I have 22 apples 20 bananas 30 carrots.
Note:In place of number use the variable.
Answer the following questions.
Which function used for the address of a variable?
Which function used to know whether a given variable is keyword?
Which function used to convert object into an expression string?
Which function used to find maximum size that integer can take?
Answers:
1.
cannot concatenate string with integer.
print str(a)+b
2.
Ans :
5 integer
5.0 floating point
7 string
error (invalid literal for int)
7.0 string
5.0 float
error
3.
#!/usr/bin/python
x="python"
ch='t'
print ch in x
Note: Output will be 'True' if character found otherwise 'False'
4.
#!/usr/bin/python
apple=22
banana=20
carrot=30
print "I have "+str(apple)+" apples "+str(banana)+" bananas "+str(carrot)+" carrots."
5.
id(variablename)
keyword.iskeyword(name)
repr(word)
sys.maxint
Operators supported for data manipulation and comparison
Consider a=4,b=6,c=10.Now write a program to have all the arithmetic operations(+,-,*,/,%,**,//) between them. For ex:a+b+c and also find the output.
Consider a=27,b=63.Now write a program that has all bitwise operations and also find the output.
Consider a=7,b=5. Now,check whether a is greater than b if so increment it by 1.
Consider a=5 What is the output of the following a<<3,a>>3,a>>2 and a<<2.
A man has taken a debt of 200 R.S. Write a program to find simple interest after 2 years with rate of interest=3% and what is the Interest?
Answers:
1 Ans.
Operator Output
+ 20
- -12
* 240
/ 0
% 4
** Infinity
// 0
2 Ans.
Operator Output
& 27
| 63
^ 36
~a -28
a<<2 108
a>>2 6
3 Ans.
#!/usr/bin/python
a=7
b=5
if a>b:
print "a is greater than b and the value of a becomes",a+1
elif a==b:
print "a is equal to b"
else:
print "a is smaller than b"
4 Ans.
0
40
1
20
5.
#!/usr/bin/python
p=200
t=2
r=3
si=p*t*r/100
print si
The interest is 12 R.S.
WHO USES PYTHON ? WHY PYTHON
Who Uses Python Today?
--------------------------------
.Google makes extensive use of Python in its web search systems.
• The popular YouTube video sharing service is largely written in Python.
• The Dropbox storage service codes both its server and desktop client software primarily
in Python.
• The Raspberry Pi single-board computer promotes Python as its educational language.
• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses
Python broadly.
• The widespread BitTorrent peer-to-peer file sharing system began its life as a
Python program.
• Industrial Light & Magic, Pixar, and others use Python in the production of animated
movies.
• ESRI uses Python as an end-user customization tool for its popular GIS mapping
products.
• Google’s App Engine web development framework uses Python as an application
language.
• The IronPort email server product uses more than 1 million lines of Python code
to do its job.
• Maya, a powerful integrated 3D modeling and animation system, provides a
Python scripting API.
• The NSA uses Python for cryptography and intelligence analysis.
• iRobot uses Python to develop commercial and military robotic devices.
Who Uses Python Today? | 9
www.it-ebooks.info
• The Civilization IV game’s customizable scripted events are written entirely in
Python.
• The One Laptop Per Child (OLPC) project built its user interface and activity model
in Python.
• Netflix and Yelp have both documented the role of Python in their software infrastructures.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.
• JPMorgan Chase, UBS, Getco, and Citadel apply Python to financial market forecasting.
• NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming
tasks.
------------------------------------------------------------------------
What Can I Do with Python?
------------------------------------------------------------------------
Systems Programming:
Python’s built-in interfaces to operating-system services make it ideal for writing
portable, maintainable system-administration tools and utilities (sometimes called shell
tools). Python programs can search files and directory trees, launch other programs, do
parallel processing with processes and threads, and so on.
GUIs:
Python’s simplicity and rapid turnaround also make it a good match for graphical user
interface programming on the desktop. Python comes with a standard object-oriented
interface to the Tk GUI API called tkinter (Tkinter in 2.X) that allows Python programs
to implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged
on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS
(both Classic and OS X).
Internet Scripting:
Python comes with standard Internet modules that allow Python programs to perform
a wide variety of networking tasks, in client and server modes. Scripts can communicate
over sockets; extract form information sent to server-side CGI scripts; transfer files by
FTP; parse and generate XML and JSON documents; send, receive, compose, and parse
In addition, full-blown web development framework packages for Python, such as
Django, TurboGears, web2py, Pylons, Zope, and WebWare, support quick construction
of full-featured and production-quality websites with Python.
Database Programming:
For traditional database demands, there are Python interfaces to all commonly used
relational database systems—Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL,SQLite, and more. The Python world has also defined a portable database API for accessing
SQL database systems from Python scripts
Rapid Prototyping
To Python programs, components written in Python and C look the same. Because of
this, it’s possible to prototype systems in Python initially, and then move selected components
to a compiled language such as C or C++ for delivery.
Numeric and Scientific Programming
And More: Gaming, Images, Data Mining, Robots, Excel...
• Game programming and multimedia with pygame, cgkit, pyglet, PySoy,
Panda3D, and others
• Serial port communication on Windows, Linux, and more with the PySerial extension
• Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya,
and more
• Robot control programming with the PyRo toolkit
• Natural language analysis with the NLTK package
• Instrumentation on the Raspberry Pi and Arduino boards
• Mobile computing with ports of Python to the Google Android and Apple iOS
platforms
• Excel spreadsheet function and macro programming with the PyXLL or DataNitro
add-ins
• Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow,
and more
• Artificial intelligence with the PyBrain neural net library and the Milk machine
learning toolkit
• Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog
• Network monitoring with zenoss, written in and customized with Python
• Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD,
and others
• Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF,
and so on
• Data visualization with Mayavi, matplotlib, VTK, VPython, and more
• XML parsing with the xml library package, the xmlrpclib module, and third-party
extensions
• JSON and CSV file processing with the json and csv modules
--------------------------------------------------------------------
Python is available on:
• Linux and Unix systems
• Microsoft Windows (all modern flavors)
• Mac OS (both OS X and Classic)
• BeOS, OS/2, VMS, and QNX
• Real-time systems such as VxWorks
• Cray supercomputers and IBM mainframes
• PDAs running Palm OS, PocketPC, and Linux
• Cell phones running Symbian OS, and Windows Mobile
• Gaming consoles and iPods
• Tablets and smartphones running Google’s Android and Apple’s iOS
• And more
------------------------------------------------------------------------------
Python Features:
-----------------------------------------------------------------------------------------
It’s Powerful:
From a features perspective, Python is something of a hybrid. Its toolset places it between
traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development
languages (such as C, C++, and Java).
---------------------------------------------------------------------------
Dynamic typing:
Python keeps track of the kinds of objects your program uses when it runs; it
doesn’t require complicated type and size declarations in your code.
--------------------------------------------------------------------------
Automatic memory management:
Python automatically allocates objects and reclaims (“garbage collects”) them
when they are no longer used, and most can grow and shrink on demand.
---------------------------------------------------------------------------
Programming-in-the-large support:
For building larger systems, Python includes tools such as modules, classes, and
exceptions. These tools allow you to organize systems into components.
------------------------------------------------------------------------------
Built-in object types:
Python provides commonly used data structures such as lists, dictionaries, and
strings as intrinsic parts of the language; as you’ll see, they’re both flexible and easy
to use.
-----------------------------------------------------------------------------
Built-in tools:
To process all those object types, Python comes with powerful and standard operations,
including concatenation (joining collections), slicing (extracting sections),
sorting, mapping, and more.
------------------------------------------------------------------------------
Library utilities:
For more specific tasks, Python also comes with a large collection of precoded
library tools that support everything from regular expression matching to networking.
----------------------------------------------------------------------------
Third-party utilities:
Because Python is open source, developers are encouraged to contribute precoded
tools that support tasks beyond those supported by its built-ins
--------------------------------------------------------
---------------------------------
--------------------------------
.Google makes extensive use of Python in its web search systems.
• The popular YouTube video sharing service is largely written in Python.
• The Dropbox storage service codes both its server and desktop client software primarily
in Python.
• The Raspberry Pi single-board computer promotes Python as its educational language.
• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses
Python broadly.
• The widespread BitTorrent peer-to-peer file sharing system began its life as a
Python program.
• Industrial Light & Magic, Pixar, and others use Python in the production of animated
movies.
• ESRI uses Python as an end-user customization tool for its popular GIS mapping
products.
• Google’s App Engine web development framework uses Python as an application
language.
• The IronPort email server product uses more than 1 million lines of Python code
to do its job.
• Maya, a powerful integrated 3D modeling and animation system, provides a
Python scripting API.
• The NSA uses Python for cryptography and intelligence analysis.
• iRobot uses Python to develop commercial and military robotic devices.
Who Uses Python Today? | 9
www.it-ebooks.info
• The Civilization IV game’s customizable scripted events are written entirely in
Python.
• The One Laptop Per Child (OLPC) project built its user interface and activity model
in Python.
• Netflix and Yelp have both documented the role of Python in their software infrastructures.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.
• JPMorgan Chase, UBS, Getco, and Citadel apply Python to financial market forecasting.
• NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming
tasks.
------------------------------------------------------------------------
What Can I Do with Python?
------------------------------------------------------------------------
Systems Programming:
Python’s built-in interfaces to operating-system services make it ideal for writing
portable, maintainable system-administration tools and utilities (sometimes called shell
tools). Python programs can search files and directory trees, launch other programs, do
parallel processing with processes and threads, and so on.
GUIs:
Python’s simplicity and rapid turnaround also make it a good match for graphical user
interface programming on the desktop. Python comes with a standard object-oriented
interface to the Tk GUI API called tkinter (Tkinter in 2.X) that allows Python programs
to implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged
on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS
(both Classic and OS X).
Internet Scripting:
Python comes with standard Internet modules that allow Python programs to perform
a wide variety of networking tasks, in client and server modes. Scripts can communicate
over sockets; extract form information sent to server-side CGI scripts; transfer files by
FTP; parse and generate XML and JSON documents; send, receive, compose, and parse
In addition, full-blown web development framework packages for Python, such as
Django, TurboGears, web2py, Pylons, Zope, and WebWare, support quick construction
of full-featured and production-quality websites with Python.
Database Programming:
For traditional database demands, there are Python interfaces to all commonly used
relational database systems—Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL,SQLite, and more. The Python world has also defined a portable database API for accessing
SQL database systems from Python scripts
Rapid Prototyping
To Python programs, components written in Python and C look the same. Because of
this, it’s possible to prototype systems in Python initially, and then move selected components
to a compiled language such as C or C++ for delivery.
Numeric and Scientific Programming
And More: Gaming, Images, Data Mining, Robots, Excel...
• Game programming and multimedia with pygame, cgkit, pyglet, PySoy,
Panda3D, and others
• Serial port communication on Windows, Linux, and more with the PySerial extension
• Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya,
and more
• Robot control programming with the PyRo toolkit
• Natural language analysis with the NLTK package
• Instrumentation on the Raspberry Pi and Arduino boards
• Mobile computing with ports of Python to the Google Android and Apple iOS
platforms
• Excel spreadsheet function and macro programming with the PyXLL or DataNitro
add-ins
• Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow,
and more
• Artificial intelligence with the PyBrain neural net library and the Milk machine
learning toolkit
• Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog
• Network monitoring with zenoss, written in and customized with Python
• Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD,
and others
• Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF,
and so on
• Data visualization with Mayavi, matplotlib, VTK, VPython, and more
• XML parsing with the xml library package, the xmlrpclib module, and third-party
extensions
• JSON and CSV file processing with the json and csv modules
--------------------------------------------------------------------
Python is available on:
• Linux and Unix systems
• Microsoft Windows (all modern flavors)
• Mac OS (both OS X and Classic)
• BeOS, OS/2, VMS, and QNX
• Real-time systems such as VxWorks
• Cray supercomputers and IBM mainframes
• PDAs running Palm OS, PocketPC, and Linux
• Cell phones running Symbian OS, and Windows Mobile
• Gaming consoles and iPods
• Tablets and smartphones running Google’s Android and Apple’s iOS
• And more
------------------------------------------------------------------------------
Python Features:
-----------------------------------------------------------------------------------------
It’s Powerful:
From a features perspective, Python is something of a hybrid. Its toolset places it between
traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development
languages (such as C, C++, and Java).
---------------------------------------------------------------------------
Dynamic typing:
Python keeps track of the kinds of objects your program uses when it runs; it
doesn’t require complicated type and size declarations in your code.
--------------------------------------------------------------------------
Automatic memory management:
Python automatically allocates objects and reclaims (“garbage collects”) them
when they are no longer used, and most can grow and shrink on demand.
---------------------------------------------------------------------------
Programming-in-the-large support:
For building larger systems, Python includes tools such as modules, classes, and
exceptions. These tools allow you to organize systems into components.
------------------------------------------------------------------------------
Built-in object types:
Python provides commonly used data structures such as lists, dictionaries, and
strings as intrinsic parts of the language; as you’ll see, they’re both flexible and easy
to use.
-----------------------------------------------------------------------------
Built-in tools:
To process all those object types, Python comes with powerful and standard operations,
including concatenation (joining collections), slicing (extracting sections),
sorting, mapping, and more.
------------------------------------------------------------------------------
Library utilities:
For more specific tasks, Python also comes with a large collection of precoded
library tools that support everything from regular expression matching to networking.
----------------------------------------------------------------------------
Third-party utilities:
Because Python is open source, developers are encouraged to contribute precoded
tools that support tasks beyond those supported by its built-ins
--------------------------------------------------------
---------------------------------
python application domains and different environments
PYTHON WAS MORE POWERFUL THAN JAVA
WE CAN DEVELOP AND USE PYTHON IN DIFFERENT DOMAINS
SCIENTIFIC SCIPY SCIENTIFIC PROBLEMS
NUMPY MATRIX AND NUMERICAL PROBLEMS
BIOPY BIOLOGY APPLICATIONS
TWIITT-API-PY TWITTER PULL DATA
RASBERRY PI-- EMBEDDED APPLICATIONS / IOT APPLICATIONS
CISCO ROUTER PROGRAMMING
DATA SCIENCE PYTHON DATA ANALYTICS
PYHADOOP HADOOP WITH PYTHON
PYODBC PYTHON WITH ODBC DATA BASES
MYSQLDB PYTHON WITH MYSQL
SQLITE3 PYTHON WITH SQLITE
PYQT PYTHON WITH GUI
KINTER PYTHON WITH GUI
MATPLOTLIB PYTHON PLOT GRAPHS
MACHINE LEARNING
DEEP LEARNING PYTHON
SELF LEARNING
NLP PROBLEMS
OBJECT PROGRAMMING PYTHON
EXCEPTION HANDLING PYTHON
THREAD PROGRAMMING PYTHON
WE CAN DEVELOP AND USE PYTHON IN DIFFERENT DOMAINS
SCIENTIFIC SCIPY SCIENTIFIC PROBLEMS
NUMPY MATRIX AND NUMERICAL PROBLEMS
BIOPY BIOLOGY APPLICATIONS
TWIITT-API-PY TWITTER PULL DATA
RASBERRY PI-- EMBEDDED APPLICATIONS / IOT APPLICATIONS
CISCO ROUTER PROGRAMMING
DATA SCIENCE PYTHON DATA ANALYTICS
PYHADOOP HADOOP WITH PYTHON
PYODBC PYTHON WITH ODBC DATA BASES
MYSQLDB PYTHON WITH MYSQL
SQLITE3 PYTHON WITH SQLITE
PYQT PYTHON WITH GUI
KINTER PYTHON WITH GUI
MATPLOTLIB PYTHON PLOT GRAPHS
MACHINE LEARNING
DEEP LEARNING PYTHON
SELF LEARNING
NLP PROBLEMS
OBJECT PROGRAMMING PYTHON
EXCEPTION HANDLING PYTHON
THREAD PROGRAMMING PYTHON
Subscribe to:
Comments (Atom)
LIST OPERATIONS
https://www.youtube.com/watch?v=qnET1chif8k