1
Python 3.x
Strings
>>> print('hello')
hello
>>> print("abc'xyz")
abc'xyz
>>> print('''this is
a
multi
line
string''')
this is
a
multi
line
string
>>>
Escape sequences
>>> print('\'hello\'')
'hello'
>>> print('\\hello\\')
\hello\
>>> print('abc\nxyz')
abc
xyz
>>> print('abc\txyz')
abc xyz
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
2
Raw strings
>>> print(r'abc\txyz')
abc\txyz
>>> print(R'abc\nxyz')
abc\nxyz
String concatenation
>>> 'abc''xyz'
'abcxyz'
Format method
>>> x = 10
>>> y = 20
>>> print('value of x is {0} and value of y is {1}'.format(x,y))
value of x is 10 and value of y is 20
>>> 22/7
3.142857142857143
>>> '{0:.4}'.format(22/7)
'3.143'
>>> '{0:*^11}'.format('hello')
'***hello***'
>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')
'Swaroop wrote A Byte of Python'
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
3
Logical and physical lines
>>> s = 'This is a string. \
This continues the string.'
>>> print(s)
This is a string. This continues the string.
>>> i = 5
>>> print\
(i)
>>> i = 5; print(i);
Operators and expressions
>>> 2+5
7
>>> 2.0+5
7.0
>>> 'a'+'b'
'ab'
>>> 9-5.0
4.0
>>> 9-4
5
>>> 3*2
6
>>> 'ab'*4
'abababab'
>>> 2**7
128
>>> 3**3
27
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
4
>>> 4/2
2.0
>>> 7/3
2.3333333333333335
>>> 7//2
3
>>> 10%2
0
>>> 10%3
1
>>> 3%5
3
>>> 10%4
2
>>>
>>> 2<<2
8
>>> 3<<1
6
>>> 3>>1
1
>>> 5>>1
2
>>> 5&3
1
>>> 5|3
7
>>> 5^3
6
>>> ~5
-6
>>> 5<2
False
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
5
>>> 5<8
True
>>> 3>=2
True
>>> 5==5
True
>>> 8!=7
True
>>> 8!=8
False
>>> True or False
True
>>> 2<5 and 8>5
True
>>>
Shortcut for math operation and assignment
>>> x =5
>>> x+= 3
>>> x
8
>>> x-=2
>>> x
6
>>> x*=3
>>> x
18
Evaluation order
>>> 2*5+2
12
>>> 2*(5+2)
14
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
6
>>> 2**3*2+3
19
>>> 4/2+5%3*2
6.0
Sample python programs
1. A program to find the area and the perimeter of a rectangle
length = 5
width = 2
area = length*width
print('Area is', area)
print('Perimeter is', 2*(length+width))
2. A program to convert a temperature value given in Celsius to
Fahrenheit
c = 25
f = (1.8 * c) +32
print(f)
3. A program to find the circumference and area of a circle when the
radius is given
r = 10
pi = 22/7
c = 2*pi*r
a = pi*(r**2)
print('Circumference = ', c)
print('Area = ', a)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
7
4. A program to find the volume and the surface area of a sphere when
the radius is given
r = 10
pi = 22/7
v = (4/3) * pi * (r**3)
a = 4* pi*(r**2)
print('Volume = ', v)
print('Area = ', a)
5. A program to find the volume of a cylinder when the radius and the
height are given
r = 8
pi = 22/7
h = 15
v = pi*(r**2)*h
print('Volume = ', v)
6. A program to find the slope and the intersection of a straight line
when the coordinates of two points are given
x1=2
y1=2
x2=4
y2=4
m = (y2-y1)/(x2-x1)
c = y1-(m*x1)
print('Slope = ',m)
print('intersection = ',c)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
8
7. A program to find the minimum number of different notes and coins
needed to pay a given amount
a = int(input("Enter the amount: "))
print('1000 notes- ',a//1000)
a%=1000
print('500 notes- ',a//500)
a%=500
print('100 notes- ',a//100)
a%=100
print('50 notes- ',a//50)
a%=50
print('20 notes- ',a//20)
a%=20
print('10 coins- ',a//10)
a%=10
print('5 coins- ',a//5)
a%=5
print('2 coins- ',a//2)
a%=2
print('1 coins- ',a)
8. Program to find the length of the hypotenuse (side opposite the
right angle of a right triangle) of a right triangle ( right-angled
triangle) when the lengths of other two legs (sides adjacent to the
right angle) are given.
x=3
y=4
z = (x**2 +y**2)**(0.5)
print(z)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
9
9. A program to print “child” or “adult” according to the age value
entered by the user
age = int (input ('Enter your age: '))
if age<18 :
print('Child')
else :
print('Adult')
A better solution for the above problem.
age = int (input ('Enter your age: '))
if age>=0 and age<18 :
print('Child')
elif age>= 18 and age<=100:
print('Adult')
else :
print('Wrong age value')
10. A program to print the largest value when two numbers are
entered
a= int (input ('Enter number 1: '))
b= int (input ('Enter number 2: '))
if a>b :
print (a)
else :
print (b)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
10
11. A program to print the largest value when three numbers are
entered.
a= int (input ('Enter number 1: '))
b= int (input ('Enter number 2: '))
c= int (input ('Enter number 3: '))
if a>b :
if a>c:
print (a)
else:
print (c)
elif b>c :
print (b)
else :
print (c)
12. A program to print the letter grade when marks are entered.
Marks Grade
75-100 A
60-75 B
45-60 C
30-45 S
0-30 F
m = int( input ('Enter marks: '))
if m>=75 and m<=100:
print ('A')
elif m>=60 and m<75:
print ('B')
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
11
elif m>=45 and m<60:
print ('C')
elif m>=30 and m<45:
print ('S')
elif m>=0 and m<30:
print ('F')
else:
print('wrong marks value')
13. A program to print numbers from 1 to 10.(using the while loop)
i=1
while i<=10:
print (i)
i=i+1
print ('loop end')
14. A program to calculate the sum of 1 to 10
i =1
tot =0
while i<=10:
tot=tot+i
i=i+1
print (tot)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
12
15. A program to calculate the sum of 10 numbers entered from the
keyboard.
total = 0
count = 1
while count<=10:
no = int(input("Enter number : "))
total=total+no
count = count + 1
print (total)
16. A program to calculate the sum of 10 numbers and stops if the
user enters -1.(use of break statement)
total = 0
count = 1
while count<=10:
no = int(input("Enter number : "))
if no == -1:
break
total=total+no
count = count + 1
print (total)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
13
17. A program to calculate sum of 10 numbers and stops if the user
enters -1. Also ignores negative numbers. (use of break and continue
statements)
total = 0
count = 1
while count<=10:
no = int(input("Enter number : "))
if no == -1:
break
if no<0:
print ("Negative number")
continue
total = total+no
count = count + 1
print (total)
18. A program to enter a series of numbers and stops entering if
-1 is entered. Then print the total.(Logic control loop)
total = 0
no = int(input("Enter number : "))
while no != -1:
total = total+no
no = int(input("Enter number : "))
print (total)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
14
19. A program to enter a series of numbers and stops by entering
(-1). If the user enters 10 numbers then it also stops using the
break statement. Then display the total.
total = 0
count = 0
no = int(input("Enter number : "))
while no != -1:
count = count + 1
total=total+no
if count == 10:
break
no = int(input("Enter number : "))
else:
print("-1 entered")
print (total)
20. A program to print from 1 to 9 using a for loop.
for num in range(1,10):
print (num)
21. A program to print 1 to 10, odd numbers
for num in range(1,10,2):
print (num)
22. A program to print a given list of numbers.
data = [10,40,50,70]
for num in data:
print(num)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
15
23. Reading a string letter by letter and print.
data = "computer"
for letter in data:
print (letter)
24. Printing multiplication tables.
no = 6
for r in range(1,13):
print (no, "x", r, "=", no*r)
Lists
>>> x = [5,1,-2,-9,7,10,12,8]
>>> x
[5, 1, -2, -9, 7, 10, 12, 8]
>>> x[0]
>>> len(x)
>>> x[len(x)-1]
>>> x[-1]
>>> x[2]
-2
>>> for i in range(len(x)):
print(i,end = " ")
0 1 2 3 4 5 6 7
>>> for i in range(len(x)):
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
16
print(x[i],end = " ")
5 1 -2 -9 7 10 12 8
>>> x[1:4]
[1, -2, -9]
>>> x.append(12)
>>> x
[5, 1, -2, -9, 7, 10, 12, 8, 12]
>>> x.reverse()
>>> x
[12, 8, 12, 10, 7, -9, -2, 1, 5]
>>> x[1:1]
[]
Tuples
>>> a = 4,1,8,6,-1
>>> a
(4, 1, 8, 6, -1)
>>> len(a)
>>> a[1]
>>> a[-1]
-1
>>> a.append(12)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a.append(12)
AttributeError: 'tuple' object has no attribute 'append'
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
17
Dictionaries
>>> x = {'a':10,'b':5,'c':3,'d':-1,'e':-4,'f':12}
>>> x
{'a': 10, 'b': 5, 'c': 3, 'd': -1, 'e': -4, 'f': 12}
>>> x['a']
10
>>> x['f']
12
>>> x['e']+= 6
>>> x
{'a': 10, 'b': 5, 'c': 3, 'd': -1, 'e': 2, 'f': 12}
>>> del x['d']
>>> x
{'a': 10, 'b': 5, 'c': 3, 'e': 2, 'f': 12}
>>> x['g'] = 17
>>> x
{'a': 10, 'b': 5, 'c': 3, 'e': 2, 'f': 12, 'g': 17}
Sets
>>> x = set([5,1,4,9,6,3,7,2])
>>> y = set([1,7,3,2])
>>> z = set([-1,10,12,20,4,6,2,7])
>>> x
{1, 2, 3, 4, 5, 6, 7, 9}
>>> y
{1, 2, 3, 7}
>>> z
{2, 4, 6, 7, 10, 12, 20, -1}
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
18
>>> x&z
{2, 4, 6, 7}
>>> x|z
{1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 20, -1}
>>> x&y
{1, 2, 3, 7}
>>> x-y
{9, 4, 5, 6}
>>> 9 in x
True
>>> 12 in x
False
>>> x.remove(1)
>>> x
{2, 3, 4, 5, 6, 7, 9}
Functions
25. Function to print a logo
def printSomething():
print('******************')
print('Advanced Level ICT')
print('******************')
printSomething()
printSomething()
printSomething()
printSomething()
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
19
26. Function to print a largest value when two numbers are entered
def printLargest(a,b):
if a>b:
print (a)
else:
print (b)
printLargest(3,5)
printLargest(4,1)
27. Local variables with functions
def func(x):
print ('x in the function is ', x)
x =2
print ('x in the function is ', x)
x = 30
func(x)
print ('x in the main program is ', x)
28. Using the ‘global’ statement to access variables defined outside the function
def func():
global x
print ('x is ', x)
x = 2
print ('Global x value is changed to ', x)
x =50
func()
print ('Value of x is', x)
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
20
29. Using default arguments
def defaultArgs(word,number=3):
print (word*number)
defaultArgs('hello')
defaultArgs('hi',5)
30. Using keyword arguments
def func(a,b=5,c=10):
print ('a is', a, 'and b is', b, 'and c is', c)
func(3,7)
func(25,c=24)
func(c=50,a=100)
31. Using the return statement
def getMax(a,b):
if a>b:
return a
else:
return b
x = getMax(4,7)
print (x)
print (getMax(-3,-4))
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
21
strip() and split()
>>> x = ' hello '
>>> x
' hello '
>>> x.strip()
'hello'
>>> x = 'computer'
>>> x.strip('c')
'omputer'
>>> x.strip('r')
'compute'
>>> x.strip('u')
'computer'
>>> data = 'Amila,75,45,89'
>>> data
'Amila,75,45,89'
>>> dl = data.split(',')
>>> dl
['Amila', '75', '45', '89']
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
22
File Handling
32. Open a file to read the content.
f = open('data.txt', 'r')
txt = f.read()
print (txt)
f.close()
33. Reading comma separated values
f = open ("marks.txt","r")
record = f.readline()
while record:
data = record.strip().split(",")
print (data)
record = f.readline()
f.close()
File content: -
Amila,33,22,85
Kasun,34,66,69
Asela,33,66,78
Bimal,55,33,92
Saman,44,55,85
34. Write data to a file
f = open ("data.txt","w")
s = 'Sri Lanka'
f.write(s)
f.close()
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science
23
35. Storing comma separated values taken from the keyboard
f = open ("xyz.txt","w")
for r in range(5):
name = input("Enter name : ")
m1 = input("Marks 1: ")
m2 = input("Marks 2: ")
m3 = input("Marks 3: ")
record = name + ", "+m1+','+m2+','+m3+'\n'
f.write(record)
f.close()
Pubudu Wijekoon
B.Sc. Sp.(Hons) in IT, M.Sc. in Computer Science