[go: up one dir, main page]

0% found this document useful (0 votes)
20 views151 pages

CSC202

The document provides an introduction to the Python and PHP programming languages. It discusses some of the key features and syntax of each language. It also provides comparisons between Python and PHP in terms of development environments, basic syntax and rules, data types, operators, and more.

Uploaded by

wmayo233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views151 pages

CSC202

The document provides an introduction to the Python and PHP programming languages. It discusses some of the key features and syntax of each language. It also provides comparisons between Python and PHP in terms of development environments, basic syntax and rules, data types, operators, and more.

Uploaded by

wmayo233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 151

FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE

(FUTA)

CSC 202

COMPARATIVE PROGRAMMING
LANGUAGES

Department of Computer Science


LECTURE 1

INTRODUCTION TO PYTHON AND PHP


PREAMBLE

⊡ There has been an upsurge in the number and varieties of programming languages
over the years. This is due mainly to some reasons which include but not limited to
the following:
i. Advancement in electronic technology which in turn leads to increased
miniaturization of computer hardware. This phenomenal growth has also made
computing devices to be more portable and affordable.
ii. Advent of mobile computing devices has also led to change is programming
paradigm
iii. Computer network and the internet have made computing to be applied beyond the
limit of traditional area of scientific and engineering applications.
iv. Growth in multimedia applications
v. Growth of e-commerce and m-commerce
vi. Every aspect of human endeavor is becoming more knowledge-based and
knowledge-driven
vii. Increased digitization of human activities
PREAMBLE CONTD.

• Thousands of programming languages have evolved, each trying to


provide solution to address particular needs of the computing world
and the society at large.
• In developing computing application for solving a problem,
programmers are faced with decision to choose the appropriate
programming language to adopt.
• There is therefore, the need to study the features of alternative
programming languages available in solving a particular problem.
• In this course, a comparative study of Python and PHP is presented.
Developed by Guido van Rossum in the Netherlands in the late ‘80s .
Python 2.0 was released on 16 October 2000. However, even though Python 3 has been released
since 3rd of December 2008, Python 2.7 still remains the most stable version and will be used throughout
this class.
It is an open-source, general-purpose, and high level programming language with remarkable power.
Simple, clean, readable and yet compact syntax.
Easy to learn and very well suitable for learning to program.
Due to its large user community, Python is experience continuous development .
Highly compatible with many leading programming languages and frameworks such as Java, C/C++,
C#.NET etc.
See www.python.org for more information on the Python language.
Python possesses many interesting technical and aesthetic features.
Support multiple programming paradigms e.g. structured, object-oriented, and functional
programming
Open Source
Interactive: provides interactive command line interface for instantaneous scripting
Easily extensible: third-party codes/library can easily be integrated
Interpreted language
Dynamic language: supports dynamic typing of variables, and objects and doesn’t require static
declaration of variables to be of particular types.
Platform independent i.e. Python can run on Windows, Apple Mac, Solaris, Linux etc.
Large library of codes: many special purpose third-party libraries are available
Support varieties of data structures and built-in types e.g. tupples, list, dictionaries, decorators,
iterators etc.
Large user support community
 Started as a Perl hack in 1994 by Rasmus Lerdorf, developed to PHP/FI (Personal Homepage/Form
Interpreter) 2.0
 Version PHP 3.0 was developed in 1997 with a new parser engine by Zeev Suraski and Andi
Gutmans changing the language’s name to recursive acronym PHP: Hypertext Preprocessor.
 New versions are being developed with improvements on previous versions including new features.
The latest version is PHP 7.2 released on 30 November, 2017
 PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language (i.e
gets interpreted) suited for web development and can be embedded into HTML.
 PHP scripts are executed on the server, makes the server generate dynamic output that is different
each time a browser requests a page. PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
 PHP is free to download and use.
 PHP supports a wide range of databases and runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.)
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have extension ".php"
 Can be downloaded from the official PHP resource: www.php.net
 The Five important characteristics that make PHP’s practical nature possible are:
Simplicity, Efficiency, Security, Flexibility, and Familiarity.

 PHP can generate dynamic page content


 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
PYTHON PHP
Text Editor  Text Editor

Notepad, Notepad++, Sublime Text 2, EditPad etc  Notepad, Notepad++, Sublime Text 2,

Integrated Development Environment EditPad etc

Python IDLE, Eclipse, EditPadPro, GEdit, JEdit, Komodo  Integrated Development Environment

IDE, Netbeans, PythonToolKit etc.  Eclipse PDT, phpDesigner, PHPEclipse,

Python Interpreter : www.python.org/download/ PhpED, PHPEdit, Komodo IDE,


Netbeans, etc.
 Web Server
 Database e.g MySQL
2

BASIC SYNTAX AND RULES


Case/Space Sensitivity
 Python codes are highly case sensitive so print is not equivalent to PRINT or Print
 The use of whitespaces is revered and so must be used appropriately. Indentation is important! You
must indent properly or your code will not work!
Variable Naming
 Python names can be as long as 255 characters
 starts with a letter or _ followed by a mix of alpha-numerics and the underscore.
 Python keywords are not allowed to be used as variable names.

Data Types Value Data Type

The following basic types are supported. 203 int

 Int, float, boolean, string 4.03 float

 complex types such as arrays, list, tupple, sets, dictionaries “futa” str
TRUE boolean
 user defined types are also supported.
Variables in python are dynamic i.e. they do not need to be declared as python automatically infers the
type based on the type of data stored them and how they are used in expressions. Python assigns
memory to a variable only when the variable is initialized.

1 >>> score = 60
2 >>> matno = “CSC/11/0036”
3 >>> height = 4.5
4 >>> isGraduated = False
5 >>> score
60 1 >>> comp = 4 + 3j
2 >>> print comp
3 (4+3j)
Python also supports scientific types such as Complex 4 >>> comp.real
Numbers and also provides means to carry out basic 5 4.0j
6 >>> comp.imag
operations on them. E.g. Getting the real, imaginary part or the 7 3.0
conjugate of the complex number. 8 >>> comp.conjugate()
9 (4-3j)
Python supports the following basic arithmetic operators

Operators Operation Precedence 1 >>> 23+6*3-9/6*2**3


2 33
3 >>> 5 % 3
+ Addition () 4 2
- Subtraction ** 5 >>> 10 / 3
6 3
* Multiplication */% 7 >>> 10.0 / 3
/ Division +- 8 3.3333333333333335
9 >>> 10 // 3
% Modulo 10 3
11 >>> 10.0 // 3
** Exponentiation
12 3.0
13 >>> 3 ** 2 ** 3
// Floor Division 14 6561
15 >>> a = 2 + 3j
16 >>> b = 3 + 6j
17 >>> c = a + b
18 >>> c
19 (5+9j)
Python supports the following basic relational operators;
All relational operators produce only boolean result!

Operators Operation 1 >>> a = 30


2 >>> b = 32
< Less Than 3 >>> a < b
4 True
> Greater Than 5 >>> a > b
== Equal To 6 False
<= Less Than or 7 >>> a >= b
Equal To 8 False
9 >>> b <= a
>= Greater Than or
10 False
Equal To
11 >>> a != b
!= Not Equal To 12 True
13 >>> a == 30
14 True
Python supports the following basic logic operators;
They are usually used to combine multiple groups of relational expressions and produce only Boolean
result!

Operators Operation 1 >>> (a<b) and (a>b)


2 False
and CONJUNCTION 3 >>> (b<=a) or (a != b)
4 True
5 >>> not(a == 30)
or DISJUNCTION
6 False
7 >>> (a<b) and (a>b) and (not((b<=a) or (a
not NEGATION 8 != b)))
False
The # character is used to comment a line of code in python. Therefore anything after a # is ignored by
the python compiler
Comments can be used
 to describe what is going to happen in a program or
 Document information about a program such as the author and date or place
 Can also be used to turn off a portion of codes temporarily or permanently

1 # Author: Kolawole Gbolahan


2 # Date: 17/06/2018
3 # Remark: Program to compute the average of 3 numbers
4
5 # This portion assigns values to the variables
6 x = 300
7 y = 456.78
8 z = 2345
9
10 w = x + y + z # this line computes the sum
Python has modes:
 The Interactive Mode:
 This mode allows users to type commands into a shell prompt (DOS-like interface)
 In this mode it prompts for the next command with the primary prompt, usually three greater-than
signs (>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...).
The interpreter prints a welcome message stating its version number and a copyright notice before
printing the first prompt:
 The Code/Normal Mode:
 While the interactive mode is appropriate for short scripting tasks or coding. The code mode provides
an environment for writing long and complete programs.
 The code mode provide code highlighting, intellisense and auto-suggestion features.
Using Print : the print keyword can be used to display program output as shown in the figure below;

1 >>> name = "Wole"


2 >>> age = 56
3 >>> print name
4 Wole
5 >>> print name,age
6 Wole 56
7 >>> print name;age
8 Wole
9 56
10 >>> print "Name: "+ name
11 Name: Wole
12 >>> print "Age: "+ str(age)
13 Age: 56
raw_input() function takes a single parameter that represents the prompt message guiding users on
what to input as shown above. This function returns any input as string values and must be converted to
appropriate data types using either int() or float().
input() function is similar to raw_input(). The major difference is that it evaluates whatever the user
inputs.

1 >>> matric = raw_input("What is your matric number?")


2 What is your matric number?CSC/05/6442
3 >>> print matric
4 CSC/05/6442
5 >>> score_test = raw_input("What is your test score?")
6 What is your test score?20
7 >>> score_exam = raw_input("What is your exam score?")
8 What is your exam score?56
9 >>> total_score_CSC201 = int(score_test) + int(score_exam)
10 >>> print total_score_CSC201
11 76
Case/Space Sensitivity
 PHP is case sensitive i.e $STATE , $State, $state are all different.
 PHP is whitespace insensitive i.e it almost never matters how many whitespace characters you have
in a row. one whitespace character is the same as many such characters.
 PHP commands/statements ends with a semicolon;
 A PHP script starts with <?php and ends with ?>

1 <?php
2 echo “welcome to PHP class”;
3 ?>
Variable Naming
 All variables in PHP are denoted with a leading dollar sign ($).
 Variable names must start with a letter of the alphabet or the _ (underscore) character.
 Variable names can contain only the characters a-z, A-Z, 0-9, and _ (underscore).
 Variable names may not contain spaces. If a variable must comprise more than one word, it should
be separated with the _ (underscore) character (e.g. $my_name).
 Variable names are case-sensitive e.g $newprogam is not the same as $Newprogram.
Variables and Data Types
Variables are assigned with the = operator, with the variable on the left-hand side and the expression
to be evaluated on the right.
Variables in PHP do not have intrinsic types i.e a variable does not know in advance whether it will be
used to store a number or a string of characters.
PHP supports eight data types which are : Integers, Doubles, Booleans, NULL, Strings, Arrays,
Objects, Resources

1 <?php
2 $classattendance = 45;
3 $class_name = “physics”;
echo “welcome to PHP class”;
?>
Operators are the mathematical, string, comparison, and logical commands such as plus, minus, multiply,
and divide.
PHP supports arithmetic, assignment, logical and relational/comparison operators.

ARITHMETIC OPERATORS LOGICAL OPERATORS

Operator Operation Example Operator Operation Example

+ Addition $p + 1 && And $K ==2 &&


$G ==45
- Subtraction $p – 3 And Low- $K ==2 and
* Multiplication $p * 67 precedence $G ==45
and
/ Division $p / 8 || Or $K ==2 || $
% Modulo $p % 2 K<45
or Low- $K ==2 or
++ Increment ++$p
precedence or $K<45
-- Decrement --$p ! Not ! ($K == $G)
xor Exclusive or $K xor $G
RELATIONAL OPERATORS

Operator Operation Example

== Is equal to $f ==5
!= Is not equal to $f !=8

> Is greater than $f>7

< Is less than $f<4

>= Is greater than $f>=17


or equal to
>= Is less than or $f<=89
equal to
ASSIGNMENT OPERATORS

Operator Example Equivalence

= $s = 12 $s = 12
+= $s += 3 $s = $s + 3

-= $s -= 4 $s = $s - 4

*= $s *= 8 $s = $s * 8

/= $s /= 12 $s = $s / 12

.= $s .= $d $s = $s . $d
There are two ways of using Comments in PHP:
Preceding a single line of code with a pair of forward slashes
Multiple-line comments : Here, /* and */ pairs of characters are used to open and close comments almost
anywhere inside the code.
However, these characters /* and */ cannot be used to comment out a large section of code that already
contains a commented-out section that already used the characters. It results into an error if this occur. i.e.
you cannot nest comments

1 <?php
2 // This is a new line
3
4 /* This is a section
5 of codes that will no longer
6
7 be needed */
8
9 ?>
PHP, there are two basic ways of displaying the output of a program.

The echo Statement


It has no return value
It can take multiple parameters (though not rarely in use)
It’s marginally faster than print
It can be used with or without parentheses; echo or echo()
It is a purely PHP language construct

The print Statement


print has return value of 1 and therefore can be used in a more complex expressions.
It’s a function-like construct that takes only one argument
It can be used with or without parentheses
1 <?php
2
3 print "<h2>Displaying Output!</h2>";
4 print "Hello Class!<br>";
5
6 print "I'm enjoying this lecture!";
7 ?>

1 <?php
2
3 echo ”<h2>PHP is Interesting!</h2>”;
4 echo ”Hello Everyone!<br>”;
5
6 echo ”This”, “is”, “going”, “to”, “be”, “fun.”;
7 ?>
Syntax Python PHP
Operators Arithmetic, Logical, Relational, Arithmetic, Logical, Relational,
Assignment Assignment
Basic Data types Boolean, Integer, Float, String Boolean, Integer, Float, String
Input statement raw_input, input no direct input statement
Output Statement print() echo(), print()
Comments # /*…..*/
Environment Interactive, code mode Code mode
Case Sensitivity Case sensitive case sensitive
Delimiters no delimiter (whitespace) ;
3

CONTROL STRUCTURES
Control structures are programming constructs for controlling the flow of execution of a program and
change the behavior of the program accordingly. Normally, statements in a program (including the ones
we have written so far) are executed sequential order.

Control structures enable the programmer to specify the order in which programs are to be executed i.e.
skip some parts of the code, repeat some parts of the code, transfer of control to another program etc.

There are two major categories of control structures:


 Selection Structures
 Repetition Structures
The selection structures enable conditional execution of code i.e. the code makes decision depending on
a condition being met. The program selects one of two or more possible paths depending on the outcome
of an already tested condition(s).

The condition must of necessity be a


statement that evaluates to a Boolean.
There are several constructs that can be
used to achieve such conditional execution
of code.
The 3 available selection structures in Python are
The if Statement: It enables Python to choose among alternative courses of action. It either performs
(selects) an action if a condition (predicate) is true or skips the action if the condition is false. It is a
single-selection structure because it selects or ignores a single path of action.
Syntax: The general form of an if-structure is:
if (expression):
<python statements>
<python statements>

1 >>> Grade = 87
2 >>> if(Grade >= 60):
3 print "Passed“
4
5 Passed
The if…else Statement: The if-else selection structure allows the programmer to specify an action to be
performed when a condition is true and a different action to be performed when the condition is false.
Syntax:
The general form of an if/else structure is:
if (expression):
<python statements1>
else:
<python statements2>
1 Grade = 60
2 if (Grade >= 40):
3 print("Pass !")
4 else:
5 print("Fail !")
6
7 >>>
8 Pass !
The if…..elif……else Statement:
This allows for a case when we have multiple conditions and corresponding actions to perform
Syntax: The general form of an if..elif..else structure is:
if (expression 1):
<python statements1>
elif(expression 2): 1 Grade = 60
2 if (Grade >= 70):
<python statements2>
3 print("A")
else: 4 elif (Grade >= 60):
5 print("B")
<python statements3>
6 elif (Grade >= 50):
7 print("C")
8 elif (Grade >= 40):
You can have as many elif as needed
9 print("D")
10 else:
11 print("F")
12 >>> B
The “if” statement checks the truthfulness of an expression and, if the expression is true, evaluates the
statement. And if it evaluates to false - it'll ignore it
1 <?php
2 $num = 4
3 if ($num> 0){
4 echo “the number is positive”;
5 }
6 ?>

To specify an alternative statement to execute when the expression is false Use the “else” keyword:

1 <?php
2 $num = 4
3 if ($num> 0){
4 echo “the number is positive”;
5 }
6 else{
7 echo “the number is not positive”;
8 }
9 ?>
elseif extends an if statement to execute more than one alternative statements in cases where there are
several conditions to be met.
1 <?php
2 $num = 4
3 if ($num> 0){
4 echo “the number is positive”;
5 }
6 elseif($num == 0){
7 echo “the number is zero”;
8 }
9 else{
10 echo “the number is negative”;
11 }
12 ?>

TERNARY CONDITIONAL OPERATOR: The ternary conditional operator (? :) can be used to shorten
simple true/false tests.

1 <?php echo ($user_input> 0) ? "the number is positive" : "the


number is not positive"; ?>
The switch statement is similar to a series of IF statements on the same expression. In many
occasions, the same variable (or expression) is compared with many different values. The value (case)
that evaluates to true is executed up to the first break keyword it finds. If none match, and a default is
given, all statements following the default keyword are executed, up to the first break keyword
encountered.
1 <?php
2 switch ($user_input){
3 case 0:
4 echo “the number is a multiple of 3”;
5 break;
6 case 1:
7 echo “the number is not a multiple of 3”;
8 break;
9 case 2:
10 echo “the number is not a multiple of 3”;
11 break;
12 default:
13 echo “input is invalid”;
14 break;
15 ?>
A repetition structure allows the programmer to specify that a program should repeat an action while
some condition remains true.
The while Statement: The while statement executes a suite until a condition is met. The expression or
condition should evaluate to false at some point, otherwise infinite loop occurs and the program hangs.
Syntax:
The general form of a while statement is:
while (expression):
<python statements1>
else:
<python statements2>
1 >>> num = 3
Note: The else clause is optional. 2 >>> while(num < 0):
3 print “counting”, num
4 num=num-1
5
counting 3
counting 2
counting 1
The for Statement
Sometimes it is desire that a set of instructions is to executed repeatedly, the Python for statement allow
us to iterate through a sequence of values.
Syntax:
The general form of a while statement is:
for <var> in <sequence>:
<body: python statements>
<body: python statements >
1 >>> num = range(3)
2 >>> for x in num:
3 print “counting”, x
4
counting 3
counting 2
counting 1
The range() function: The function range() is used to create a consecutive sequence of values: It
produces a list of numbers starting with 0 and continuing up to, but not including a specified maximum
value.
The different mode of operation is shown below;
range ( n)
Generates values starting from 0 up to n (but not including n)
range ( start, n)
Generates values starting from start up to n but not including n
range ( start, n, step )
1 >>> print range(6)
2 1,2,3,4,5
3 >>> print range(1,11)
4 1,2,3,4,5,6,7,8,9,10
5 >>> print range(0,20,3)
6 0,3,6,9,12,15,18
The simplest form of repetition in PHP is the while statement:

If the expression evaluates to true, the statement is executed and then the expression is re-evaluated (if
it is still true, the body of the loop is executed again, and so on). The loop exits when the expression is
no longer true, i.e., evaluates to false.

1 <?php
2 $i = 1;
3 while ($i<= 10) {
4 $i=Si-1;
5 echo $i;
6 }
7 ?>
do...while loops are very similar to while loops, except the truth expression is checked at the end of
each iteration instead of in the beginning.

The main difference from regular while loops is that the first iteration of a do..while loop is guaranteed to
run at least once(the truth expression is only checked at the end of the iteration)

1 <?php
2 $i = 1;
3 do {
4 $i=Si-1;
5 echo $i;
6 } while ($i<= 10)
7 ?>
The for statement is similar to the while statement, except it adds counter initialization and counter
manipulation expressions, and is often shorter and easier to read than the equivalent while loop.

The expression start is evaluated once, at the beginning of the for statement. Each time through the
loop, the expression condition is tested. If it is true, the body of the loop is executed; if it is false, the loop
ends. The expression increment is evaluated after the loop body runs.

1 <?php
2 for ($i=0; $i<= 10; $i++) {
3 echo $i;
4 }
5 ?>
foreach works only on arrays, and will issue an error when you try to use it on a variable with a different
data type or an uninitialized variables. The foreach statement allows you to iterate over elements in an
array.

1 <?php
2 $i=array(1,2,3,4,5,6,7,8,9)
3 foreach ($num as $i) {
4 echo $num;
5 }
6 ?>
Control Structures Python PHP
Selection if, if….else, if…elseif…else if, if….else, if…elseif…else,
switch

Repetition while, for while, do….while, for, foreach


4

SUBPROGRAMS AND PARAMETER


PASSING
A subprogram is a named block of code that performs a specific task, possibly acting upon a set of
values given to it, or parameters, and possibly returning a single value.

 Each subprogram has a single entry point i.e. a starting point.


 Each subprogram can have one or more exit points
 A subprogram call is an explicit request that the subprogram be executed.
 When a subprogram is called, the calling program is suspended during execution of the called
subprogram.
 Control always returns to the caller when the called subprogram’s execution terminates.
 There are functions that come pre-packaged with programming languages. These are called
inbuilt functions. Users can also create their own user defined functions specifying its actions.
 A subprogram definition describes the interface to and the actions of the subprogram
abstraction.
 The header is the first part of the definition, including the name, the kind of subprogram, and the
formal parameters.
 The parameter profile (also signature) of a subprogram is the number, order, and types of its
parameters
 Parameters are variables/ values passed to a subprogram. A formal parameter is a dummy
variable listed in the subprogram header and used in the subprogram while an actual parameter
represents a value or address used in the subprogram call statement
Subprograms in python are called functions. The keyword “def” is used to create a named function.

1 >>> def greet(name) :


2 >>> print “How are you? ”+name

definition keyword function body parameter function name

Python provides some out-of-the-box built-in functions for performing some common programming
tasks called. Some common functions are :int(), float(), str(), type(), bool(), len(), chr(), min(), max(),
range(), hex(), bin(), abs(), ord(), pow(), raw_input(), sum(), format(), cmp(), dir(), oct(), round(),
print()
Python also allows programmers to define user-defined functions.
 perform a task or set of tasks
 no return a value
 has a function name and may have zero or more parameters
Built in Functions User Defined Functions
1 >>> len("Technology") 1 def print1to10():
2 10 2 for i in range(1,11):
3 >>> chr(65) 3 print i,
4 'A' 4
5 >>> ord('B') 5 # to call the function
6 66 6 print1to10()
7 >>> range(1,10) 7
8 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
9 >>> range (1,20, 3) 8 1 2 3 4 5 6 7 8 9 10
10 [1, 4, 7, 10, 13, 16, 19]
11 >>> range (20,1,-5)
12 [20, 15, 10, 5]
13 >>> sum([3,2],0)
14 5
15 >>> sum(range(1,5), 0)
16 10
17 >>> round(0.89377,3)
18 0.894
Functions can also accept values to be used as part as their execution, such values are stored in
variables. The variables are called parameters. Python has four mechanisms for passing parameters

 Normal parameters: Functions can accept values of ay data type i.e. int, float, string, list, tuples etc.
as parameters.

1 def findAverage(num1, num2):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+num2) / 2
4 print “average is “, average

5 #Calling this function:


6 findAverage(4,8)
7 >>>
8 Average is 6
 Parameters with default values: Functions can have optional parameters, also called default
parameters. Default parameters are parameters, which don't have to be given, if the function is called.
In this case, the default values are used.

1 def findAverage(num1, num2=5):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+num2) / 2
4 print “average is “, average

5 #Calling this function:


6 findAverage(4,8)
7 findAverage(9) #the default value for num2 is used
8 >>>
9 Average is 6
10 Average is 7
 Parameter list (*args): There are many situations in programming, in which the exact number of
necessary parameters cannot be determined beforehand. Python uses tuple references. An asterisk
"*" is used in front of the last parameter name to denote it.

1 def findAverage(*num):
2 ‘’’A function to calculate the average of numbers ’’’
3 sum=0
4 if len(num)==0:
5 return 0
6 else:
7 for number in num:
8 sum+=number
9 average=sum/len(num)
10 print “average is “, average
11
#Calling this function:
12 findAverage(4,8,4,6,3,2,5,5,8)
13 findAverage(4,7,8,4,3)
>>> Average is 5
 Keyword parameters (**kwargs): Using keyword parameters is an alternative way to make function
calls. The definition of the function doesn't change. Keyword parameters can only be those, which are
not used as positional arguments.

1 def findAverage(num1, num2, num=3, num4=9):


2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+ num2+ num3+ num4) / 4
4 print “average is “, average

5 #Calling this function:


6 findAverage(3,5)
7 findAverage(8,7, num4=10) #the default value for num3 is used
8 >>>
9 Average is 5
10 Average is 7
There result of the computation in a subprogram might be needed in the calling program. The “return”
statement is used to return values from a function.
1 def findAverage(num1, num2):
2 ‘’’A function to calculate the average of numbers ’’’
3 average=(num1+ num2+ num3+ num4) / 2
4 return average

5 #Calling this function:


6 vg=findAverage(2,5)
7 print “the mean of the numbers is”, avg
8 >>> The mean of the numbers is 6

There are special functions in Python called “lambda”. They are functions that have no name (i.e.
anonymous), contain only expressions and no statements and occupy only one line. They are
convenient to use. A lambda can take multiple arguments and can return (like a function) multiple values

1 determinant = lambda a, b, c: (b ** 2) + (4*a*c)


2 print determinant(4, 5, 6)
3 >>> 281
In PHP, functions are defined using the “function” keyword. The function name can be any string that
starts with a letter or underscore followed by zero or more letters, underscores, and digits.

Function names are case-insensitive; that is, you can call the sin() function as sin(1), SIN(1), SiN(1), and
so on, because all these names refer to the same function. By convention, built-in PHP functions are
called with all lowercase.

1 <?php
2 function findAverage(){
3 $average=0;
4 echo “average is “, $average;
5 }
6 ?>
In PHP, There are several kinds of parameters

 Default parameters: To specify a default parameter, assign the parameter value in the function
declaration. The value assigned to a parameter as a default value cannot be a complex expression; it
can only be a scalar value.

1 <?php
2 function findAverage($num1, $num2, $num3=7){
3 $average=($num1 + $num2+$num3)/3;
4 return $average;
5 }
6 ?>
 Variable Parameters: A function may require a variable number of arguments. To declare a function
with a variable number of arguments, leave out the parameter block entirely

1 <?php
2 function findAverage(){
3 if (func_num_args() == 0) {
4 return 0;
5 }
6 else {
$sum = 0;
for ($i = 0; $i<func_num_args(); $i++) {
$sum += func_get_arg($i);
}
$average=$sum/func_num_args();
return $average;
}
}
?>
PHP provides three functions you can use in the function to retrieve the parameters passed to it.
 func_get_args() returns an array of all parameters provided to the function;
 func_num_args() returns the number of parameters provided to the function;
 func_get_arg() returns a specific argument from the parameters.

For example:
$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_number);
 Missing Parameters: PHP allows the passing of any number of arguments to the function. Any
parameters the function expects that are not passed to it remain unset, and a warning is issued for
each of them:

1 <?php
2 function findAverage($num1, $num2, $num3=7){
3 $average=($num1 + $num2+$num3)/3
4 return $average
5 }
6 ?>
Passing Parameters by Value
This means the value of the parameter is copied into the function i.e. the function has access to a copy of
the value not the original .The function is evaluated, and the resulting value is assigned to the appropriate
variable in the function. In all of the examples so far, we’ve been passing arguments by value.

Passing Parameters by Reference


Passing by reference gives a function direct access to a variable. you indicate that a particular argument
of a function will be passed by reference by preceding the variable name in the parameter list with an
ampersand (&).
1 <?php
2 function findAverage(&$num1, &$num2,){
3 $average=($num1 + $num2)/2
4 return $average
5 }
6 ?>
To return a value by reference, both declare the function with an & before its name and when assigning
the returned value to a variable:

1 <?php
2 function &findAverage($num1, $num2, $num3){
3 $average=($num1 + $num2+$num3)/3
4 return $average
5 }
6 ?>
PHP allows the definition of localized and temporary functions. Such functions are called anonymous
functions or closure. It is defined using the normal function definition syntax, but assign it is then assigned
to a variable or pass it directly.

1 <?php
2 function findAverage($num1, $num2, $num3, function(){ return
3 $sum=$num1 + $num2+$num3)}){
4 $average=($num1 + $num2+$num3)/3
5 return $average
6 }
?>
Python PHP
Function Keyword def function
Parameter Passing pass by reference pass by value, pass by
reference
Types of parameter normal, default value, Variable, default, missing
parameter list, keyword
Special function Lambda Anonymous function
5

DATA STRUCTURES
Data Structure is a collection of data objects characterized by how the objects are accessed. It is an
Abstract Data Type that is implemented in a particular programming language.

Basic Terms
Interface − Each data structure has an interface. Interface represents the set of operations that a data
structure supports. An interface only provides the list of supported operations, type of parameters they
can accept and return type of these operations.

Implementation − Implementation provides the internal representation of a data structure.


Implementation also provides the definition of the algorithms used in the operations of the data structure.
Data type is a way to classify various types of value which determines
 the values that can be used with the corresponding type of data
 the type of operations that can be performed on the corresponding type of data.

There are two data types :

 Built-in Data Type: Those data types for which a language has built-in support
 Derived Data Type: Those data types which are implementation independent as they can be
implemented in one or the other way are known as derived data types. These data types are normally
built by the combination of primary or built-in data types and associated operations on them.
Integers
You can use an integer represent numeric data, and more specifically, whole numbers from negative
infinity to infinity, like 4, 5, or -1.
Float
"Float" stands for 'floating point number'. You can use it for rational numbers, usually ending with a
decimal figure, such as 1.11 or 3.14.

1 # Floats 1 # Returns the quotient


2 x = 4.0 2 print(x / y)
3 y = 2.0 3 # Returns the remainder
4 # Addition 4 print(x % y)
5 print(x + y) 5 # Absolute value
6 # Subtraction 6 print(abs(x))
7 print(x - y) 7 # x to the power y
8 # Multiplication 8 print(x ** y)
9 print(x * y) 9
Strings are collections of alphabets, words or other characters. In Python, you can create strings by
enclosing a sequence of characters within a pair of single or double quotes. For example: 'cake', "cookie",
etc.
Operation
 The + operation on two or more strings to concatenate
 The * operation to repeat a string a certain number of times:
 Slice operation on strings, which means that you select parts of strings
 Python has many built-in methods or helper functions to manipulate strings. Such as
 Retrieve the length of a string in characters.
 Check if a string contains numbers etc.
1 #concatenate 1 #length of a string
2 x = 'Cake' 2 str1 = "Cake 4 U"
3 y = 'Cookie' 3 str2 = "404"
4 x + ' & ' + y 4 len(str1)
5 >>>'Cake & Cookie‘ 5 >>>8
6 6
7 #repeat 7 str1.isdigit()
8 x * 2 8 False
9 >>>'CakeCake' 9 str2.isdigit()
>>>True
# Range Slicing
z = y[2:]
print(z)
>>>‘okie‘

#Capitalize strings
str.capitalize('cookie')
>>>'Cookie‘
This built-in data type that can take up the values: True and False, which often makes them
interchangeable with the integers 1 and 0. Booleans are useful in conditional and comparison
expressions
1 x = 4
2 y = 2
3 x == y
4 >>>False
5 x > y
6 >>True
7 x = 4
8 y = 2
9 z = (x==y)

# Comparison expression (Evaluates to false)


if z: # Conditional on truth/false value of 'z'
print("Cookie")
else: print("No Cookie")
>>>No Cookie
Changing the data type of a variable from one data type to another is called "typecasting". There can
be two kinds of data conversions possible:

Implicit Data Type conversion


This is an automatic data conversion and the compiler handles this for you.
1 # A float
2 x = 4.0
3
4 # An integer
5 y = 2
6
7 # Divide `x` by `y`
8 z = x/y
9
# Check the type of `z`
type(z)
>>>float
Explicit Data Type Conversion
This type of data type conversion is user defined, which means you have to explicitly inform the
compiler to change the data type of certain entities. Note that it might not always be possible to convert
a data type to another. Some built-in data conversion functions that you can use here are: int(), float(),
and str().

1 x = 2
2 y = "this"
3 result = (y) + str(x)
4 print(result)
5 >>>this 2
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type. They correspond
to simple whole numbers, both positive and negative.
Double
They are decimal numbers. By default, doubles print with the minimum number of decimal places needed

Operations

1 # Double 1 # Returns the quotient


2 $x = 4.0; 2 echo $x / $y;
3 $y = 2.0; 3 # Returns the remainder
4 # Addition 4 echo $x % $y;
5 echo $x + $y; 5 # x to the power y
# Subtraction echo $x ** $y;
echo $x - $y;
# Multiplication
echo $x * $y;
Strings are sequences of characters.

1 <?php
2 $variable = "name";
3 $literally = 'My $variable will not print!';
4
5 print($literally);
print "<br>";

$literally = "My $variable will print!";


print($literally);
?>

This will produce following result:


My $variable will not print!
My name will print
These are certain character sequences beginning with backslash (\) and are replaced with special
characters.
Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
They have only two possible values either true or false. PHP provides a couple of constants especially for
use as Booleans: TRUE and FALSE.

1 <?php
2 if (TRUE){
3 print “this will always print <br>”;
4 }
5 else {
print “this will never print <br>”;
}
?>
Other data types can be used as Boolean by following these rules:
 If the value is a number; it is false if it is zero else it is “true”.
 If the value is a string; it is false if it is an empty string (has zero characters) or if it is the string "0",
else it is true.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true otherwise.
 For an object, containing a value means having a member variable that has been assigned a value.
 Valid resources are true (although some functions that return resources when they are successful will
return FALSE when unsuccessful).
 Don't use double as Booleans.
When you declare a variable in PHP, you do not specify its type. Its type depends on the value it currently
holds. we verify by using the gettype() function:

1 <?php
2 $val = 'Hello there!'; // assign string
3 echo gettype($val); // string
4 ?>

PHP provides a variety of methods for changing the type of a variable or temporarily changing the type
of the value it holds.
 The settype() Function changes the type of a variable. It is used for strings, integer, float, boolean,
array, object, and null. The variable will retain that type unless you either change the value of the
variable to another type, or use settype() again to assign another type to it.
1 <?php
2 $val = 24; // integer
3 // set $val type to string
4 settype($val, 'string');
// check type and value of $val
var_dump($val); // string(2) "24"
?>

 The strval() function can be used to convert a value to a string. the strval function returns a converted
value but does not change the type of the variable itself. Related functions are available for converting
to other types as well: intval, floatval, and boolval (for converting to integers, floating point numbers, and
booleans).

 Type casting to change the type of a variable. In order to cast a variable (or value) to another type,
specify the desired type in parentheses immediately before the variable you wish to convert. Casting
does not change the type of the variable. It only returns the converted value and makes no lasting
change, just as the conversion functions like strval. In addition to (string), the following casts are also
supported by PHP: (int), (bool), (float), (array), and (object).
Non-primitive types are the sophisticated members of the data structure family. They don't just store a
value, but rather a collection of values in various formats.

In the traditional computer science world, the non-primitive data structures are divided into:
 Arrays
 Lists
 Files

Array been the very basic one will be explained for python and PHP.
Arrays are not popular in Python, unlike PHP. In general, when people talk of arrays in Python, they are
actually referring to lists.
In Python, arrays are supported by the array module and need to be imported before it can be used. The
elements stored in an array are constrained in their data type. The data type is specified during the array
creation and specified using a type code, which is a single character.

1 import array as arr


2 a = arr.array("I",[3,6,9])
3 type(a)
4 array.array

Other Python Types Include


 Tuples
 Dictionary
 Sets
In PHP, arrays are named and indexed collections of other values. An array is a data structure that
stores one or more similar type of values in a single value.

1 <?php
2 /* First method to create array. */
3 $numbers = array( 3,6,9);
4
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>

Other PHP Types Include


Null
Object
Resource
Python PHP
Numeric Types Integers, float Integers, Double
Booleans TRUE, FALSE, 0 , 1 True, False, 0, 1, other data
types except double
Strings Single quote (‘..’), double Single quote (‘..’), double
quotes (“..”), triple quotes quotes (“..”)
(‘’’…’’’)
Escape sequences \n , \r , \t , \" , \\ \n , \r , \t , \" , \\ and \$
Determine data type type() gettype()
Changing data type int(), float(), and str() settype(), (string), (int), (bool),
(float), (array), (object), strval,
intval, floatval and boolval
Other types List, Tuples, Dictionary, Sets Array, Null, Object Resource
6

MODULES
A module (i.e. a reusable piece of software) is a file containing reusable code
 Modules lets you break code down into reusable functions and classes; then reassemble those
components into modules and packages. The larger the project, the more useful this organization
 A module allows you to logically organize your code. Grouping related code into a module makes the
code easier to understand and use.
 Many related modules can be grouped together into a collection called a package.

Advantages / Benefits of Using Modules


It allows you to logically organize your code.
Grouping related code into a module makes the code easier to understand and use.
It improves code maintainability.
Error containment i.e. it confines program error (s) to a section of the code.
It ensures code reusability.
Type of Modules
Standard Library Modules: is provided as part of the core language
User-defined Modules: usually created by developers or programmers.

The import Statement:


Any Python source file can be used as a module by executing an import statement in some other Python
source file. Three options are available:
Importing Modules from the Same Directory (or Folder):
Syntax: import module1 [, module2 [, ... moduleN ]
 A search path is a list of directories that the interpreter searches before importing a module. In this
case, it will include the path to the current working directory where the current program file is saved.
 At least one module name must be specified at the execution of the import statement, the square
bracket in the syntax means the second to the nth module are optional.
 After importation, you can access the names in the module using dot notation.
Module Name: greeting.py
1 def greet(name):
2 print “how are you today, “, name, “ ?”

Module Name: main.py


1 import greeting
2 greeting.greet(“Mary”)

Output:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win32Type "copyright", "credits" or "license()" for more
information.
>>> ============================ RESTART ===========================
>>> How Are You Doing Mary?
>>>
Instead of the import statement used in python, PHP uses the include or require statement. The
include (or require) statement takes all the text/code/markup that exists in the specified file and copies
it into the file that uses the include statement.

PHP include and require Statements:


It is possible to insert the content of one PHP file into another PHP file (before the server executes it),
with the include or require statement.

The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
Including Modules in PHP: -
Syntax: include 'filename'; or require 'filename';
 The execution of the above statement includes the file, provided it is available at the path specified
by the filename.
 The filename will be a single name .php if the file is in the same folder as the one we are including
into, else the full path to the file is represented by the file name.

Current File Name : newfile.php


1 <?php include ‘/C:/wamp64/www/test/modulefile.php';?>

Require is used when the file is required by the program while Include is used when the file is not
required and the program should continue when file is not found.
After inclusion, access to the variables and functions in the module are as if they were defined in the
program.
Module Name : greeting.php
1 <? php
2
function greet($name){
3
4 echo “How Are You Doing Mr $name ?”;
5
5 }
6 ?>

Main_Program : main.php Output


1 <? php 1 How Are You Doing Thomas?
2
include(“greeting.php”);
3
4 greet(“Thomas”);
5
6 ?>
A package contains related modules, sub-packages, sub-sub-packages and so on.
You can access module inside a package using dot notation e.g.
if module nature_of_root.py were saved in myPythonCodes, you will access it as:
myPythonCodes.nature_of_root.determinant(a, b, c)
where myPythonCode is the package name, nature_of_root is the module name and determinant(a, b, c)
is the function name.
To import a module from a different package, create an empty Python file _init_.py and save it in the
package you want to import from.
The script _init_.py runs when the package is imported.
Accessing a module in PHP is quite different from that of python
You can access module inside the project folder by just including it into your work.
if module nature_of_root.php were saved in the same folder as main.php, main.php will access the
module as:
include(nature_of_root.php);.
nature_of_root($a,$b,$c);
Python PHP

Module access import include, require

Package access import include


7

CLASSES
Classes are data structures representing real life objects, abstract entities or concepts e.g. car, animal,
shape, color etc. The characteristics/features/properties of these classes are called “attributes”, and the
actions that can be performed on these classes are called “methods”.

Example 1
Class: Vehicle
Attributes: numberOfWheels, steeringWheelType, brandName, vehicleType
Methods: drive(), serviceEngine(), paintBody()

Example 2
Class: Polygon
Attributes: area, perimeter, dimension, vertex, edges
Methods: calculateArea(), calculatePerimeter()
A class is defined as a user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and instance
variables) and methods. A class is a template for building objects.

An object (or instance) is a unique instance (or occurrence) of a class. The object contains all the
methods and attributes of the original class. However, the data for each object differs. The storage
locations are unique, even if the data is the same.

Instantiation is creating an instance of a class. The result is an object.

A very important feature of classes is that its methods can access and often modify its own attributes i.e.
each object has a view of “self” or “this” and is differentiated from other objects.
Python is a purely Object Oriented Language.

A class is defined in Python by using the keyword “class”. The class name must be followed by “:” and
then indented. Class names must conform to the rules for Python identifiers.

1 >>> class rectangle:


2 >>> print “this is a class”

It is standard practice to define classes in a distinct file. Instantiating or creating an object from your
class is done as shown below. If the class is to be used in another file, it has to be imported before it can
be instantiated. Ensure the two files are saved in the same folder.

1 >>> from rectangle import Rectangle


2 >>> first_rectangle = Rectangle()
>>> second_rectangle = Rectangle()
The attribute of a class are data/ variables called “properties” or “member variables”. There are two
types:
 Class variable: A variable that is shared by all instances of a class. Class variables are defined
within a class but outside any of the class's methods. Class variables are not used as frequently as
instance variables are. e.g numberOfRectangles in the example below
 Instance variable: A variable that is defined inside a method and belongs only to the current instance
of a class. e.g. self.length in the example below

1 >>> class Rectangle:


2 >>> numberOfRectangles=0
3 >>> print “the rectangles are ”, numberOfRectangles

4 >>> def set_length (self, new_length):


5 >>> self.length= new_length
The functions of a class are called “methods”.

 All methods of a class must accept as parameter “self”.

 It is standard practice to use getter and setter methods to modify the properties of a class.

 Methods use “self.var_name” to access the properties of the current object and to call other
methods on that object.

 The member variables and methods can be accessed using the dot notation “.”. However, it is
secure and safer to use the getter and setter methods when accessing member variables.
1 >>> class Rectangle:
2 >>> numberOfRectangles=0
3 >>> print “the rectangles are ”, numberOfRectangles

4 >>> def set_length (self, new_length):


5 >>> self.length= new_length
6 >>> def get_length (self):
7 >>> return self.length
8 >>> def set_ breadth (self, new_ breadth):
9 >>> self.breadth = new_ breadth
10 >>> def get_ breadth (self):
11 >>> return self.breadth
12 >>> def area(self):
13 >>> self.area = self.breadth * self.length
14 >>> return self.area
15 >>> def perimeter(self):
16 >>> self.perimeter = 2*( self.breadth * self.length)
17 >>> return self.perimeter
All objects have a special built-in method. It is automatically included by PHP in any object created
(even if it is not visible). It is called “constructor”.
 The constructor is called when an object is created to initialize the properties of an object on
instantiation i.e. give it default values.
 The values can either be passed as a parameter or it can explicitly specified.
 A constructor starts/ is designated as “__init__”.

1 >>> class Rectangle:


2 >>> numberOfRectangles=0
3 >>> print “the rectangles are ”, numberOfRectangles

(...other previous code…)

18 >>> def __init__(self):


19 >>> self.length =0
20 >>> self.breadth =0
PHP is historically a procedural language. However, it has been extended with some OOP features.
A class is defined in PHP by using the keyword “class”. The class definition must be enclosed in curly
brackets { }. Class names are case-insensitive and must conform to the rules for PHP identifiers. The
class name stdClass is reserved. .
1 <?php
2 class rectangle{
3 echo “This is a rectangle”;
4 }
5 ?>

It is good practice create your classes in a different PHP file. Instantiating or creating an object from your
class is done with the keyword “new”. If the class is to be used in another file, it has to be imported
before it can be instantiated
1 <?php include (“rectangle.php”); ?>
2 <?php
3 $first_rectangle = new rectangle();
4 $second_rectangle = new rectangle;
5 ?>
The attribute of a class are data/ variables called “properties”.

1 <?php
2 class rectangle{
3 var $length;
4 var $breadth;
5 var $area;
6 var $perimeter;
7 }
8 ?>

 The functions of a class are called “methods”.


 It is standard practice to use getter and setter methods to modify the properties of a class.
 The properties are accessed by using the “$this->var_name”. This lets PHP know that you are
referring to the variable inside the class.
1 <?php
2 class rectangle{
3 var $length;
var $breadth;
4 var $area;
5 var $perimeter;
6
7 function area(){
8 $this->area = $this->length * $this->breadth;
9 return $this->area;
10 }
11 function perimeter(){
12 $this->perimeter=2*($this->length *$this->breadth);
13 return $this->perimeter;
14 }

Continued in next slide


17
18 function set_length ($new_length){
19 $this->length =$new_length;
20 }
21 function get_length (){
22 return $this->length;
23 }
24 function set_breadth ($new_breadth){
25 $this->breadth =$new_breadth;
26 }
27 function get_breadth (){
28 return $this->breadth;
29 }
30 }
31 ?>
All objects have a special built-in method. It is automatically included by PHP in any object created (even if
it is not visible). It is called “constructor”. The constructor is used to initialize the properties of an object
on instantiation i.e. give it default values. PHP calls the constructor when an object is created. A
constructor starts with two underscores “__”.

1 <?php
2 class rectangle{
3 var $length;
4 var $breadth;
5 var $area;
6 var $perimeter;

… (other previous code)

32 function __construct(){
33 $this->length =0;
34 $this->breadth =0;
35 }
36 }
37 ?>
It refers to deriving a new class with little or no modification to an existing class. Inheritance is a
relationship between two or more classes where a derived class inherits properties and methods from a
preexisting class i.e. the new class is based on the already existing class. This also allows code to be
reusable.
Class: BigCats
Properties: legs, speed, strength, numberofTeeth
Methods: hunt(), hide(), giveBirth()

Class: Lion inheritsFrom BigCats


Properties: mane, habitat
Methods: roar(), formPride(), markTerritory()
Super Class: Also called Base Class or Parent Class is the class whose properties are inherited by
another class e.g. the BigCat class in the example
Sub Class: Also called the Derived Class or Child Class is the class that inherits properties from the super
class. e.g. the Lion class in the example
 To inherit the properties and methods from another class, include the parent class in a parenthesis
when defining the child class. In the example below, The Square class contains all the properties and
methods of the of the Rectangle class. Objects instantiated using the Square class can use these
methods and properties like it belongs to it

Module Name: parent.py


1 class Rectangle:
2 … (previous code)
3 class Square (Rectangle):
4 self.length=self.breadth

Module Name: main.py


1 from parent import Rectangle
2 first_square = Rectangle()
first_square.set_length(6)
print “the length is “, first_suare.get_length()
 Python supports multiple inheritance i.e. inheriting from more than one parent class. This is done by
adding the parents classes to the parenthesis when defining the child class. If an attribute is not found
in the class Square, it is searched in the first parent class, then the second parent class and so on.

Module Name: parent.py


1 class Rectangle:
2 … (previous code)
3 class Polygon:
4 self.numberOfSide=4
5 class Square (Rectangle, Polygon):
6 self.length=self.breadth
 Until recently, Python did not support abstract classes. It changed with the abc (Abstract Base Class)
module from the standard library. An abc module allows to enforce that a derived class implements a
particular method using a special “@abstractmethod decorator” on that method.

Module Name: parent.py


1 from abc import ABCMeta, abstractmethod
2 class Polygon:
3 __metaclass__ = ABCMeta
4 @abstractmethod
5 def area(self):
6 pass
7 class Square (Polygon):
8 def __init__(self, new_length):
9 self.length=new_length
10 def area(self):
11 self.area=self.length*self.breadth
PHP provides four means of implementing inheritance. Each means has its own special use. They are:
 Extending a class
To inherit the properties and methods from another class, use the “extends” keyword in the class
definition, followed by the name of the base class:

Module Name: parent.php Module Name: main.py


1 <?php 1 <?php include (“rectangle.php”);?>
2 class Rectangle{ 2 <?php
3 … (previous code) 3 $first_square = new Square();
4 } 4 $first_square->set_length(45);
5 class Square extends Rectangle{ 5 ?>
6 $this->length=$this->breadth;
7 }
8 ?>
9
Implementing an interface
Interfaces provide a way for defining contracts to which a class adheres; the interface provides method
prototypes and constants, and any class that implements the interface must provide implementations for
all methods in the interface. Interfaces are defined using the “interface” keyword. To declare that a class
implements an interface, include the “implements” keyword. A class can implement more than one
interface, separated by commas.
Module Name: parent.php
1 <?php
2 interface Polygon{
3 $numberOfSides;
4 $area;
5 function area();
6 }
7
8 class Square implements Polygon{
9 $length;
function area(){
$this->area=$this->length * $this->length;
return $this.area;
}
}
?>
Using Traits
Traits provide a mechanism for reusing code outside of a class hierarchy. It easily noticed that the classes
used in the sample code are related to each other in concept i.e. rectangle are related to squares, a
square is a type of polygon.

Traits allow you to share functionality across different classes that don’t (and shouldn’t) share a common
ancestor in a class hierarchy. A trait is defined using the “trait” keyword. To declare that a class should
include a trait’s methods, the “use” keyword is used and any number of traits, separated by commas.
Module Name: parent.php
1 <?php
2 trait Timer{
3 public log($logString){
4 $className = __CLASS__;
5 echo date("Y-m-d h:i:s", time()) . ": [{$className}]
6 {$logString}";
7 }
8 }
9 class Square {
uses Timer;
$length;
function __construct($new_length){
$this->length=$new_length;
$this->log("Square of length '{$this->length}'");
}
}
?>
Extending Abstract Classes
PHP also provides a mechanism for declaring that certain methods on the class must be implemented by
subclasses—the implementation of those methods is not defined in the parent class. In these cases, an
abstract method is added; in addition, if a class has any methods in it defined as abstract, it must also
declare the class as an abstract class. This is done using the “abstract” keyword. This is different from
interfaces in that some methods in an abstract can be implemented
Module Name: parent.php
1 <?php
2 abstract class Polygon{
3 $numberOfSides;
4 $area;
5 abstract function area();
6 function set_numberOfSides($new_numberOfSides){
7 $this-> numberOfSides =$new_numberOfSides;
8 }
9 }

class Square implements Polygon{


$length;
function area(){
$this->area=$this->length * $this->length;
return $this.area;
}
}
?>
Method overriding means to replace the parent’s method in the child class.
Class: BigCats
Properties: legs, speed, strength, numberofTeeth
Methods: hunt(), hide(), giveBirth()
Class: Lion inheritsFrom BigCats
Properties: mane, habitat
Methods: roar(), formPride(), markTerritory(), hunt()
The way a lion hunts is different from the way other big cat hunts.
Method Overloading is creating methods with the same name but differ in the type of input parameter.. It
is assigning multiple implementations to the same function name.
Class: Lion inheritsFrom BigCats
Properties: mane, habitat
Methods: roar(), formPride(), markTerritory(), hunt(zebra), hunt(hippotamus), hunt(rabbit).
The way a lion hunts a zebra is different from the way the lion hunts a rabbit, even if both are still hunting.
Method Overriding is achieved by providing the implementation of the method in the child class. The
parent method can still be accessed by the child class by using the “super” keyword.

Module Name: parent.py


1 class Rectangle:
2 … (previous code)
3 def perimeter(self):
4 self.perimeter=2*(self.length * self. breadth)
5 return self.perimeter
6 class Square (Rectangle):
7 def perimeter(self):
8 self.perimeter=4*self.length
9 return self.perimeter
Python does not explicitly support method overloading i.e. it does not allow two methods to have the same
name. However, the same goal is achieved by using “single dispatch generic funtions”.

Module Name: parent.py


1 def area(entity):
2 if entity==instanceOf(Rectangle):
3 Rectangle.area()
4 elif entity==instanceOf(Square):
Square.area()
Method overriding in PHP is achieved by providing the implementation of the method in the child class.

Module Name: parent.py


1 <?php
2 class Rectangle{
3 … (previous code)
4 function perimeter(){
$this->perimeter = 2*($this->length * $this-
>breadth);
return $this->perimeter;
}

}
class Square extends Rectangle{
$this->length=$this->breadth;
function perimeter(){
$this->perimeter = 4*$this->length;
return $this->perimeter;
}

}
?>
PHP's interpretation of "overloading" is different than most object oriented languages. Overloading
traditionally provides the ability to have multiple methods with the same name but different quantities and
types of arguments. Overloading in PHP provides means to dynamically "create" properties and methods.

PHP supports:
 the ability to call multiple methods with the same name but different quantities. See func_get_args
 the ability to call multiple methods with the same name but different types. Only variables can be
passed by reference, you can not manage a overloading for constant/variable detection.

PHP does not support


 the ability to declare multiple methods with the same name but different quantities.
 the ability to declare multiple methods with the same name but different types.
Method overloading is achieved by making a call to the magic method “ __call”. This method is
automatically called behind the scene.
Module Name: parent.py
1 <?php
2 class Shape{
3 const Pi = 3.142 ;
4 function __call($fname, $argument){
5 if($name == 'area'){
6 switch(count($argument)){
7 case 0 : return 0 ;
8 case 1 : return self::Pi * $argument[0]
9 case 2 : return $argument[0] * $argument[1];
}
}
}
}

$circle = new Shape();


echo "Area of circle:".$circle->area(5);
$rect = new Shape();
echo "Area of rectangle:".$rect->area(5,10);
?>
Python PHP

Class Yes Yes

Properties Instance varibles, member Properties


variables
Methods Yes Yes

Inheritance Subclass Subclass, interface, traits

Abstract class Not really, uses ABC module Yes

Method overriding Yes Yes

Method Overloading Not really, uses workaround Not really, using _call()
8

EXCEPTION AND ERROR HANDLING


Errors are mistakes in code or code execution. There are three types:

 Syntax Error: These are errors that have to do with using the wrong code, and usually is a result of
typos.

 Semantic Errors: occur because the meaning behind a series of steps used to perform a task is
wrong — the result is incorrect even though the code apparently runs precisely as it should.

 Logical Errors: occur when the developer’s thinking is faulty. In many cases, this sort of error
happens when the developer uses a relational or logical operator incorrectly. However, logical errors
can happen in all sorts of other ways, too. For example, a developer might think that data is always
stored on the local hard drive, which means that the application may behave in an unusual way.
Exceptions are errors that occur during runtime.

There are special constructs that are specifically for “graceful handling” of error i.e. the error is detected
without crashing your code.

Detecting an exception with a code statement is called catching an exception. The act of processing an
exception is called error handling or exception handling.
There are four means of handling errors and exceptions in Python:
 Syntax errors are easily highlighted by Python IDE for correction.

 try and except: Any block of code that might cause error is placed in the “try” block. Python starts by
executing the sequence of statements in the try block. If all goes well, it skips the “except” block and
proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the
sequence of statements in the except block.

1 >>> try:
2 >>> x=int(raw_input(“enter a number”))
3 >>> print x
4 >>> except ValueError:
5 >>> print “Please enter a valid number”
 The raise statement allows the programmer to force a specified exception to occur. The sole
argument to raise indicates the exception to be raised.

1 >>> try:
2 >>> x=int(raw_input(“enter a number”))
3 >>> print x
4 >>> raise ValueError
5 >>> except ValueError:
6 >>> print “Please enter a valid number”
 The finally statement: always executes, even when an exception occurs. You can place code to
perform other essential tasks such as close files etc. in the code block associated with this clause.

1 >>> x=0
2 >>> try:
3 >>> x=int(raw_input(“enter a number”))
4 >>> print x
5 >>> except ValueError:
6 >>> print “Please enter a valid number”
7 >>> finally:
8 >>> print “The value of x is ”, x
Python provides a wealth of standard exceptions that you should use whenever possible. These
exceptions are incredibly flexible, and you can even modify them as needed (within reason) to meet
specific needs
 EnvironmentError
 RuntimeError
 Exception  IOError
 AttributeError
 StopIteration  OSError
 EOFError
 SystemExit  SyntaxError
 ImportError
 StandardError  IndentationError
 KeyboardInterrupt
 ArithmeticError  SystemError
 LookupError
 OverflowError  SystemExit
 IndexError
 FloatingPointError  TypeError
 KeyError
 ZeroDivisionError  ValueError
 NameError
 AssertionError  NotImplementedError
 UnboundLocalError
PHP has built-in support for error handling. PHP has three severity levels of errors::
 E_NOTICE errors are minor, nonfatal errors designed to help you identify possible bugs in your code.
IN general, E_NOTICE error is something that works but may not do what you intended.
 E_WARNING errors are nonfatal runtime errors. They do not halt or change the control flow of the
script, but they indicate that something bad happened.
 E_ERROR errors are unrecoverable errors that halt the execution of the running script
PHP provides the following means of handling exceptions

 try - A code that may give an error should be in a "try" block. If the exception does not trigger, the
code will continue as normal. However if the exception triggers, an exception is "thrown“

 throw - This is how you trigger an exception. Each "throw" must have at least one "catch“

 catch - A "catch" block retrieves the exception and creates an object containing the exception
information. This is where the error is handled.
1 <?php
2 try{
3 $dbhandle = new PDO('mysql:host=localhost;
4 dbname=library',$username, $pwd);
5 doDB_Work($dbhandle); // call function on gaining a connection
6 $dbhandle = null; // release handle when done
7 }
8 catch (PDOException $error) {
9 echo "Error!: " . $error->getMessage() . "<br/>";
10 die();
}
?>
Exception Python PHP

Error Levels None Three severity levels

Try Yes Yes

Catch Yes Yes

Raise Yes No

Throw No Yes

Finally Yes Yes

Exception Classes Many exception classes Few Exception Classes


9

LANGUAGE COMPARISON
DESIGN PHILOSOPHY
 readability of the code
 concisely expressing an idea in fewer lines of code rather than the verbose way of expressing things.
 Allow a single obvious way to express a given task.

VERSIONS
Python has two versions : 2.x version and 3.x version.

INFLUENCES
 Python compiles to an intermediary code and this in turn is interpreted by the Python Runtime
Environment to the Native Machine Code similar to Java
 The initial versions of Python were heavily inspired from lisp (for functional programming constructs).
 Python had heavily borrowed the module system, exception model and also keyword arguments
from Modula-3 language.
DESIGN PHILOSOPHY
 To enhance websites and improve its performance.
 Another reason to create PHP was to monitor online data sources and related information.

VERSIONS
PHP is a server side scripting language
 PHP 2.0 (1995)
 PHP3 (1998) supports multiple platforms, web servers, and a wide number of databases.
 PHP4 (2000) improve speed and reliability over PHP3. Also reference and Boolean support, COM
support on Windows, output buffering, and expanded object oriented programming.
 PHP5 (2004) Powered by Zend Engine II. improved support of object-oriented programming and
provided a well-defined and consistent PDO interface to access databases, backward compatibility
with earlier version of PHP. Late binding feature was added to later version of PHP5 (V5.3).
Python language and its interpreter can be easily extended, there are several different packages of
python available catering to different purposes.

COMMON INTERPRETERS COMMON IDEs

 Cpython  IDLE
 pypy  pycharm
 jython  pydev
 iron python  aptana studio
 skulpt  komodo edit
 anaconda
The more common one are

 PHP Eclipse plugin is an open source add-on to the eclipse framework used to provide PHP tools.
Eclipse supports PHP GUI development by allowing PHP integration with HTML.

 Visual PHP is a complete PHP visual development environment designed for developers to quickly
create PHP web applications and web services. It is available for only Windows operating system.

 Adobe Dreamweaver is a web development tool developed originally by Macromedia in 1997 and
then acquired by Adobe Systems in 2005.
Features PHP Python
Programming imperative, functional, object Multi-paradigm: object-oriented,
paradigms oriented, procedural, reflective imperative, functional,
procedural, reflective
Memory PHP 5.3: GC Yes: Python Runtime
Management
Bounds checking Run time Run time
Static Type Checking No No. But we can have optional static
typing starting from version 3.0

Dynamic Type Checking Yes Yes.


Exception Handling Yes, they can throw exceptions Yes, via except/finally block. We can
and can also try and catch them have multiple except blocks.
Compiled/ Interpretation done at the web Code evaluated in 2 steps: compiled to
server level (tomcat apache) intermediate code and then interpreted
Interpreted
by Python environment
Features PHP Python
Conditional compilation Yes It is not built in.
But we can use import statements
inside conditional blocks.
Multiple No, Multiple class inheritance Python has full support for
Inheritance concept is replaced by multiple inheritance in classes.
interfaces
Web Server Microsoft IIS, apache tomcat Tornado,
Twisted Web, and adapters are
available for
Apache Servers.
Session Yes. PHP manages Yes. Sessions are managed
Management states using $_SESSION through cookies.
CRITERION 1: SECURE PROGRAMMING PRACTICES AND TYPING STRATEGIES

 Python and PHP are strongly dynamic typed languages


 The advantage in using a dynamic typed programming language is that it can be used for rapid
prototyping

CRITERION 2: WEB SERVICES DESIGN AND COMPOSITION

 Python and PHP can be used to write web services.


 PHP web services, does not need extra hardware resources on the target that will host these services.
CRITERION 3: OO-BASED ABSTRACTION AND ENCAPSULATION

Abstraction means hiding unnecessary details from the end user. Abstraction is generally achieved
through inheritance hierarchy.

 Python and PHP support abstraction through Classes.


 PHP has separate syntaxes for Abstract class, Interfaces, which Python lacks but there are
workarounds to implement Abstract classes and interfaces in Python.

Encapsulation is the process of hiding the class variables and exposing it through member functions.

 PHP provides encapsulation through private, public and protected access specifiers.
 Python has the worst support for encapsulation as all the class members are public.
CRITERION 4: REFLECTION
Reflection is a programming paradigm that allows developers to add/modify/edit/view system class
members at runtime. It is often used for debugging purposes.

 Reflection with PHP and Python allows immediate inspection of the interfaces, classes, methods
parameters and fields during execution. It also, enables creating instances, bind types to existing
objects, invoke methods, or directly access properties and fields.
 Python has support for reflection when it was first initiated, while PHP have added support for
reflection recently.

CRITERION 5: FUNCTIONAL PROGRAMMING

Both Python and PHP support functional programming.


CRITERION 6: SOURCE CODE SIZE

We will compare the source code sizes of the languages using “hello world” program

1 >>> print “Hello World” 1 <?php


2 echo “<p>Hello world”/p>;
3 ?>

Python PHP
Total line of code: 1 Total line of code: 3
Characters count excluding spaces and new line Characters count excluding spaces and new line
characters: 17 characters: 35

You might also like