0% found this document useful (0 votes)
4 views21 pages

CSC305_ScriptingProgrammingBriefNotes

The document provides an overview of Python as a scripting programming language, highlighting its key features such as dynamic typing, rapid application development, and support for various data types. It includes examples of basic Python functions, string manipulation, list operations, and tuple usage. Additionally, it emphasizes Python's concise and readable syntax, making it suitable for both beginners and experienced programmers.

Uploaded by

2021870426
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views21 pages

CSC305_ScriptingProgrammingBriefNotes

The document provides an overview of Python as a scripting programming language, highlighting its key features such as dynamic typing, rapid application development, and support for various data types. It includes examples of basic Python functions, string manipulation, list operations, and tuple usage. Additionally, it emphasizes Python's concise and readable syntax, making it suitable for both beginners and experienced programmers.

Uploaded by

2021870426
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

CSC305 – PROGRAMMING PARADIGMS

SCRIPTING PROGRAMMING [PYTHON]


Concepts based - Similar to Imperative Programming
- Support variables, commands and procedures
- Special characteristics: support very high level for string
processing, high level of GUI and dynamic typing (All
operations are type-checked at run-time)
- Rapid development of application (easy to write application)
- Use script to glue subsystems together (example like an
office software connects Microsoft Words to spell checker
or drawing tools)
- Regular expression – is a kind of pattern that matches some
set of strings
Language - Python, JavaScript, PHP, ASP
- Python has been used to develop the most powerful search
engine, e.g. google.
- Python programming is the idea of based on Perl, Haskell
and Object Oriented
Invented Python was designed in the early 1990s by Guido Van Rossum
Key concepts - Concise, readable, highly expressive
- Compact language
- By default, data entered in Python is in string
- Has string matching
- Dynamically typed or with no type information in variable
declaration, simply assign a value to the variable
- Has composite data types: tuples, strings, lists,
dictionaries, sets and objects
- Support local and global variables
- Python has continue, break, return and exception in Object
Oriented
- Support function procedures to return value and proper
procedures which return nothing
- Python has three different constructs: packages, modules
and classes. Package is a group of modules. Module is a
group of components such as variables, procedures and class.
All components of a module are public. Except with ‘_’ are
private. A class is a group of variables, class methods and
instance methods. If the first formal parameter of procedure
in the class declaration is named as ‘self’, it acts as
instance method, otherwise acts as class method. The keyword
of the constructor is ‘__init__’.

Comments # for single line comments


“”” “”” for multiple line comments

1
Starts the
first Python

>>> def display():


Simple print("Hello world!!!")
function on >>> display()
Python console Output:
Hello world!!!

>>> def display():


name = input ("Your name : ")
print("My name is ",name)
>>> display()
Output:
Your name : jamilah bakar
My name is jamilah bakar

>>> def kira(x,y):


print(x," + ", y, " is ", (x+y))
>>> kira(8,9)
Output:
8 + 9 is 17

>>> def multiply(a,b,c):


result = a * b * c
print (“Result is ”, result)
>>> multiply(1,2,3)
Output:
Result is 6

2
Create the
function in
the Python
editor

Give the file name and save as fstProg.py.


Then on console import the file name
Eg : >>> import fstProg
>>> 3 x 5 = 15  output

Input and
output
commands

>>> import scProg


Enter your name : jamal othman
Enter year of birth : 1984
My name is jamal othman
My age is 38

• 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 : “))

Formatting \n, >>> def sampel():


print(5,end="")
\t print(6)
>>> sampel()
56  output

>>> def sampel():


print(5,end="\n")
print(6)
>>> sampel()
5  output
6

>>> def sampel():


print(5,end="\t")
print(6)

>>> 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']

#Access characters in a String


word = "Hello World"
letter=word[0]
>>> print letter
H

#Find a Character in a String


>>> word = "Hello World"
>>> print word.find("H") #find the index number of char H in the string
0

>>> word = "Hello World"


>>> print word.count('l') #count how many times l is in the string
3

s = "Count, the number of spaces"


>>> print s.count(' ')
8

word = "hello world"


>>> word.startswith("H")
True  boolean result
>>> word.endswith("d")
True  boolean result
>>> word.endswith("w")
False  boolean result

print "."* 10 # prints ten dots


>>> print "." * 10 #multiple the string for 10 times
..........

word = "Hello World"


>>> word.replace("Hello", "Goodbye")
'Goodbye World'

string = "Hello World"


>>> print string.upper() #capitalize or uppercase
HELLO WORLD
>>> print string.lower() #lowercase
hello world
>>> print string.title() #only the first letter of each word is capitalized
Hello World

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!"

#Others String Manipulation


word.isalnum() #check if all char are alphanumeric
word.isalpha() #check if all char in the string are alphabetic
word.isdigit() #test if string contains digits
word.istitle() #test if string contains title words
word.isupper() #test if string contains upper case
word.islower() #test if string contains lower case
word.isspace() #test if string contains spaces
word.endswith('d') #test if string endswith a d
word.startswith('H') #test if string startswith H

>>> name =['ali','aminah','hazlina','cindai','karimah','zantun','othman','bakar']


>>> name
['ali', 'aminah', 'hazlina', 'cindai', 'karimah', 'zantun', 'othman', 'bakar']

>>> name.append('salima') #append string into list


>>> name
['ali', 'aminah', 'hazlina', 'cindai', 'karimah', 'zantun', 'othman', 'bakar', 'salima']

>>> name.insert(1,'azli') #insert string into specific location in the list


>>> name
['ali', 'azli', 'aminah', 'hazlina', 'cindai', 'karimah', 'zantun', 'othman', 'bakar', 'salima']

>>> name.extend(['kasturi','sabri']) #append several strings into the list


>>> name
['ali', 'azli', 'aminah', 'hazlina', 'cindai', 'karimah', 'zantun', 'othman', 'bakar', 'salima',
'kasturi', 'sabri']

>>> name.remove('cindai') #remove string from the list


>>> name
['ali', 'azli', 'aminah', 'hazlina', 'karimah', 'zantun', 'othman', 'bakar', 'salima', 'kasturi',
'sabri']

>>> name.sort() #sort in ascending order all elements from the list
>>> name
['ali', 'aminah', 'azli', 'bakar', 'hazlina', 'karimah', 'kasturi', 'othman', 'sabri', 'salima',
'zantun']

>>> name.reverse()#sort in descending order all elements from the list


>>> name
['zantun', 'salima', 'sabri', 'othman', 'kasturi', 'karimah', 'hazlina', 'bakar', 'azli',
'aminah', 'ali']

https://www.programiz.com/python-programming/list
# empty list
my_list = []

# list with mixed data types


my_list = [1, "Hello", 3.4]

languages = ["Python", "Swift", "C++"]

# access item at index 0


print(languages[0]) # Output : Python, extract from from of the list

# access item at index 2


print(languages[2]) # Output : C++, extract from from of the list

languages = ["Python", "Swift", "C++"]

# access item at index 0


print(languages[-1]) # Output : C++, extract from the back of the list (-)

# access item at index 2


print(languages[-3]) # Output : Python, extract from the back of the list (-)

# access item at index 2


print(languages[-2:]) # Output : Swift, C++ extract from the back of the list (-)

# List slicing in Python


my_list = ['p','r','o','g','r','a','m','i','z']
# items from index 2 to index 4
print(my_list[2:5]) #Output : ['o', 'g', 'r']

5
# items from index 5 to end
print(my_list[5:]) #Output : ['a', 'm', 'i', 'z']

# items beginning to end


print(my_list[:]) #Output : ['p', 'r', 'o', 'g', 'r', '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

languages = ['Python', 'Swift', 'C++']


# changing the third item to 'C'
languages[2] = 'C'
print(languages) # Output : ['Python', 'Swift', 'C']

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']


# deleting the second item
del languages[1]
print(languages) # Output : ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item


del languages[-1]
print(languages) # Output : ['Python', 'C++', 'C', 'Java', 'Rust']

# delete first two items


del languages[0 : 2]
print(languages) # Output : ['C', 'Java', 'Rust']

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']


# remove 'Python' from the list
languages.remove('Python')
print(languages) # Output : ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

languages = ['Python', 'Swift', 'C++']


# iterating through the list
for language in languages:
print(language)
Output:
Python
Swift
C++

>>> def test():


name =['ali','aminah','hazlina','cindai','karimah','zantun','othman','bakar']
for x in name:
print(x)

>>> test()
ali
aminah
hazlina
cindai
karimah
zantun
othman
bakar

languages = ['Python', 'Swift', 'C++']


print('C' in languages) # Output : False
print('Python' in languages) # Output : True

'C' is not present in languages, 'C' in languages evaluates to False.


'Python' is present in languages, 'Python' in languages evaluates to True.

#length of the lists


languages = ['Python', 'Swift', 'C++']
print("List: ", languages)
print("Total Elements: ", len(languages)) # Output : 3

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

# accessing tuple elements using slicing


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index


print(my_tuple[1:4]) # output ('r', 'o', 'g')

# elements beginning to 2nd


print(my_tuple[:-7]) # output ('p', 'r')

# elements 8th to end


print(my_tuple[7:]) # output ('i', 'z')

# elements beginning to end


print(my_tuple[:]) # output ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

my_tuple[1:4] returns a tuple with elements from index 1 to index 3.


my_tuple[:-7] returns a tuple with elements from beginning to index 2.
my_tuple[7:] returns a tuple with elements from index 7 to the end.

7
my_tuple[:] returns all tuple items.

my_tuple = ('a', 'p', 'p', 'l', 'e',)


print(my_tuple.count('p')) #output :prints 2
print(my_tuple.index('l')) #output :prints 3

my_tuple.count('p') - counts total number of 'p' in my_tuple


my_tuple.index('l') - returns the first occurrence of 'l' in my_tuple

languages = ('Python', 'Swift', 'C++')


# iterating through the tuple
for language in languages:
print(language)
Output:
Python
Swift
C++

languages = ('Python', 'Swift', 'C++')


print('C' in languages) # Output : False
print('Python' in languages) # Output : True

Adding new values in the tuple


#Two numbers added in the tuple
>>> numberTuple = numberTuple + (11,12)
>>> numberTuple
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

*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'}

# Change value of Dictionary


student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", student_id)
student_id[112] = "Stan"
print("Updated Dictionary: ", student_id)
Output:
Initial Dictionary: {111: 'Eric', 112: 'Kyle', 113: 'Butters'}
Updated Dictionary: {111: 'Eric', 112: 'Stan', 113: 'Butters'}

#access element for dictionary


student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print(student_id[111]) # Output : prints Eric
print(student_id[113]) # Output : prints Butters

#remove element from dictionary


student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", student_id)
del student_id[111]
print("Updated Dictionary ", student_id)
Output:
Initial Dictionary: {111: 'Eric', 112: 'Kyle', 113: 'Butters'}
Updated Dictionary {112: 'Kyle', 113: 'Butters'}

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

# Membership Test for Dictionary Keys, not the value


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares) # prints True
print(2 not in squares) # prints True

# membership tests for key only not value


print(49 in squares) # prints false

# Iterating through a Dictionary


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i]) # i is the key
Output:
1
9
25
49
81

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)

That is, # create a set of string type


elements of a vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
set cannot be
duplicated. # create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
In Python, we
create sets by OUTPUT:
placing all Student ID: {112, 114, 115, 116, 118}
Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
the elements Set of mixed data types: {'Hello', 'Bye', 101, -2}
inside curly
# create an empty set
braces {}, empty_set = set()

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.

Add item in a set


numbers = {34, 12, 21, 54}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)

Output
Initial Set: {34, 12, 21, 54}
Updated Set: {32, 34, 12, 21, 54}

Update Python Set


companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
companies.update(tech_companies)
print(companies)
# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Remove an Element from a Set


languages = {'Swift', 'Java', 'Python'}
print('Initial Set:',languages)
# remove 'Java' from a set
removedValue = languages.discard('Java')
print('Set after remove():', languages)

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

Find Number of Set Elements


even_numbers = {2,4,6,8}
print('Set:',even_numbers)
# find number of elements
print('Total Elements:', len(even_numbers))

Output:
Set: {8, 2, 4, 6}
Total Elements: 4

Union or | operations on Set


# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}

# perform union operation using |


print('Union using |:', A | B)

# perform union operation using union()


print('Union using union():', A.union(B))

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}

# perform intersection operation using &


print('Intersection using &:', A & B)

# perform intersection operation using intersection()


print('Intersection using intersection():', A.intersection(B))

Output:
Intersection using &: {1, 3}
Intersection using intersection(): {1, 3}
Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets


# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}

# perform difference operation using &


print('Difference using -:', A - B)

# perform difference operation using difference()


print('Difference using difference():', A.difference(B))

Output:
Difference using -: {3, 5}
Difference using difference(): {3, 5}
Note: A - B and A.difference(B) is equivalent to A - B set operation.

Set Symmetric Difference


# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}

# perform difference operation using ^


print('using ^:', A ^ B)

# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))

Output:
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

Check if two sets are equal


# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}

# perform difference operation using &


if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')

Output :
Set A and Set B are equal

#The set can be mixture of numbers and chars


>>> setA = {2,3,5,'a'}
>>> setA
{2, 3, 'a', 5}

>>> setB = {1,2,3,3,'a','a','b'}


>>> setB
{1, 2, 3, 'a', 'b'}

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

Example 2 (dual selection):


>>> def selection(x,y):
a=x
b=y
if (a > b):
print(a, " greater than ", b)
else:
print(b, " greater than ", a)

>>> selection(3,2)
3 greater than 2

Example 3 (multi selection):


>>> def selection2(x,y, z):
a=x
b=y
c=z
if ((a > b) and (a > c)):
print(a, " is largest number ")
elif ((b > a) and (b > c)):
print(b, " is largest number ")
else:
print(c, " is largest number ")

>>> selection2(4,2,5)
5 is largest number

Example 4 (multi selection):

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():

numb1 = eval(input("Enter first number : "))


numb2 = eval(input("Enter second number : "))
operator = input("Enter operator, +, -, *, /, %, **")
operation(numb1,numb2,operator)
main()

>>> import prog5


Enter first number : 5
Enter second number : 2
Enter operator, +, -, *, /, %, **/
5 / 2 = 2.5
>>> prog5.main()
Enter first number : 5
Enter second number : 2
Enter operator, +, -, *, /, %, ****
5 ** 2 = 25

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

Example 5 (using dictionary like switch…case):

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"}

mnth = eval(input("Enter the month : "))

print("The month of ", mnth, " is ", month[mnth])


main()

Output :
Enter the month : 5
The month of 5 is MAY

Repetition in
Python using
for … in
range(…)

The loop starts from 0


>>> import ProgRange
0 x 2 = 0
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
>>> ProgRange.repttion()
0 x 2 = 0
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8

second option is by setting the loop numbers


>>> def progRep():
for i in [1,2,3,4,5]:
print(i," x 2 = ",(i*2))
>>> progRep()
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5 x 2 = 10

Third option is by setting the the starting, ending and step


>>> def rep():
for i in range(1,10,3): #step/jumper by 3
print(i)

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

Repetition in Example 1:[counter loop]


Python using def main():
while x=0 #initialization
sum=0

while (x!= 5): #condition


numb = eval(input("Enter a number : "))
sum = sum + numb
x=x+1 #counter

print("The summation is {0:0.2f}".format(sum))

main()

>>> import prog6


Enter a number : 6
Enter a number : 9
Enter a number : 8
Enter a number : 4
Enter a number : 6
The summation is 33.00

Example 2:[sentinel loop]


def kira(a,b):
return (a+b)

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()

>>> import prog7


Enter a number :6
Enter a number again :5
Result is 11
Enter 1 to continue or 0 to stop :1
Enter a number :4
Enter a number again :9
Result is 13
Enter 1 to continue or 0 to stop :0

Example 3:[implementation of lists or array]


def main():
marks = [45,34,38,42,42,26,43,41,40,21]
x=0
cnt=0

while (x < 10):


if (marks[x] < 25):
cnt=cnt+1
x =x + 1

14
print("Total less than 25 marks ",cnt)

main()

>>> import prog8


Total less than 25 marks 1

Example 4:[using the while loop but looks like a do..while]

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():

number = eval(input("Enter a number : "))

output(number)
main()

Output:
Enter a number : 5
5
6
7
8
9
10

Format the
numbers as int
or float

>>> import formatnumbers


Enter any number : 9.6
Enter any number again : 12
The number in integer : 9
The number in float : 12.0

Format until 2 decimal places


def main():
x = eval(input("enter a number : "))
y = eval(input("enter a number again : "))
z = x / y
print("The result is {0:0.2f}".format(z))
main()

>>> import formatdecimals


enter a number : 1
enter a number again : 3
The result is 0.33

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

Save the file


as prog1.py

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 kira2(a): #function procedure with return value


zakat = a * 0.025
return zakat

def main():
workingdays = eval(input("Number of working days : "))
rateperdays = eval(input("Rate per days : RM "))
wage = kira1(workingdays,rateperdays)
zakat = kira2(wage)

print("Total wage RM {0:0.2f}".format(wage))


print("Total zakat RM {0:0.2f}".format(zakat))
main()

>>> import prog2


Number of working days : 25
Rate per days : RM 35.20
Total wage RM 880.00
Total zakat RM 22.00

16
Example 2:
def cnvrt(x): #function procedure with return value
change = x * 0.10
return change

def display(name,mark,converts): #proper procedure without return (void)


print("Name is {0}, and mark is {1}, and weightage is
{2:0.2f}".format(name,mark,converts))

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()

>>> import prog3


Enter your name : jamal othman
Enter your mark : 65
Name is jamal othman, and mark is 65, and weightage is 6.50

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

print(" First number is : ",a)


print(" Second number is : ",b)
print(" Third number is : ",c)

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

print("Before function call",s,num,d)

fun(s,num,d)

print("After function call",s,num,d)


Output:
Before function call [1, 2, 4] {'name': 'john'} {4, 5, 6}
Inside function call [1, 2, 4, 5] {'name': 'harry'} {1, 2, 4, 5, 6}
After function call [1, 2, 4, 5] {'name': 'harry'} {1, 2, 4, 5, 6}

Class in Example 1 [Class of Student is written on console]


>>> class Student:
Python def __init__(self,studid,studname): # __ is double underscore on left-right
self.studid = studid # __ for constructor
self.studname = studname

>>> ali = Student(1234,"Ali Bin Abu Bakar")


>>> amin = Student(3482,"Amin Bin Ibrahim")
>>> ali.studid
1234
>>> ali.studname
'Ali Bin Abu Bakar'

Example 2 [Class of Student is written in editor]


class Student:
#constructor
def __init__(self,studid,studname):
self.studid = studid
self.studname = studname

#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

def main(): # simultaneous assignment


stid, stname = getData() # the caller assigned to multiple variables,
stud1 = Student(stid,stname)
print("Student id : ",stud1.getStudID())
print("Student name : ",stud1.getStudName())
main()

>>> import progOO


Enter student id : 1232
Enter student name : jamal ali bin muhd jamoh
Student id : 1232
Student name : jamal ali bin muhd jamoh

Class with File name : player.py


class Player: #Parent
inheritance #constructor
and def __init__(self, playerID, playerName):
polimorphism self.playerID = playerID
self.playerName = playerName

#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)

class Footballer(Player): #child


#constructor
def __init__ (self, playerID, playerName, countryOrigin):
Player.__init__(self, playerID, playerName) # inherit from super
self.countryOrigin = countryOrigin

#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)

class Badminton(Player): #child


#constructor
def __init__ (self, playerID, playerName, playerLevel):
Player.__init__(self, playerID, playerName) # inherit from super
self.playerLevel = playerLevel

#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)

File name : playerApp.py


from player import *

def main():

plyr1 = Footballer(1234,"Sabri Fadhil","Malaysia")


plyr2 = Badminton(1283,"Misbun Sidek",3)

#polimorphisim
plyr1.printer()
plyr2.printer()

print("Retrieve player id #1 :",plyr1.getPlayerID())


print("Retrieve country origin player #1 :",plyr1.getCountryOrigin())

main()

Output:

>>> import playerApp


Player ID : 1234
Player Name : Sabri Fadhil
Country Origin : Malaysia
Player ID : 1283
Player Name : Misbun Sidek
Player Level : 3
Retrieve player id #1 : 1234
Retrieve country origin player #1 : Malaysia

Module library supports string handling, markup, mathematics, cryptography,


multimedia, GUIs, operating system services, Internet
services, compilation

21

You might also like