CSC202
CSC202
(FUTA)
CSC 202
COMPARATIVE PROGRAMMING
LANGUAGES
⊡ 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.
Notepad, Notepad++, Sublime Text 2, EditPad etc Notepad, Notepad++, Sublime Text 2,
Python IDLE, Eclipse, EditPadPro, GEdit, JEdit, Komodo Integrated Development Environment
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
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.
== Is equal to $f ==5
!= Is not equal to $f !=8
= $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.
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.
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.
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
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(*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.
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
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.
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.
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.
#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)
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 <?php
2 $variable = "name";
3 $literally = 'My $variable will not print!';
4
5 print($literally);
print "<br>";
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 <?php
2 /* First method to create array. */
3 $numbers = array( 3,6,9);
4
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
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.
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.
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.
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 ?>
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.
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.
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.
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
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 ?>
1 <?php
2 class rectangle{
3 var $length;
4 var $breadth;
5 var $area;
6 var $perimeter;
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()
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 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.
Method Overloading Not really, uses workaround Not really, using _call()
8
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
Raise Yes No
Throw No Yes
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.
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
Abstraction means hiding unnecessary details from the end user. Abstraction is generally achieved
through inheritance hierarchy.
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.
We will compare the source code sizes of the languages using “hello world” program
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