CSC305_ScriptingProgrammingBriefNotes
CSC305_ScriptingProgrammingBriefNotes
1
Starts the
first Python
2
Create the
function in
the Python
editor
Input and
output
commands
• eval if you want to enter numbers or you can use int as well
• Without the eval command considered as input string
• Other option is you can use:-
yearofbirth = int(input(“Enter year of birth : “))
>>> sampel()
5 6 output
3
String and >>> 4 integer
4
numbers in >>> 6.4 float
Python 6.4
>>> 3.142
3.142
>>> "Hello world" string
'Hello world'
*String and https://www.pythonforbeginners.com/basics/string-manipulation-in-
python#:~:text=To%20perform%20string%20manipulation%20in,1%20of%20the%20string%20string_name.
list
>>> str1 = "WELCOME TO PULAU PINANG"
manipulation >>> print(str1[10]) #space
>>> print(str1[9]) #O
O
• A heterogeneous
sequence of >>> len(str1) #length of the string
values 23
• Contains items
separated by >>> "WELCOME" + "TO" + "PENANG" #concatenate the strings
'WELCOMETOPENANG'
commas and
>>> 3 * "WELCOME" #multiply the string
enclosed within a 'WELCOMEWELCOMEWELCOME'
square bracket [ ]
• Components of >>> int('20') #convert string to integer
lists can be 20
updated, inserted
>>> print(str1[:7]) #extract string from index 0 til 6
and deleted
WELCOME
• Mutable for
lists, means can >>> grade = ['A','B','C','D','E','F']
be updated or >>> grade[2] #xtract value at index 2
value can be 'C'
changed >>> grade[2:4] #extract from index 2 to 3
['C', 'D']
• Components of >>> grade[0:1]*2 #extract from index 0 only and multiply the string
list can be ['A', 'A']
mixture of
numbers and >>> str2 = "Universiti Teknologi MARA"
strings >>> str2.split()
['Universiti', 'Teknologi', 'MARA']
4
>>> print string.capitalize() #only the first letter of the sentence is capitalized
Hello world
>>> print string.swapcase() #tOGGLE cASE
hELLO wORLD
#concatenate
"Hello " + "World" # Output is "Hello World"
"Hello " + "World" + "!" # Output is "Hello World!"
>>> name.sort() #sort in ascending order all elements from the list
>>> name
['ali', 'aminah', 'azli', 'bakar', 'hazlina', 'karimah', 'kasturi', 'othman', 'sabri', 'salima',
'zantun']
https://www.programiz.com/python-programming/list
# empty list
my_list = []
5
# items from index 5 to end
print(my_list[5:]) #Output : ['a', 'm', 'i', 'z']
Output:
['o', 'g', 'r']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
my_list[2:5] returns a list with items from index 2 to index 4.
my_list[5:] returns a list with items from index 5 to the end.
my_list[:] returns all list items
>>> test()
ali
aminah
hazlina
cindai
karimah
zantun
othman
bakar
6
Other methods that you can practiced in list manipulation
*Tuple https://www.programiz.com/python-programming/tuple
A number of >>> tuple1 =() ➔ blank
values >>> print(tuple1)
separated by () ➔ Output
comma and
enclosed within >>> tuple2 = (1, 2, 3, 4) ➔ integers only
a parentheses ( >>> print(tuple2)
) (1, 2, 3, 4) ➔ Output
Tuples are
immutable >>> tuple3 = (123, "jamil bin ali", "cs110") ➔ mixture of data type
(value cannot be >>> print(tuple3)
changed). If any (123, 'jamil bin ali', 'cs110') ➔ Output
of their
components are >>> tuple4 = (123, "jamal bin ali",["cs110","cs111"])➔ nested tuple
mutable then the >>> print(tuple4)
value can be (123, 'jamal bin ali', ['cs110', 'cs111']) ➔ Output
changed.
Components of #Access tuple
tuple can be >>> print(tuple2[0]) ➔ access from left
mixture of 1 ➔ Output
numbers, >>> print(tuple2[:2])
strings and (1, 2) ➔ Output
lists) >>> print(tuple2[2:])
(3, 4) ➔ Output
>>> print(tuple2[-1]) ➔ access from right
4 ➔ Output
>>> print(tuple2[-2])
3 ➔ Output
>>> print(tuple2[:-1]) ➔ access from left to right but exclude index -1 from right
(1, 2, 3) ➔ Output
7
my_tuple[:] returns all tuple items.
*Dictionary https://www.programiz.com/python-programming/dictionary
capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
• associative
print(capital_city)
array
Output:
• are enclosed by {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
curly braces { } Keys are "Nepal", "Italy", "England"
• Values are Values are "Kathmandu", "Rome", "London"
assigned and
accessed using # dictionary with keys and values of different data types
square bracket numbers = {1: "One", 2: "Two", 3: "Three"}
[] print(numbers)
• Components of Output:
lists can be [3: "Three", 1: "One", 2: "Two"]
updated,
inserted and #Add element in dictionary
deleted capital_city = {"Nepal": "Kathmandu", "England": "London"}
• Mutable for print("Initial Dictionary: ",capital_city)
lists, means can Output:
be updated Initial Dictionary: {'Nepal': 'Kathmandu', 'England': 'London'}
capital_city["Japan"] = "Tokyo"
print("Updated Dictionary: ",capital_city)
Output:
Updated Dictionary: {'Nepal': 'Kathmandu', 'England': 'London', 'Japan': 'Tokyo'}
8
student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
# delete student_id dictionary
del student_id #you cannot delete if did not specify the key of dictionary
print(student_id)
# Output: NameError: name 'student_id' is not defined
Set https://www.programiz.com/python-programming/set
A set is a # create a set of integer type
collection of student_id = {112, 114, 116, 118, 115}
unique data. print('Student ID:', student_id)
9
separated by
#Duplicate Items in a Set
comma. numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # Output : {8, 2, 4, 6}
#Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
Output
Initial Set: {34, 12, 21, 54}
Updated Set: {32, 34, 12, 21, 54}
Output:
Initial Set: {'Python', 'Swift', 'Java'}
Set after remove(): {'Python', 'Swift'}
Iterate in set
fruits = {"Apple", "Peach", "Mango"}
# for loop to access each fruits
for fruit in fruits:
print(fruit)
Output
Mango
Peach
Apple
Output:
Set: {8, 2, 4, 6}
Total Elements: 4
Output:
Union using |: {0, 1, 2, 3, 4, 5}
Union using union(): {0, 1, 2, 3, 4, 5}
Note: A|B and union() is equivalent to A ⋃ B set operation.
10
Intersection or & operations on Set
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output:
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}
Note: A&B and intersection() is equivalent to A ⋂ B set operation.
Output:
Difference using -: {3, 5}
Difference using difference(): {3, 5}
Note: A - B and A.difference(B) is equivalent to A - B set operation.
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Output:
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
Output :
Set A and Set B are equal
11
Selection in Example 1 (single selection):
>>> def example():
Python num = int (input("Enter a number :"))
if (num > 10):
if print("Number greater than 10")
if else
if elif else >>> example()
Enter a number :12
Number greater than 10
>>> selection(3,2)
3 greater than 2
>>> selection2(4,2,5)
5 is largest number
def operation(n1,n2,op):
if (op=='+'):
result = n1 + n2
elif (op=='-'):
result = n1 - n2
elif (op=='/'):
result = n1 / n2
elif (op=='*'):
result = n1 * n2
elif (op=='**'):
result = n1 ** n2
else:
result = n1 % n2
print(n1,op,n2,"=",result)
def main():
12
Example 4 (Nested Selection):
def nestedSelection():
num = int(input("Enter a number : "))
if (num < 10):
if ((num > 0) and (num <= 2)):
print ("Number in between 1 to 2")
else:
print("Number in between 3 to 9")
else:
print("Number larger than 10")
>>> nestedSelection()
Enter a number : 3
Number in between 3 to 9
def main():
month = {1:"JAN",2:"FEB",3:"MAR",4:"APR",5:"MAY",6:"JUN",
7:"JUL",8:"AUG",9:"SEP",10:"OCT",11:"NOV",12:"DEC"}
Output :
Enter the month : 5
The month of 5 is MAY
Repetition in
Python using
for … in
range(…)
13
>>> rep()
1
4
7
Fourth option is by setting the the starting, ending and step is default to 1
>>> def rep():
for i in range(1,3):
print(i)
>>> rep()
1
2
3
main()
def main():
sentinel=1
while (sentinel==1):
a = eval(input("Enter a number :"))
b = eval(input("Enter a number again :"))
result = kira(a,b)
print("Result is ",result)
sentinel = eval(input("Enter 1 to continue or 0 to stop :"))
main()
14
print("Total less than 25 marks ",cnt)
main()
def output(x):
i=x
sumX = 0
while True: #set the loop as true, no need for condition checks for the 1st loop
print(i)
i = i + 1
if (i>10):
break
def main():
output(number)
main()
Output:
Enter a number : 5
5
6
7
8
9
10
Format the
numbers as int
or float
15
{0:0.2f} 0 refers to the first variable which is z
0.2f refers to formatted until 2 decimal places
Other examples
print("{0:0.2f}, {1:0.1f}, {2:6.3f} ".format(3.1426, 28.35, 234,78225))
Output :
3.14, 28.4, 234.000
Write function
main()
Write the
function in
text file,
using the
Python editor
And later
import prog1
at the console
>>> import prog1
>>> prog1.main()
Enter first number : 4
Enter second number : 6
4 + 6 = 10
Multiple Example 1:
functions with def kira1(x, y): # unction procedure with return value
the main wage=x*y #dynamically typed, state the name but not
function #the type of formal parameter
return wage
def main():
workingdays = eval(input("Number of working days : "))
rateperdays = eval(input("Rate per days : RM "))
wage = kira1(workingdays,rateperdays)
zakat = kira2(wage)
16
Example 2:
def cnvrt(x): #function procedure with return value
change = x * 0.10
return change
def main():
name = input("Enter your name : ")
#choose either eval or int
mark = eval(input("Enter your mark : "))
# mark = int(input("Enter your mark : "))
converts = cnvrt(mark)
display(name,mark,converts)
main()
Example 3:
def display(numb,i):
print("number at index {0} is {1}".format(i,numb[i]))
def main():
numbers = [3, 2, 6, 8, 3, 8, 4, 10, 12, 5]
for i in range(0,10,1):
display(numbers,i) #send lists to proper procedure
main()
>>>import prog10
number at index 0 is 3
number at index 1 is 2
number at index 2 is 6
number at index 3 is 8
number at index 4 is 3
number at index 5 is 8
number at index 6 is 4
number at index 7 is 10
number at index 8 is 12
number at index 9 is 5
17
Example 4: [function which returns multiple values and multiple
variable assign to an expression]
def getData():
x = int(input("Enter first number : "))
y = int(input("Enter second number : "))
z = int(input("Enter third number : "))
return (x,y,z) #Python returns multiple values
def main():
a, b, c = getData() #an expression assigned to multiple
variables
main()
Output:
>>> import prog13
Enter first number : 1
Enter second number : 2
Enter third number : 3
First number is : 1
Second number is : 2
Third number is : 3
Pass By Value Python actually uses Call By Object Reference also called as Call By Assignment which
means that it depends on the type of argument being passed. Python passes arguments
and Reference neither by reference nor by value, but by assignment.
in Python
Pass By Value
def fun(a):
a+=10
print("Inside function call",a)
a=20
print("Before function call",a)
fun(a)
print("After function call",a)
Output:
Before function call 20
Inside function call 30
After function call 20
Pass By Reference
def fun(a):
a.append('i')
print("Inside function call",a)
a=['H']
print("Before function call",a)
fun(a)
print("After function call",a)
Output:
Before function call ['H']
Inside function call ['H', 'i']
After function call ['H', 'i']
If immutable objects are passed then it uses Call by value (String, Integer, Tuple)
These objects cannot change their state or value.
Example :
def fun(s,num,d):
18
s="Hello"
num=10
d=(5,6,7)
print("Inside function call",s,num,d)
s="Opengenus"
num=1
d=(1,2,3)
print("Before function call",s,num,d)
fun(s,num,d)
print("After function call",s,num,d)
Output:
Before function call Opengenus 1 (1, 2, 3)
Inside function call Hello 10 (5, 6, 7)
After function call Opengenus 1 (1, 2, 3)
If mutable objects are passed then it uses Call by reference (List, Dictionary, Set)
def fun(s,num,d):
s.append(5)
num["name"]="harry"
d|=set({1,2})
print("Inside function call",s,num,d)
s=[1,2,4] #list
num={"name":"john"} #dictionary
d={4,5,6} #set
fun(s,num,d)
#getter
def getStudID(self):
return self.studid
def getStudName(self):
return self.studname
#setter
def setStudID(self, studid):
self.studid=studid
def setStudName(self,studname):
self.studname=studname
19
def getData():
sid = input ("Enter student id : ")
sname = input ("Enter student name : ")
return sid, sname # function return many values
#mutator
def setPlayer(self, playerID, playerName):
self.playerID = playerName
self.playerName = playerName
#accessor
def getPlayerID(self):
return self.playerID
def getPlayerName(self):
return self.playerName
#printer
def printer(self):
print(" Player ID : ",self.playerID)
print(" Player Name : ",self.playerName)
#mutator
def setCountryOrigin(self, countryOrigin):
self.countryOrigin = countryOrigin
#getter
def getCountryOrigin(self):
return self.countryOrigin
#printer
def printer(self):
Player.printer(self) # inherit from super
print("Country Origin : ",self.countryOrigin)
#mutator
def setPlayerLevel(self, playerLevel):
self.playerLevel = playerLevel
#getter
def getPlayerLevel(self):
return self.playerLevel
20
#printer
def printer(self):
Player.printer(self) # inherit from super # inherit from super
print("Player Level : ",self.playerLevel)
def main():
#polimorphisim
plyr1.printer()
plyr2.printer()
main()
Output:
21