🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

CSC 202 LECTURE- KB MARSHALL (2).PDF.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

COMPARATIVE PROGRAMMING (A Study of Python and PHP) LECTURE MATERIAL DEPARTMENT OF COMPUTER SCIENCE SCHOOL OF COMPUTING THE FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE, NIGERIA © 2018 1 ...

COMPARATIVE PROGRAMMING (A Study of Python and PHP) LECTURE MATERIAL DEPARTMENT OF COMPUTER SCIENCE SCHOOL OF COMPUTING THE FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE, NIGERIA © 2018 1 CHAPTER ONE 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 Hence, 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. INTRODUCTION TO PYTHON AND PHP PROGRAMMING 1.1 PYTHON Facts about Python  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. 2  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. 1.2 Features of Python Python possesses many interesting technical and aesthetic features, which include:  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 does not 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. tuples, list, dictionaries, decorators, iterators etc.  Large user support community 1.3 Development Tools  Text Editor o Notepad, Notepad++, Sublime Text 2, EditPad etc  Integrated Development Environment o Python IDLE, Eclipse, EditPadPro, GEdit, JEdit, Komodo IDE, Netbeans, PythonToolKit etc.  Python Interpreter www.python.org/download/ 1.4 Introduction: What is PHP?  Started as a Perl hack in 1994 by Rasmus Lerdorf, developed to PHP/FI (Personal Homepage/Form Interpreter) 2.0 3  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.  For the purpose of this course, version 7.2 will be used.  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 free to download and use.  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP supports a wide range of databases and runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) 1.5 Features of PHP  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. 1.6 What PHP Can Do  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 i.e small text files placed on your computer by a web server when you view some sites online.  PHP can add, delete, modify data in your database 4  PHP can be used to control user-access  PHP can encrypt data 1.7 Development Tools  Text Editor o Notepad, Notepad++, Sublime Text 2, EditPad etc  Integrated Development Environment o Eclipse PDT, phpDesigner, PHPEclipse, PhpED, PHPEdit, Komodo IDE, Netbeans, etc.  Web Server  Database e.g MySQL 5 CHAPTER TWO BASIC SYNTAX AND RULES IN PYTHON AND PHP Python 2.1 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! 2.2 Variable Naming  Python names can be as long as 255 characters, starts with a letter or _ followed by a mixture of alpha-numeric and the underscore. Python keywords are not allowed to be used as variable names. 2.3 Data Types  Even though it is strictly dynamic and does not require static variable declarations, the following basic types are supported. However complex types such as arrays, list, tuple, sets, dictionaries and user defined types are also supported. For example, Value Type 203 int 4.03 float “futa” str 2.4 Variables Variables are containers for storing values. 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 in them and how they are used in expressions. Python assigns memory to a variable only when the variable is initialized. Python also supports scientific types such as Complex Numbers and also provides means to carry out basic operations on them. E.g. Getting the real, imaginary part or the conjugate of the complex number. For example, score = 60 matno = “CSC/11/0036” height = 4.5 isGraduated = False 6 comp = 4 + 3j >>> print comp (4+3j) >>> comp.real 4.0j >>> comp.imag 3.0 >>> comp.conjugate() (4-3j) 2.6 Expressions & Operators  Python supports the following basic arithmetic operators; Operators Operation Precedence + Addition () - Subtraction ** * Multiplication */% / Division +- % Modulo ** Exponentiation // Floor Division  Python supports the following basic relational operators;  All relational operators produce only boolean result! Operators Operation < Less Than > Greater Than == Equal To 7 = Greater Than or Equal To != Not Equal To a = 30 b = 32 ab False a >= b False b >>); for continuation lines it prompts with the secondary prompt, by 9 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.  The interactive mode can be used as a calculator, as a tool for testing lines of codes, or for writing simple system administration scripting.  For example see below; b = 10 * 5 >>> x = 400 + b >>> print b 50 >>> print x 450 >>> print a,b 50, 450 >>> dir() 10 [‘__builtins__’,’ __docs__’,’ __name__’,’b’,’x’]  When the interactive is started, it keeps a collection of all variables and objects initialized or created during a particular code session and persists such until the shell is exited or restarted. 2.10 Displaying code output  Using Print : the print keyword can be used to display program output as shown in the example below; Notice how function str() is used to convert the integer variable age to a string >>>name = "Wole" >>> age = 56 >>> print name Wole >>> print name,age Wole 56 >>> print name;age Wole 56 >>> print "Name: "+ name Name: Wole >>> print "Age: "+ str (age) Age: 56 2.11 Reading data input from the keyboard  raw_input: the raw_input() function can be used to read in users’ inputs as shown in the example below;  raw_input() function takes a single parameter that represents the prompt message guiding users on what to input as shown above.  raw_input() functions return primarily string values and must be converted to appropriate types using either int() or float() functions as shown above or even str() as the case maybe. matric = raw_input("What is your matric number?") What is your matric number?CSC/05/6442 >>> print matric CSC/05/6442 >>> score_test = raw_input("What is your test score?") What is your test score?20 >>> score_exam = raw_input("What is your exam score?") What is your exam score?56 >>> total_score_CSC201 = int(score_test) + int(score_exam) >>> print total_score_CSC201 76 11 2.12 Using help() on the command line interface  help(): it is used to learn more about the python language. It displays the documentation of many common topics in python.  If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')” has the same effect as typing a particular string at the help> prompt. 2.13 Using dir() on the command line interface  typing dir() returns the names in the current scope of the interpreter, while typing dir(object) returns a list of strings containing the object’s attributes, and class's attributes etc >>>dir() ['__builtins__', '__doc__', '__name__', '__package__', 'age', 'isOld', 's‘] >>> dir(age) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] 2.14 Basic Rules/Syntax in PHP  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.  A PHP script starts with  PHP commands/statements ends with a semicolon e.g $new = “ Welcome to csc 202 class!” ;  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). 12  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. 2.15 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. e.g $classattendance = 45; $class_name = “physics”;  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 2.16 Operators  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 Operator Operation Example + Addition $p + 1 - Subtraction $p – 3 * Multiplication $p * 67 / Division $p / 8 % Modulo $p % 2 ++ Increment ++$p -- Decrement --$p 13 Logical Operators Operator Operation Example && And $K ==2 && $G ==45 And Low-precedence and $K ==2 and $G ==45 || Or $K ==2 || $ K7 14 < Is less than $f= Is greater than or equal to $f>=17 >= Is less than or equal to $f Seeing this type of example, the PHP interpreter will not know where a comment ends and will display an error message. 2.18 Output Statements Displaying Output: In PHP, there are two basic ways of displaying the output of a program. These are echo and print. They are both used as output statements, however, with little differences. The echo Statement  It has no return value 16  It can take multiple parameters (though not rarely in use)  It is marginally faster than print  It can be used with or without parentheses; echo or echo()  It is a purely PHP language construct Example The print Statement  print has return value of 1 and therefore can be used in more complex expressions.  It is a function-like construct that takes only one argument  It can be used with or without parentheses Example To specify an alternative statement to execute when the expression is false i.e. execute a statement if a certain condition is met, and a different statement if the condition is not met. Use the “else” keyword: 20 elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. The ternary conditional operator (? :) can be used to shorten simple true/false tests. 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, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. A switch statement is given an expression, compare its value to all cases in the switch. All statements in a matching case are 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. PHP provides alternate syntax for its selection structures if (condition): echo "Welcome!"; elseif (condition): echo "Welcome!"; else: echo "Access Forbidden!"; endif; The alternative syntax for switch: switch(condition): case 0: // do something break; case 1: // do something break; case 2: // do something break; default: // do something break; endswitch; 22 REPETITION A repetition structure allows the programmer to specify that a program should repeat an action while some condition remains true. There are several structures for implementing this. PYTHON Computers are often used to automate repetitive tasks. Because iteration is so common, Python provides several language features to make it easier. One form of iteration in Python is the while statement. x=10 while (x 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. 24 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. You can specify multiple expressions for any of the expressions in a for statement by separating the expressions with commas. You can also leave an expression empty, signaling that nothing should be done for that phase. In the most degenerate form, the for statement becomes an infinite loop. You probably don’t want to run this example, as it never stops printing: 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. The alternate syntax for the repetition structures are: foreach ($array as $current): // do something endforeach; 25 The alternative syntax for while has this structure: while (expr): // do something endwhile; The alternative syntax of a for statement is: for (expr1; expr2; expr3): // do something endfor; 26 CHAPTER FOUR SUBPROGRAMS AND PARAMETER PASSING (FUNCTIONS AND SUBROUTINES) 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. 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. Subprograms save on compile time—no matter the number of times it is called, functions are compiled only once for the page. They also improve reliability by allowing you to fix any bugs in one place, rather than everywhere you perform a task, and they improve readability by isolating code that performs specific tasks. The following are terminologies of subprograms: 1. A subprogram definition describes the interface to and the actions of the subprogram abstraction. 2. The header is the first part of the definition, including the name, the kind of subprogram, and the formal parameters. 3. The parameter profile (also signature) of a subprogram is the number, order, and types of its parameters 4. 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 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. Subprograms in Python Subprograms in python are called functions. The keyword “def” is used to create a named function. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed and the function definition generates no output until the function is called. The name of a function follows the naming convention of variable names. The first statement in the body of a function is usually a string enclosed in ‘’’, which can be accessed with function_name.__doc__ This statement is called Docstring. def findAverage(): ‘’’A function to calculate the average of numbers ’’’ average=0 print “average is “, average Making use of a function is “calling the function”. 27 findAverage() Functions can also accept values to be used as part as their execution, such values are stored in variables. The variables are called parameters. The parameters can be one or more.Python returns an error if the number of parameters is less than or more than the number specified eg. The function specifies 2 parameters and 3 is passed. There are several types of parameters 1. Normal parameters: Functions can accept values of any data type i.e. int, float, string, list, tuples etc. as parameters. def findAverage(num1, num2): ‘’’A function to calculate the average of numbers ’’’ average=(num1+num2) / 2 print “average is “, average Calling this function: findAverage(4,8) 2. 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. def findAverage(num1, num2=5): ‘’’A function to calculate the average of numbers ’’’ average=(num1+num2) / 2 print “average is “, average Calling this function: findAverage(4,8) findAverage(4) // the default value for num2 is used 3. Parameter list (*args): There are many situations in programming, in which the exact number of necessary parameters cannot be determined a-priori. An arbitrary parameter number can be accomplished in Python with so-called tuple references. An asterisk "*" is used in front of the last parameter name to denote it as a tuple reference. def findAverage(*num): 28 ‘’’A function to calculate the average of numbers ’’’ sum=0 if len(num)==0: return 0 else: for number in num: sum+=number average=sum/len(num) print “average is “, average Calling this function: findAverage(4,8,4,6,3,2,5,2,8) findAverage(4,7,8,4,3) 4. 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. def findAverage(num1, num2, num3=8, num4=9): ‘’’A function to calculate the average of numbers ’’’ average=(num1 + num2 +num3 +num4) /4 print “average is “, average Calling this function: findAverage(2,5) findAverage(4,7,num4=5) We can see the benefit in the example. If we had no keyword parameters, the second call to function would have needed all four arguments, even though the num3 needs just the default value. The keywords can also be of any length by using the asterisk “**” before the parameter name. Python arguments are passed by assignment. The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed 29 using call by value (where the value is always an object reference, not the value of the object), This is termed call-by-reference. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function. The 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. The return statement takes zero or more values, separated by commas. Using commas actually returns a single tuple. The default value is None. To return multiple values, use a tuple or list. def findAverage(num1, num2): ‘’’A function to calculate the average of numbers ’’’ average=(num1+num2) / 2 return average Calling this function: avg= findAverage(4,8) print “the mean of the distribution is “, avg 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. determinant = lambda a, b, c: (b ** 2) + (4*a*c) print determinant(4, 5, 6) Subprograms in PHP 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. 30 Sometimes a function may need to accept a particular parameter. 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: A function may have any number of parameters with default values. However, they must be listed after all parameters that do not have default values. 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: 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; and 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: There are two different ways to pass parameters to a function. 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. 32 Passing Parameters by Reference Passing by reference gives a function direct access to a variable. To be passed by reference, the argument must be 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 (&). Because the function’s $value parameter is passed by reference, the actual value of $num1 and $num2, rather than a copy of that value, is modified by the function. By default, values are copied out of the function. To return a value by reference, both declare the function with an & before its name and when assigning the returned value to a variable: In this code, the function returns an alias for $average, instead of a copy of its value. This technique is sometimes used to return large string or array values efficiently from a function. However, PHP implements copy-on-write for variable values, meaning that returning a reference from a function is typically unnecessary. Returning a reference to a value is slower than returning the value itself. Typically, functions return some value. To return a value from a function, use the return statement. When a return statement is encountered during execution, control reverts to the calling statement, and the evaluated results will be returned as the value of the function. A function can have several return statements. PHP functions can return only a single value with the return keyword. To return multiple values, return an array. If no return value is provided by a function, the function returns NULL instead. Anonymous Functions Some PHP functions use a function you provide them with to do part of their work. For example, the usort() function uses a function you create and pass to it as a parameter to determine the sort order of the items in an array. PHP allows the definition of localized and temporary functions. Such functions are called anonymous function or closure. It is defined using the normal function definition syntax, but assign it is then assigned to a variable or pass it directly.

Tags

Python programming PHP programming comparative study computer science
Use Quizgecko on...
Browser
Browser