** KTU - INTRODUCTION TO COMPUTING AND PROBLEM SOLVING **
variables, expressions and statements, evaluation of expressions, precedence, string operations. Control statements, Boolean expressions and logical operators, conditional and alternative executions. Iteration - while statement and tables.
Functions, calling functions, type conversion and coercion, composition of functions, mathematical functions, user-defined functions, parameters and arguments.
Strings and lists – string traversal and comparison with examples. tuples and dictionaries – operations and examples
Files and exceptions - text files, directories. Introduction to classes and objects - attributes, instances
This notebook includes
a=1
b=1.0
#when an integer is added to a float, result is float
c=a+b
print c
2.0
print "2+3 is", 2+3
print "2-3 is", 2-3
print "2/3 is", 2/3
print "2*3 is", 2*3
print "2**3 is", 2**3
print "2%3 is",2%3
print "2==3", 2==3
print "2.0==2",2==2.0
2+3 is 5 2-3 is -1 2/3 is 0 2*3 is 6 2**3 is 8 2%3 is 2 2==3 False 2.0==2 True
v1="hello"
v2="world"
print type(v1)
#length can be found with len function
print len(v1)
print len(v2)
<type 'str'> 5 5
#String concatenation can be done with + operator
print "The string is",v1+v2
print v1[0:len(v1)]
#index of -1 means last element
print v1[-1]
print 3*v1
The string is helloworld hello o hellohellohello
When the arguments of a numeric operation are of different types, the interpreter tries to coerce the arguments into a common type. The numeric operation is then performed using this common type.
Type conversion is a mechanism which should be used explicitly.
#coersion example
a=1
print type(a)
b=1.0
print type(b)
c=a+b
print c
print type(c)
<type 'int'> <type 'float'> 2.0 <type 'float'>
#If anyone of the number is float, result is converted to float
print "3/2 is ",3/2
print "3/2.0 is ", 3.0/2.0
print "3.0/2 is ", 3.0/2.0
3/2 is 1 3/2.0 is 1.5 3.0/2 is 1.5
#conversion example
print a
d=float(a)
print d
print type(d)
1 1.0 <type 'float'>
A list is an ordered set of values. Each value is identified by an index.
nlist=[1,2,3,4]
slist=["kerala","TN","Andhra"]
print nlist
print slist
[1, 2, 3, 4] ['kerala', 'TN', 'Andhra']
append is used to add elements to the list
nlist.append(5)
slist.append(5)
print nlist
print slist
[1, 2, 3, 4, 5, 5] ['kerala', 'TN', 'Andhra', 5, 5]
list indexing is similar to that of string
print nlist[0:3]
print nlist[0:5]
print nlist[-1]
print nlist[0:-1]
[1, 2, 3] [1, 2, 3, 4, 5] 5 [1, 2, 3, 4, 5]
print nlist
print nlist.index(2)
nlist.append(2)
print nlist
print nlist.index(2)
[1, 2, 3, 4, 5, 5] 1 [1, 2, 3, 4, 5, 5, 2] 1
in is a boolean operator that tests membership
print 5 in nlist
True
split function breaks a string into a list of words
sent="This is a line."
lst=sent.split()
print lst
['This', 'is', 'a', 'line.']
Python tuple is an immutable data structure. Operations on tuples are the same as the operations on lists.
tuple = ('a', 'b', 'c')
print tuple
#For creating a tuple with a single element
tu=('a',)
print tu
tu=('a')
print tu
('a', 'b', 'c') ('a',) a
Unlike other data types, dictionaries can use data types other than integer (integer is also included) as index. Dictionaries are made up of key-value pairs.
dict={"univ1":"Kerala","univ2":"Calicut","univ3":"CUSAT"}
print dict["univ3"]
print dict.keys()
print dict.values()
print dict.items()
CUSAT ['univ1', 'univ3', 'univ2'] ['Kerala', 'CUSAT', 'Calicut'] [('univ1', 'Kerala'), ('univ3', 'CUSAT'), ('univ2', 'Calicut')]
print dict.has_key("univ5")
print dict.has_key("univ2")
False True
There are three logical operators:
Operands of the logical operators should be boolean expressions. Any nonzero number is interpreted as True.
x = 5
x and 1
1
Program to sorted list as an when numbers are entered
#use of while
a=[]
while True:
a.append(int(raw_input()))
a.sort()
print a
#use of if statment
x = int(raw_input("Please enter an integer: "))
if x==0:
print "x is zero"
elif x>0:
print "positive"
else:
print "negative"
Please enter an integer: 4 positive
#use of for statement
for i in range(0,9):
print i
a=["one","two","three"]
for i in a:
print i
0 1 2 3 4 5 6 7 8 one two three
The break statement breaks out of the smallest enclosing for or while loop. The continue statement continues with the next iteration of the loop.
inp=int(raw_input())
#using incrementing while
itr=0
sqr=0
while itr<inp:
sqr=sqr+inp
itr+=1
print sqr
print "----------------"
#using decrementing while loop
itr=inp
sqr=0
while itr!=0:
sqr=sqr+inp
itr-=1
print sqr
print "----------------"
#using a for loop
sqr=0
for itr in range(0,inp):
sqr=sqr+inp
print sqr
4 16 ---------------- 16 ---------------- 16
for i = 1:n
k = i
for j = i+1:n
if a[j] < a[k]
k = j
swap a[i,k]
end
# Selection sort example
lst=[3,4,21,7,33]
for i in range(0,len(lst)):
k=i
for j in range(i+1,len(lst)):
if lst[j] < lst[k]:
k=j
tmp=lst[i]
lst[i]=lst[k]
lst[k]=tmp
print lst
[3, 4, 7, 21, 33]
#Mathematical functions example
import math
math.factorial(5)
120
print math.pi
3.14159265359
# user-defined function example
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
print fact(1)
print fact(2)
print fact(3)
print fact(4)
print fact(5)
print fact(6)
#Program to print fibonacci series upto n
def fib(n):
a=0
b=1
while a<n:
print a
# expressions to the right of the assignment operator are evaluated before any of the assignments are made.
a,b=b,a+b
fib(10)
0 1 1 2 3 5 8
class may define a special method named __init__() to create objects with instances customized to a specific initial state.
class Dog:
#tricks=[]
def __init__(self, name):
self.name = name
self.tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
x=Dog("a")
x.add_trick("play dead")
print x.name
print x.tricks
y=Dog("b")
y.add_trick("roll over")
print y.name
print y.tricks
a ['play dead'] b ['roll over']
Different file modes are
#Open a file
f=open("filename.txt","w")
#readline method reads all the characters up to and including the next newline character
print f.readline()
# write method is used to write data
f.write("line one\nline two\nline three\n")
# tell method is used to print the current position of file pointer
print f.tell()
# seek method is used to seek to a custom position in a file. seek(0) will move to first byte
f.seek(0)
#close method is used to close the file
f.close()
--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-2-35b65cdcff10> in <module>() 2 f=open("filename.txt","w") 3 #readline method reads all the characters up to and including the next newline character ----> 4 print f.readline() 5 # write method is used to write data 6 f.write("line one\nline two\nline three\n") IOError: File not open for reading
Exceptions can be handled using the try and except statements. If your program detects an error condition, you can make it raise an exception. More information about Python builtin exception can be found from Python docs.
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
Enter a file name: test There is no file named test
def inputNumber () :
x = input('Pick a number: ')
if x == 17 :
raise ValueError, '17 is a bad number'
return x
inputNumber()
Pick a number: 17
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-16-54951093164d> in <module>() 4 raise ValueError, '17 is a bad number' 5 return x ----> 6 inputNumber() <ipython-input-16-54951093164d> in inputNumber() 2 x = input('Pick a number: ') 3 if x == 17 : ----> 4 raise ValueError, '17 is a bad number' 5 return x 6 inputNumber() ValueError: 17 is a bad number