0% found this document useful (0 votes)
21 views

BCA 5 Semester UNIT 4 & 5

BCA 5 Semester UNIT 4 & 5

Uploaded by

txerox17
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)
21 views

BCA 5 Semester UNIT 4 & 5

BCA 5 Semester UNIT 4 & 5

Uploaded by

txerox17
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/ 50

Unix programming

th
BCA 5 semester

IV And V Units

1
BCA502 UNIXPROGRAMMING

Credits: 4

Instruction: (4 l ) hrsperweek Duration of SEE: 3 hours


CIE:30marks SEE: 70marks

UNIT-I Unix: Introduction, commands, file system, security and file permission,
regular expression and grep, shell programming, awk

UNIT-II
The Unix Model, signal, process control, daemon process. Interprocess
Communication: Introduction, file and record locking, other Unix locking techniques,
pipes, FIFOs, streams and messages, namespaccs, message queues, semaphores and
shared memory.

UNIT-III
Socket programming, Socket address, elementary socket system calls, advanced socket
system calls, reserved ports, socked options, asynchronous I/O, Input/ Output
Multiplexing, out-off band. data, sockets and signals, Internet super server.

UNIT-IV
Introduction to PHP: Overview, syntactic characteristics, primitives, operations and
expressions, output, control statements, arrays, functions. pattern matching, form
handling files, cookies and session tracking.

UNIT-V
Python Basics, Python Objects, Numbers, Sequences: Strings, Lists, and Tuples,
Mapping and Set Types, Conditionals and Loops, Files and Input/Output, Errors and
Exceptions, Functions and Functional Programming, Modules, Object oriented
programming.

Suggested Readings:
Behrouz A. Forouzan and Richard F. Gilberg, "Unix and Shell Programming: a
Text book" Cengage learning,2008.
W. Richard Stevens, "Unix Network Programming", Pearson Education,2009.
Robert W. Sebesta, "Programming the World Wide Web", Pearson
Education,2008.
Wesley J. Chun, "Core Python Programming", PrenticeHall.
Sumitabha Das, "Unix concepts & Applications", Fourth Edition, Tata McGraw
hill,2006.

********************************************************************

2
UNIT-IV
Introduction to PHP: Overview, syntactic characteristics, primitives,
operations and expressions, output, control statements, arrays, functions.
pattern matching, form handling files, cookies and session tracking

What is XAMPP?

XAMPP is an open-source web server solution package. It is mainly used for web application
testing on a local host webserver.
XAMPP stands for:
X = Cross-platform
A = Apache Server
M = MariaDB
P = PHP
P = Perl
Now that you have a better understanding of the XAMPP software, let us move on to its
installation.

Introduction to PHP

o PHP is an open-source, interpreted, and object-oriented scripting


language that can be executed at the server-side.
o PHP is well suited for web development. Therefore, it is used to develop
web applications (an application that executes on the server and
generates the dynamic page.).
o PHP was created by Rasmus Lerdorf in 1994 but appeared in the
market in 1995.
o PHP stands for Hypertext Preprocessor. Which gives you a good idea of
its core purpose: to process information and produce hypertext (HTML)
as a result. (Developers love recursive acronyms, and PHP: Hypertext
Preprocessor is a good example of one.)
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the
dynamic content of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.

3
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language

Features of PHP:
 Performance:
PHP script is executed much faster than those scripts which are written
in other
languages such as JSP and ASP. PHP uses its own memory, so the server
workload
and loading time is automatically reduced, which results in faster
processing
speed and better performance.
 Open Source:
PHP source code and software are freely available on the web. You can
develop
all the versions of PHP according to your requirement without paying
any cost. All
its components are free to download and use.
 Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable
coding with it.
 Embedded:
PHP code can be easily embedded within HTML tags and script.
 Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP
application developed in one OS can be easily executed in other OS also.
 Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC,

4
etc.
 Error Reporting -
PHP has predefined error reporting constants to generate an error
notice or
warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT,
E_PARSE.
 Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be
taken
automatically at the time of execution based on the type of data it
contains on its
value.
 Web servers Support:
PHP is compatible with almost all local servers used today like Apache,
Netscape,
Microsoft IIS, etc
******************************************************************
PHP, as a programming language, has several syntactic characteristics that distinguish
it from other languages. Here are some key syntactic features of PHP:

 Scripting Language: PHP is primarily used as a server-side scripting language,


embedded within HTML. This means PHP code is embedded within <?php ... ?> tags
within an HTML file to dynamically generate content.
 Variables: PHP variables start with the $ symbol followed by the variable name.
Variables in PHP are loosely typed, meaning they do not need explicit declaration and
their types can change dynamically.
 Data Types: PHP supports various data types including integers, floats (floating-
point numbers), strings, booleans, arrays, objects, and NULL.
 Control Structures: PHP includes familiar control structures such as if statements,
else-if statements, else statements, and switch statements for decision-making. It also
supports loops like for, foreach, while, and do-while loops.
 Functions: Functions in PHP are defined using the function keyword, followed by
the function name and parameters. PHP supports both built-in functions and user-
defined functions.
 Arrays: PHP arrays can be indexed (numeric or string keys) or associative (key-value
pairs). Arrays are very flexible and can hold multiple types of data.
 Strings: PHP provides extensive support for strings, including functions for
string manipulation, interpolation within double-quoted strings, and
concatenation with the dot (.) operator.
 Classes and Objects: PHP supports object-oriented programming (OOP) with
classes and objects. Classes are defined using the class keyword, and objects are
instances of classes.
 Error Handling: PHP has built-in error handling features, including predefined error
constants, error reporting levels, and mechanisms like try, catch, and throw for
exception handling.
 Include and Require: PHP allows files to be included or required within other PHP
files using include, include_once, require, or require_once. This is useful for
modularizing code and reusing functionality.

5
 Comments: PHP supports both single-line comments (//) and multi-line comments
(/* */) for code documentation and readability.
 Global Variables: PHP allows the use of global variables, which can be accessed
across different scopes of the script. However, proper usage of globals is generally
discouraged for maintainable code.
 Superglobals: PHP provides several predefined arrays called superglobals ($_GET,
$_POST, $_SESSION, $_COOKIE, etc.) that are accessible from any part of the
script, allowing information to be passed between pages.
 HTML Integration: PHP can seamlessly integrate with HTML, allowing developers
to mix PHP code directly within HTML files, which makes it easy to generate
dynamic content.
 File Handling: PHP provides functions for file handling operations such as reading
from and writing to files, checking file existence, file permissions, etc.
**************************************************************************
PHP sample program:
<?php
// Outputs a welcome message:
echo "Welcome sphoorthy!";
?>
Output:
Welcome sphoorthy
**************************************************************************
Primitives of PHP

PHP Data Types:


PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
1.Scalar Types (predefined)
2.Compound Types (user-defined)
3.Special Types
PHP Data Types:Scalar Types
It holds only single value. There are 4 scalar data types in PHP.
boolean
integer
float
string
PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
array
object
PHP Data Types: Special Types
NULL

1.PHP Data Types: Scalar Types

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is
correct, it returns TRUE otherwise FALSE.

6
Example:
<?php
$x = true;
var_dump($x);
?>
Output:
bool(true)

PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
Rules for integer:
 An integer can be either positive or negative.
 An integer must not contain decimal point.
 Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
 The range of an integer must be lie between 2,147,483,648 and
2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69

PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812

PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and
even special characters.
String values must be enclosed either within single quotes or in double quotes. But
both are treated differently. To clarify this, see the example below:

7
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company

2.PHP Data Types: Compound Types

PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
Output: array(3) {
[0]=>
string(5) "Volvo"
}
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"

PHP Object:
Represents instances of user-defined classes or built-in PHP objects.
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

8
Output:
Bike Model: Royal Enfield
This is an advanced topic of PHP, which we will discuss later in detail.

3.PHP Data Types: Special Types

PHP NULL Value:


Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of


NULL.

Variables can also be emptied by setting the value to NULL:


Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output:
NULL
*********************************************************************
OPERATORS IN PHP

 Arithmetic Operations:
PHP supports standard arithmetic operations for numbers (int and float):
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (remainder) (%)
Example:
<?php
$a = 10;
$b = 3;
echo $a + $b . "</br>";
echo $a - $b . "</br>";
echo $a * $b . "</br>";
echo $a / $b . "</br>";
echo $a % $b . "</br>";
?>
Output:
13
7
30
3.3333333333333
1

9
 Assignment Operators:
PHP provides various assignment operators to assign values and perform operations
in a concise manner:
Simple assignment (=)
Addition assignment (+=)
Subtraction assignment (-=)
Multiplication assignment (*=)
Division assignment (/=)
Modulus assignment (%=)
Example:
<?php
$a = 10;
echo $a += 5;
echo ("<br>");
echo $a -= 3;
echo ("<br>");
echo $a *= 2;
echo ("<br>");
echo $a /= 4;
echo ("<br>");
echo $a %= 5;
?>
Output:
15
12
24
6
1

 Comparison Operators
These operators are used to compare two values and return a boolean (true or false)
result:
Equal to (==)
Identical to (===)
Not equal to (!= or <>)
Not identical to (!==)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Example:
<?php
$a = 10;
$b = 5;
$result1 = ($a == $b);
echo"result1=$result1" . "</br>";
$result2 = ($a != $b);

10
echo"result2=$result2" . "</br>";
$result3 = ($a > $b);
echo"result3=$result3" . "</br>";
$result4 = ($a <= $b);
echo"result4=$result4" . "</br>";
?>
Output:
result1=
result2=1
result3=1
result4=

 Logical Operators
These operators are used to combine conditions and manipulate boolean values:
Logical AND (&& or and)
Logical OR (|| or or)
Logical XOR (xor)
Logical NOT (!)
Example:
<?php
$a = true;
$b = false;
$result1 = ($a && $b);
echo"result1=$result1" . "</br>";
$result2 = ($a || $b);
echo"result2=$result2" . "</br>";
$result3 = ($a xor $b);
echo"result3=$result3" . "</br>";
$result4 = (!$a);
echo"result4=$result4" . "</br>";
?>
Output:
result1=
result2=1
result3=1
result4=

 String Operations
PHP allows various operations on strings, such as concatenation (.) and comparison:
Example:
<?php
$str1 = "Hello";
$str2 = " PHP";
$result = $str1 . $str2;
echo"$result";
?>
Output:
Hello PHP

 Ternary Operator

11
PHP supports a shorthand conditional operator (?:) which is useful for assigning
values based on a condition:
Example:
<?php
$age=25;
echo $canvote = ($age>=18) ? "Yes" : "No";
?>
Output:
Yes

 Increment and Decrement Operators


PHP includes increment (++) and decrement (--) operators:
Example:
<?php
$a = 5;
echo ++$a . "</br>";
echo --$a . "</br>";
echo $a++ . "</br>";
echo $a--;
?>
Output:
6
5
5
6

 Array Operations
PHP offers various array operations, such as accessing elements, adding/removing
elements, merging arrays, etc.:
Example:
<?php
$array1 = array("apple", "banana", "cherry");
$array2 = array("date", "elderberry", "fig");

// Accessing elements
echo "Element at index 1 of array1: " . $array1[1] . "\n" . "</br>";

// Adding elements
$array1[] = "grape";
echo "Array1 after adding an element:";
print_r($array1);
echo ("<br>");

// Removing elements
unset($array1[2]);
echo "Array1 after removing an element: ";
print_r($array1);
echo ("<br>");

// Merging arrays

12
$mergedArray = array_merge($array1, $array2);
echo "Merged array: ";
print_r($mergedArray);
?>
Output:
Element at index 1 of array1: banana
Array1 after adding an element:Array ( [0] => apple [1] => banana [2] =>
cherry [3] => grape )
Array1 after removing an element: Array ( [0] => apple [1] => banana [3] =>
grape )
Merged array: Array ( [0] => apple [1] => banana [2] => grape [3] => date [4]
=> elderberry [5] => fig )

********************************************************************
Expressions in PHP:
Expressions are fundamental components used to perform computations, evaluate
conditions, and generate values. An expression in PHP is typically a combination of
variables, constants, operators, and functions that evaluates to a value.

Introduction
Almost everything in a PHP script is an expression. Anything that has a value is an
expression. In a typical assignment statement ($x=100), a literal value, a function or
operands processed by operators is an expression, anything that appears to the right of
assignment operator (=)
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression

Expression with ++ and – operators

These operators are called increment and decrement operators respectively. They are unary
operators, needing just one operand and can be used in prefix or postfix manner, although
with different effect on value of expression
Example
<?php
$x=10;
$y=++$x;//equivalent to $y=$x followed by $x=$x+1
echo "x =$x y = $y";
?>
Output
x =11 y = 11

Expression with Ternary conditional operator


Ternary operator has three operands. First one is a logical expression. If it is TRU, second
operand expression is evaluated otherwise third one is evaluated

13
Example
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Output
Pass
**************************************************************************
SETTYPE()
The settype() function converts a variable to a specific type.
Syntax
settype(variable, type);

Parameter Values Parameter Description


variable Required.Specifies the variable to
convert
type Required. Specifies the type to
convert variable to. The possible
types are: boolean, bool, integer,
int, float, double, string, array,
object, null
EXAMPLE:
<?php
$a = "32"; // string
echo settype($a, "integer"); // $a is now integer
echo ("<br>");

$b = 32; // integer
echo settype($b, "string"); // $b is now string
echo ("<br>");

$c = true; // boolean
echo settype($c, "integer"); // $c is now integer (1)
?>
Output:
1
1
1
**************************************************************************
Control statements in php
Control statements in PHP allow you to control the flow of execution based on conditions
and perform repetitive tasks.
1.Conditional Statements:
 if Statement:
Executes a block of code if a specified condition is true.
Example:
<?php
$age = 25;

14
if ($age >= 18) {
echo "You are an adult.";
}
?>
Output:
You are an adult.

 if...else Statement:
Executes one block of code if a specified condition is true and another block if the
condition is false.
Example:
<?php
$age = 15;

if ($age >= 18) {


echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
Output:
You are a minor

 elseif Statement:
Allows you to check multiple conditions and execute a block of code as soon as one
of the conditions is true.
Example:
<?php
$age = 70;
if ($age < 18)
{
echo "You are a child.";
} elseif ($age < 65)
{
echo "You are an adult.";
} else
{
echo "You are a senior citizen.";
}
?>
Output:
You are a senior citizen.

 Switch Statement:
Selects one of many blocks of code to execute based on the value of an expression.
Example:
<?php
$day = "Sunday";
switch ($day) {
case "Monday":
echo "Start of the week.";

15
break;
case "Tuesday":
echo "Second day of the week.";
break;
case "Wednesday":
echo "Third day of the week.";
break;
case "Thursday":
echo "Fourth day of the week.";
break;
case "Friday":
echo "Almost weekend!";
break;
default:
echo "***Weekend***";
}
?>
Output:
Start of the week.

2.Looping Statements:
 for Loop:
Executes a block of code a specified number of times.

Example:
<?php
for ($i = 1; $i <= 5; $i++)
{
echo "Iteration $i <br>";
}
?>
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

 while Loop:
Executes a block of code as long as a specified condition is true.
Example:

<?php
$num = 1;
while ($num <= 5)
{
echo "Number: $num <br>";
$num++;

16
}
?>
Output:
Number:1
Number:2
Number:3
Number:4
Number:5

 do...while Loop:
Similar to the while loop, but the block of code is executed once before the
condition is checked.

Example:
<?php
$num = 1;
do
{
echo "Number: $num <br>";
$num++;
} while ($num <= 5);
?>
Output:
Number:1
Number:2
Number:3
Number:4
Number:5

3.Jump Statements

 break Statement:
Terminates the current loop or switch statement and transfers execution to the
statement immediately following the loop or switch.

Example:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break; // Stop the loop when $i is 6
}
echo "$i <br>";
}
?>
Output:
1
2
3
4

17
5

 continue Statement:
Skips the rest of the current loop iteration and continues to the next iteration.

Example:
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip iteration when $i is 3
}
echo "$i <br>";
}
?>
Output:
1
2
4
5

 Return Statement
Terminates the execution of a function and optionally returns a value to the calling
code.

Example:
<?php
function add($a, $b) {
$sum = $a + $b;
return $sum;
}

$result = add(3, 5);


echo "result=$result"; // $result will be 8
?>
Output:
result=8
*********************************************************************************
PHP Arrays:
PHP array is an ordered map (contains value on the basis of key). It is used to hold
multiple values of similar type in a single variable.
There are 3 types of array in PHP.
1.Indexed Array
2.Associative Array
3.Multidimensional Array

1.PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an index

18
number by default.
There are two ways to define indexed array:
 1st way:
Example:
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn

 2nd way:
Example:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn

2.PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
Example:
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000

3.Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store
tabular data in an array. PHP multidimensional array can be represented in the form
of matrix which is represented by row * column.
Example:
<?php
$emp = array

19
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
OUTPUT:
1 sonoo 400000
2 john 500000
3 rahul 300000
Let's see a simple example of PHP multidimensional array to display following
tabular data. In this example, we are displaying 3 rows and 3 columns.
Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

ADVANTAGES OF ARRAYS:
 Less Code: We don't need to define multiple variables.
 Easy to traverse: By the help of single loop, we can traverse all the elements
of an array.
 Sorting: We can sort the elements of array.
******************************************************************************************************************************

Functions in PHP:
A function is a block of code written in a program to perform some specific task.
PHP provides us with two major types of functions:

Built-in functions : PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and
so on.
User Defined Functions : Apart from the built-in functions, PHP allows us to create our
own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.

20
Syntax:
function functionname()
{
executable code;
}

User defined function with out parameters.


EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
function example()
{
echo "Hello world!";
}
example();
?>
</body>
</html>
Output:
Hello world!

User defined function with parameters


EXAMPLE:
<!DOCTYPE html>
<html>
<body>

<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
</body>
</html>
OUTPUT:
5 + 10 = 15
7 + 13 = 20
2+4=6

********************************************************************

21
What is a Regular Expression?
 A regular expression is a sequence of characters that forms a
search pattern. When you search for data in a text, you can use
this search pattern to describe what you are searching for.
 A regular expression can be a single character, or a more
complicated pattern.
 Regular expressions can be used to perform all types of text
search and text replace operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern
and optional modifiers.
$exp = "/w3schools/i";
PHP provides a variety of functions that allow you to use regular
expressions.
The most common functions are:
preg_match() Returns 1 if the pattern was found in the
string and 0 if not

preg_match_all() Returns the number of times the pattern was


found in the string, which may also be 0

preg_replace() Returns a new string where matched patterns


have been replaced with another string

 The preg_match() function will tell you whether a string


contains matches of a pattern.
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>

</body>
</html>
Output:
1

 The preg_match_all() function will tell you how many


matches were found for a pattern in a string.
Example:
<!DOCTYPE html>
<html>

22
<body>

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
</body>
</html>
Output:
Visit W3Schools!

 The preg_replace() function will tell you whether a


string contains matches of a pattern.
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>

</body>
</html>
Output:
Visit W3Schools!

****************************************************************************************************************

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need to
use $_GET, for post request $_POST.
 PHP Get Form
Get request is the default form request. The data passed through get request is
visible on the URL browser so it is not secured. You can send limited amount of
data through get request.
Let's see a simple example to receive data from get request in PHP.
Example:
"welcome_get.php" looks like this:
<html>

23
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>
Create html file as follows : save as formget.html

<!DOCTYPE HTML>
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
Procedure : to see the output execute formget.html file in the browser
Output:

Name:
E-mail:

Welcome latha
Your email address is: [email protected]

 PHP Post Form


Post request is widely used to submit form that have large amount of data
such as file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is
secured. You can send large amount of data through post request.
Example:
The "welcome.php" looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>

24
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

Create html file as follows : save as formpost.html

<!DOCTYPE HTML>
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
Procedure : to see the output execute formpost.html file in the browser
Output:

Name:
E-mail:

Welcome latha
Your email address is: [email protected]

Difference Between GET and POST Methods in PHP

Parameter GET POST


Data is appended to the URL and Data is included in the request body
Visibility
visible in the browser's address bar. and not visible in the URL.
Limited by the URL length, which No inherent limit on data size,
Data Length can vary by browser and server. allowing for large amounts of data to
Typically, around 2048 characters. be sent.
Less secure due to visibility in the
More secure for transmitting sensitive
URL. Sensitive data can be easily
Security data since it's not exposed in the
exposed in browser history, server
URL.
logs, etc.
Suited for transactions that result in a
Ideal for simple data retrieval where
change on the server, such as
Use Case the data can be bookmarked or
updating data, submitting forms, and
shared.
uploading files.

25
Idempotent, meaning multiple Non-idempotent, meaning multiple
Idempotency identical requests have the same identical requests, may have different
effect as a single request. outcomes.
Can be cached by the browser and Not cached by default since it can
Caching
proxies. change the server state.
Only ASCII characters are allowed.
Can handle binary data in addition to
Data Type Non-ASCII characters must be
text, making it suitable for file uploads.
encoded.
Reloading a page can cause the
Reloading a page requested by GET
Back/Forward browser to prompt the user for
does not usually require browser
Buttons confirmation to resubmit the POST
confirmation.
request.
Cannot be bookmarked or shared
Bookmarks and Easily bookmarked and shared
through the URL since the data is in
Sharing since the data is part of the URL.
the request body.
Often causes a change in server state
Generally used for retrieving data
Impact on (e.g., database updates) or side
without any side effects on the
Server effects.
server.

*******************************************************************************************************************************

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is
used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client
sends request to the server, cookie is embedded with request. Such way, cookie can
be received at the server side.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is
set, you can access it by $_COOKIE superglobal variable.
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
$value=$_COOKIE["CookieName"];//returns cookie value
PHP Cookie Example
<?php

26
setcookie("user", "BCA");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie
is set now.
Output:
Cookie Value: BCA

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.
Example:
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ag
o
?>
Output:
Cookie 'user' is deleted.
PHP Sessions
A session is a way to store information (in variables) to be used across
multiple pages.
Unlike a cookie, the information is not stored on the users computer.

 syntax for remove all session variables


session_unset();

 syntax for destroy the session


session_destroy();

27
Start a PHP Session

A session is started with the session_start() function.Session variables


are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we
start a new PHP session and set some session variables:

Example:

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Output:
Session variables are set.
Get PHP Session Variable Values
Next, we create another page called "demo_session2.php". From this page,
we will access the session information we set on the first page
("demo_session1.php").
Notice that session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning of
each page (session_start()).
Also notice that all session variable values are stored in the global
$_SESSION variable:
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>

28
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>
Output:
Favorite color is .
Favorite animal is .

Difference Between Session and Cookies in PHP

Session Cookies

A session stores the variables and Cookies are stored on the user's
their values within a file in a computer as a
temporary directory on the text file.
server.

The session ends when the user Cookies end on the lifetime set by
logout from the application or the user.
closes his web browser.
It can store an unlimited amount of It can store only limited data.
data.

We can store as much data as we The maximum size of the browser's


want within a session, but there is cookies is 4 KB.
a maximum memory limit, which a
script can use at one time, and it
in 128 MB.

We need to call the session_start() We don't need to call a function to


function to start the session. start a cookie as it is stored
within the local computer.

In PHP, to set a session data, the In PHP, to get the data from
$_SESSION global variable is used. cookies, the $_COOKIE global
variable is used.

In PHP, to destroy or remove the We can set an expiration date to


data stored within a session, we delete the cookie's data. It will
session destroy() function, and to automatically delete the data at

29
unset a can use the specific that specific time. There is no
variable, we can use the unset() particular function to remove the
function. data.

Sessions are more secured compared Cookies are not secure, as data is
to cookies, as they save data in stored in a text file, and if any
encrypted form. unauthorized user gets access to
our system, he can temper the data.

IMPORTANT QUESTIONS

1.What is PHP? Explain the Overview,features and applications of PHP.


2.Write about Asyntactic characteristics of PHP.
3.Explain about Primitives in PHP.
4.Write about operations and expressions in PHP.
5.Write ahout PHP output methods.
6.Explain about Control statements, arrays and functions.
7.Write about Pattern matching and form handling files.
8.Discuss briefly about cookies and session tracking.

********************************************************************************************************************************

30
UNIT-V
Python Basics, Python Objects, Numbers, Sequences: Strings, Lists, and Tuples,
Mapping and Set Types, Conditionals and Loops, Files and Input/Output, Errors and
Exceptions, Functions and Functional Programming, Modules, Object oriented
programming.
Python Basic:
Python is a popular programming language known for its simplicity and versatility. Here are
some key features and advantages:

Features of Python
1.Easy to Learn and Use: Python has a simple syntax that is easy to understand, making it a
great choice for beginners1.
2.Interpreted Language: Python executes code line by line, which makes debugging easier2.
3.Object-Oriented: Supports object-oriented programming, which helps in structuring code
effectively2.
4.Extensive Libraries: Python has a vast standard library that supports many common
programming tasks3.
5.Portability: Python code can run on various platforms without modification2.
6.GUI Programming Support: Python supports GUI applications that can be created using
libraries like Tkinter2.
7.Dynamic Typing: Variables in Python do not need explicit declaration, making the code
more flexible2.
Advantages of Python
1.Rapid Development: Python’s simplicity and extensive libraries allow for quick development
and deployment1.
2.High Performance: Despite being an interpreted language, Python can be optimized for
performance1.
3.Strong Community Support: Python has a large and active community, which means plenty
of resources and support are available2.
4.Versatility: Python is used in various fields such as web development, data analysis, artificial
intelligence, scientific computing, and more1.
5.Less Coding: Python often requires fewer lines of code to accomplish tasks compared to
other languages1.
6.Corporate Support: Many large companies, including Google and Facebook, support Python,
which ensures its continued development and relevance1.
****************************************************************************
Python Objects:
1.Python is an object-oriented programming language.
2.Everything is in Python treated as an objects including variable ,function, list, tuple,
dictionary,sets etc.
3.An Object is the collection of various data and functions that operate on those data.
An object contains the following properties.
1.State: The attributes of an object represents its state.
2.Behavior: The method of an object represents its behavior.
3. Identity: Each object must be uniquely identified and allows interacting with the other
objects.
Python Classes/Objects
1.Python is an object oriented programming language.
2.Almost everything in Python is an object, with its properties and methods.
3.A Class is like an object constructor, or a "blueprint" for creating objects.

31
Create a Class
To create a class, use the keyword class:

Syntax: Class Definition


class ClassName:
# Statement

Syntax: Object Definition


obj = ClassName()
print(obj.atrr)

Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print("name is:",p1.name)
print("age is:",p1.age)
Output:
my name and age is : John
my age is: 36
****************************************************************************
Numbers:
1.In Python, “Numbers” is a category that encompasses different types of numeric data.
2. Python supports various types of numbers, including integers, floating-point numbers, and
complex numbers.

1.Integer
Python int is the whole number, including negative numbers but not fractions. In Python, there
is no limit to how long an integer value can be.
Example:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'int'>
<class 'int'>

2.Floating point numbers:

"floating point number" is a number, positive or negative, containing one or more decimals.
Example:

32
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>

3.Complex type
Complex numbers are written with a "j" as the imaginary part:
Example:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output:

****************************************************************************
Python Sequence
It is a type that stores more than one item at a time. Therefore, we can say that it is a collection
of
items. Moreover, to access these items each item has a particular index number. There are
three types of sequence data types namely, strings, lists, and tuples.
Python Strings
1.It is a group of characters. These characters can be digits, alphabets, or special symbols.
Moreover, they can be with or without spaces.
2.We can represent a string using single quotes, double quotes, or, triple quotes. Hence, these
quotes mark the beginning and end of a string and are not a part of the string.
3.Besides, numeric operations are not valid on a string.

Example:

33
Output:

The most useful string methods


Here are the dozen-ish Python string methods I recommend committing to memory.

Method Related Methods Description


join Join iterable of strings by a separator
split rsplit Split (on whitespace by default) into list of strings
replace Replace all copies of one substring with another
strip rstrip & lstrip Remove whitespace from the beginning and end
casefold lower & upper Return a case-normalized version of the string
startswith Check if string starts with 1 or more other strings
endswith Check if string ends with 1 or more other strings
splitlines Split into a list of lines
format Format the string (consider an f-string before this)
count Count how many times a given substring occurs
removeprefix Remove the given prefix
removesuffix Remove the given suffix
You might be wondering "wait why is my favorite method not in that list?" I'll briefly explain the rest of
the methods and my thoughts on them below. But first, let's look at each of the above methods.

Python Lists
It is a collection of different types of data. Besides, we can represent it using square brackets
[]. We sequentially store the items and separate them using commas. Examples are as follows:
Lists:
 List is consists of a group of elements.
 A list can store different types of elements.
 List is an example for sequence datatype.
 To store the student’s information a list is created as follows:
student =[10, ‘Anitha’, ‘F’, 50, 90, 64, 80]
 The elements of student list are stored in square brackets and the elements are
separated by a comma( , ).
 To view the elements of a list as a whole, the print( ) function is used like as follows:
print(student)
Output:-
[10, ‘Anitha’,‘F’, 50, 90, 64, 80]

34
Python Tuples:
 A Tuple Stores a group of elements.
 Tuples are similar to lists but main difference is tuples are immutable where as lists are
mutable.
 Since tuples are immutable, once we create a tuple we cannot modify its elements.
 Tuples are generally used to store data which should not be modified.
Creating Tuples:-
 Tuples are created by writing elements inside parentheses ( ) and elements are
separated by comma.
 The elements in tuple can be of same type or different tupes.
Ex:-1 tp = (10, 20, 30)
Ex:-2 tp = (10, 20, -3.4, 72.5, “BSC”)
Example:
ls = [1, 2, 3]
tp = tuple(ls)
print(tp)
Output:-
(1, 2, 3)
difference between list and tuple in python

35
****************************************************************************
Mapping and set types in python:
Dictionaries (dict):
Description: A dictionary in Python is a built-in data type that stores key-value pairs. It allows
you to store and retrieve data efficiently using unique keys.
Syntax:

my_dict = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}

Key Features:
1.Keys must be immutable (e.g., strings, numbers, tuples with immutable elements).
Values can be of any type.
2.Dictionaries are unordered (as of Python 3.7+, they maintain insertion order).
Keys must be unique within a dictionary.
Example:
# Creating a dictionary
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}

36
# Accessing a value
print(person['name']) # Output: Alice

# Adding a new key-value pair


person['occupation'] = 'Engineer'

# Iterating through keys and values


for key, value in person.items():
print(f"{key}: {value}")
OUTPUT:
Alice
name: Alice
age: 30
city: New York
occupation: Engineer

2. Set Types
Sets (set):

Description: A set in Python is an unordered collection of unique elements. It is useful for


operations that involve membership tests, eliminating duplicate entries, and mathematical set
operations like unions and intersections.

Syntax:
my_set = {1, 2, 3, 4}

Key Features:

•Sets are unordered, so the elements have no index.


•Elements must be immutable (e.g., numbers, strings, tuples), but the set itself is mutable.
•Duplicate elements are automatically removed.

Example:
# Creating a set
numbers = {1, 2, 3, 4, 4, 5}

# Adding an element
numbers.add(6)

# Removing an element
numbers.remove(2)

# Checking membership
print(3 in numbers) # Output: True

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # Output: {1, 2, 3, 4, 5}
print(a.intersection(b)) #{3}

37
OUTPUT:
True
{1, 2, 3, 4, 5}
{3}

Comparison Between Mapping and Set Types:


Dictionaries are mapping types where you deal with key-value pairs. They are optimized for
fast lookups by keys.
Sets are collections of unique items and are optimized for membership tests and set operations.

****************************************************************************
Conditional Statements
Conditional statements in Python allow us to check for certain conditions and perform actions
based on the outcome of those checks. There are several types of conditional statements in
Python, including:

•if statement
•if else statement
•if elif else statement
•nested if else statement
Let’s take a look at each of these in more detail.

1.if statement:
The if statement is used to check if a certain condition is true, and if so, execute a specific
block of code.
Example:
age = 18
if age >= 18:
print("You are old enough to vote.")

38
Output:
You are old enough to vote

In this example, the if statement checks if the value of the variable age is greater than or equal
to 18. If it is, the code inside the if statement is executed, which in this case is simply printing
a message to the console.

2. if else statement:
The if else statement is used to execute one block of code if a condition is true, and another
block of code if the condition is false.
Example:
age = 16
if age >= 18:
print("You are old enough to vote.")
else:
print("You are not old enough to vote yet.")
Output:
You are not old enough to vote yet

In this example, the if statement checks if the value of age is greater than or equal to 18. If it is,
the message "You are old enough to vote." is printed. If it is not, the message "You are not old
enough to vote yet." is printed instead.

3. if elif else statement:

The if elif else statement is used to check multiple conditions, and execute a specific block of
code based on which condition is true.
Example:
age = 16
if age >= 18:
print("You are old enough to vote.")
elif age >= 16:
print("You can drive but cannot vote.")
else:
print("You cannot drive or vote yet.")
Output:
You can drive but cannot vote

In this example, the first if statement checks if the value of age is greater than or equal to 18. If
it is, the message "You are old enough to vote." is printed. If not, the elif statement checks if
age is greater than or equal to 16. If it is, the message "You can drive but cannot vote." is
printed. If neither of these conditions are true, the else statement executes, and the message
"You cannot drive or vote yet." is printed.

4. nested if else statement:

The nested if else statement is used when we need to check a condition inside another
condition.

Example:

39
age = 18
gender = "female"
if age >= 18:
if gender == "male":
print("You are a male and old enough to vote.")
else:
print("You are a female and old enough to vote.")
else:
print("You are not old enough to vote yet.")
Output:
You are a female and old enough to vote

In this example, the first if statement checks if age is greater than or equal to 18. If it is, the
nested if statement checks if the value of gender is "male". If it is, the message "You are a
male and old enough to vote." is printed. If not, the message "You are a female and old
enough.

Loops in Python
A loop is a repetitive statement or task.

1.While Loop Statement:


A while loop statement in Python is used to repeatedly execute a block of code as long as a
condition is true. It is typically used when you don’t know how many times the loop will run in
advance.

Example:
# Print numbers from 1 to 5 using a while loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
12345

2.For Loop Statement:


A for-loop statement in Python is used to iterate over a sequence (such as a list, tuple, or
string) and perform a certain action for each item in the sequence.

Example:
# Print each character in a string using a for loop
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n

40
Conclusion:
In Python programming, conditional statements and loops are powerful tools for controlling
the flow of your program. They allow you to execute specific blocks of code based on certain
conditions or to repeat a certain block of code multiple times. The if statement, if-else
statement, if-elif-else statement, nested if-else statement, while loop statement, and for loop
statement are some of the most commonly used conditional statements and loops in Python.
****************************************************************************
Files and I/O in Python:
Basic File Operations

1.Opening a File:
 In Python, you use the open() function to open a file. It returns a file object that
provides methods to interact with the file.
 88In Python, you use the open() function to open a file. It returns a file object that
provides methods to interact with the file.
Syntax:
file = open('filename.txt', 'r') # Open for reading (default mode)
•Modes for opening files:
'r': Read (default mode)
'w': Write (creates a new file or truncates an existing file)
'a': Append (adds to the end of the file)
'b': Binary mode (e.g., 'rb' or 'wb' for binary files)
'x': Exclusive creation (fails if the file already exists)

2.Reading from a File:


You can read the contents of a file in several ways:
•Read the entire file:
content = file.read()
print(content)
•Read one line at a time:
line = file.readline()
print(line)
•Read all lines into a list:
lines = file.readlines()
print(lines)

3.Writing to a File:
You use the write() or writelines() methods to write to a file.
•Write a string to the file:
file = open('filename.txt', 'w')
file.write('Hello, World!\n')
file.close()
•Write multiple lines:
lines = ['Hello, World!\n', 'Python is awesome!\n']
file.writelines(lines)

4.Closing a File:
Always close a file after you are done with it to free up system resources.

41
file.close()
Using Context Managers:
A more elegant way to handle files is using a with statement, which automatically closes the
file when the block is exited.
with open('filename.txt', 'r') as file:
content = file.read()
print(content)
8file
s 'cplex'>
****************************************************************************
Errors and Exceptions
Errors are problems in a program due to which the program to stop its execution. On the other
hand, exceptions are raised when some internal events occurwhich changes the normal flow of
the program.
Two types of errors occurs in python:
1.Syntax errors
2.Logical errors (Exceptions)
1.Syntax errors:
When the proper syntax of the language is not followed then a syntax error is thrown.
It returns a syntax error message because after the if statement a colon: is missing. We can fix
this by writing the correct syntax.
Example:
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase DsaSelf Paced or not
if(amount>2999)
print("You are eligible to purchase DsaSelf Paced")
Output:

2.logical errors(Exceptions):
When in the runtime an error that occurs after passing the syntax test is called exception or
logical type. For example, when we divide any number by zero then the ZeroDivisionError
exception is raised, or when we import a module that does not exist Import a module that does
not exist then ImportError is raised.
Example:
#initialize the amount variable
marks=10000
#perform division with 0
a=marks/0
print(a)
Output:
Traceback (most recent call last):
File “/home/f3ad05420ab851d4bd106ffb04229907.py”, line 4, in <module>

42
a=marks/0
ZeroDivisionError: division by zero

 Some of the common built-in exceptions are other than above mention exceptions are:

Exception Description
Index Error When the wrong index of a list is retrieved
Assertion Error It occurs when the assert statement fails
Attribute Error It occurs when an attribute assignment is failed.
Import Error It occurs when an imported module is not found.
Key Error It occurs when the key of the dictionary is not found
Name Error It occurs when the variable is not defined.

Memory Error It occurs when a program runs out of memory.

Type Error It occurs when a function and operation are applied in an incorrect
type.

Error Handling:
When an error and an exception are raised then we handle that with the help of the Handling
method.
``1.Handling Exceptions with Try/Except/Finally
We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall
back code in except and final code in finally block.
Example:
# put unsafe operation in try block
try:
print("code start")
# unsafe operation perform
print(1 / 0)
# if error occur the it goes in except block
except:
print("an error occurs")
# final code in finally block
finally:
print("GeeksForGeeks")
Output:
code start
an error occurs
GeeksForGeeks

2.Raising exceptions for a predefined condition


When we want to code for the limitation of certain conditions then we can raise an exception.
Example:
# try for unsafe code
try:

43
amount = 1999
if amount < 2999:
# raise the ValueError
raiseValueError("please add money in your account")
else:
print("You are eligible to purchase DSA Self Paced course")
# if false then raise the value error
exceptValueErroras e:
print(e)
Output:
please add money in your account
****************************************************************************
FUNCTIONS AND FUNCTIONAL PROGRAMMING
Python Functions
Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.
Syntax: Python Functions

Creating a Python Function


We can create a Python function using the def keyword.
A simple Python function
def fun ():
print ("Welcome to GFG")

Calling a Python Function


After creating a function, we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Example:
# A simple Python function
def fun):
print ("Welcome to GFG")
#Driver code to call a function
Fun ()
Output:
Welcome to GFG

Defining and calling a function with parameters


If you have experience in C/C++ or Java then you must be thinking about the return type of the

44
function and data type of arguments. That is possible in Python as well (specifically for Python
3.5 and above).

Syntax:
Python Function with parameters
def function _name (parameter: data _type) -> return_ type:
""" Doctring """
#body of the function
return expression
The following example uses arguments that you will learn later in this article so you can come
back on it again if not understood. It is defined here for people with prior experience in
languages like C/C++ or Java.

Example
def add (num1: int, num2: int) ->int:
“”” Add two numbers"””
return num3
#Driver code
num1, num2=5,15
a ns =add (num1, num2)
print (f" The addition of {num1} and {num2) results (a ns}.")
Output:
The addition of 5 and 15 results 20.

Arguments of a Python Function


Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call.
Let's discuss each type in detail.
✔ Default arguments: A default argument is a parameter that assumes a default value if a value
is not provided in the function call for that argument.
✓ Keyword arguments: The idea is to allow the caller to specify the argument name with
values so that caller does not need to remember the order of parameters.
Return statement in Python function
The function return statement is used to exit from a function and go back to the function caller
and return the specified value or data item to the caller.
Syntax:
return [expression _list]
The return statement can consist of a variable, an expression, or a constant which is returned to
the end of the function execution. If none of the above is present with the return statement a
None object is returned.
Pass by Reference or pass by value
One important thing to note is, in Python every variable name is a reference. When we pass a
variable to a function, a new reference to the object is created. Parameter passing in Python is
the same as reference passing in Java.
Anonymous functions in Python Function
In Python, an anonymous function means that a function is without a name. As we already
know the def keyword is used to define the normal functions and the lambda keyword is used
to create anonymous functions

45
Python Function within Functions
A function that is defined inside another function is known as the inner function or nested
function. Nested functions are able to access variables of the enclosing scope. Inner functions
are used so that they can be protected from everything happening outside the function.
Functional Programming
Functional programming is a programming paradigm in which we try to bind everything in
pure mathematical functions style. It is a declarative type of programming style. Its main focus
is on "what to solve" in contrast to an imperative style where the main focus is "how to solve".
It uses expressions instead of statements. An expression is evaluated to produce a value
whereas a statement is executed to assign variables.
Concepts of Functional Programming
Any Functional programming language is expected to follow these concepts.
1. Pure Functions: These functions have two main properties. First, they always produce the
same output for the same arguments irrespective of anything else. Secondly, they have no side-
effects i.e. they do modify any argument or global variables or output something
2. Recursion: There are no "for" or "while" loop in functional languages. Iteration in
functional languages is implemented through recursion.
3. Functions are First-Class and can be Higher-Order: First-class functions are treated as
first-class variable. The first-class variables can be passed to functions as a parameter, can be
returned from functions or stored in data structures.
4.Variables are Immutable: In functional programming, we can't modify a variable after it's
been initialized. We can create new variables - but we can't modify existing variables.
Immutability
The second property is also known as immutability. The only result of the Pure Function is the
value it returns. They are deterministic. Programs done using functional programming are easy
to debug because pure functions have no side effects or hidden I/O. Pure functions also make it
easier to write parallel/concurrent applications. When the code is written in this style, a smart
compiler can do many things - it can parallelize the instructions, wait to evaluate results when
needing them, and memorize the results since the results never change as long as the input
doesn't change.
Example:
#Python program to demonstrate
# pure functions
# A pure function that does Not
#changes the input list and
#returns the new List
def pure _func(List):
New _List=[]
for i in List:
New _ List. append(i**2)
return New _ List
# Driver's code
Original _ List = [1, 2, 3, 4]
Modified _List = pure _ fun (Original _List)
Print ("Original List:", Original _List)
Print ("Modified List:", Modified _List)
Output:
Original List: [1, 2, 3, 4]
Modified List: [1, 4, 9, 16]

46
Recursion:
During functional programming, there is no concept of for loop or while loop, instead
recursion is used. Recursion is a process in which a function calls itself directly or indirectly
In the recursive program, the solution to the base case is provided and the solution to the
bigger problem is expressed in terms of smaller problems. A question may arise what is base
case? The base case can be considered as a condition that tells the compiler or interpreter to
exit from the function.
Note: For more information, refer Recursion
Example: Let's consider a program that will find the sum of all the elements of a list without
using any for loop.
Python program to demonstrate Recursion
Recursive Function to find sum of a list
def Sum (L, i, n, count):
#Base case
if n <= i
return count

count+= L[i]
#Going into the recursion
count=Sum(L, i + 1, n, count)
return count
#Driver's code
L= [1, 2, 3.4.5]
count = o
n= len (L)
print(Sum(L, o, n, count))

Output:
15
****************************************************************************
MODULES:
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code. Grouping related
code into a module makes the code easier to understand and use. It also makes the code
logically organized.

Create a simple Python module


Let's create a simple calc.py in which we define two functions, one add and another subtract.
 A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Modules provide us with a way to share reusable functions. A module is simply a
"Python file" which contains code we can reuse in multiple Python programs. A module may
contain functions, classes, lists, etc.

Modules in Python can be of two types


1. Built-in Modules.
2.User-defined Modules.

47
1.Built-in Modules in Python : One of the many superpowers of Python is that it comes with
a "rich standard library". This rich standard library contains lots of built-in modules. Hence, it
provides a lot of reusable code.
2.User-Defined Modules in Python : Another superpower of Python is that it lets you take
things in your own hands. You can create your own functions and classes, put them inside
modules and voila! You can now include hundreds of lines of code into any program just by
writing a simple import statement.

Importing Modules in Python


We use the import keyword to import both built-in and user-defined modules in Python. Let's
import our user-defined module from the previous section into our Python shell:
>>> import mypymodule
To call the greeting function of mypymodule, we simply need to use the dot notation:
>>> mypymodule.greeting("Techvidvan")
Output:
Hello, Techvidvan
Similarly, we can import mypymodule into any Python file and call the greeting function as we
did above.

****************************************************************************

Object Oriented Programming


Object Oriented Programming is a fundamental concept in Python, empowering developers to
build modular, maintainable, and scalable applications.
The main concept of object-oriented Programming (OOPs) or oops concepts in Python is to
bind the data and the functions that work together as a single unit so that no other part of the
code can access this data.
Points to Remember
1. Everything is an object
2. Developer manipulates objects that uses message passing.
3. Every object is an instance of a class.
4. The class contains the attribute and behaviour associated with an object.
Pillars of OOPs
The major concepts that we have discussed above are known as pillars of OOPs. There are four
pillars on which OOP rests.
1. Class and Object
2. Inheritance
3. Abstraction
4. Encapsulation
5. Polymorphism

1.Classes and Objects:

o Class: A blueprint for creating objects. It defines a set of attributes and methods that the created objects
will have.
o Object: An instance of a class. For example, if Dog is a class, then my_dog could be an object of that
class.

48
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print("Woof!")

my_dog = Dog("Buddy", 3)
my_dog.bark()

Output:
Woof!
2.Inheritance: The concept allows us to inherit or acquire the properties of an existing
class (parent class) into a newly created class (child class). It is known as inheritance. It
provides code reusability.

Example:
class Animal:
def eat(self):
print("I can eat!")

class Dog(Animal):
def bark(self):
print("Woof!")

my_dog = Dog()
my_dog.eat() # Output: I can eat!
my_dog.bark() # Output: Woof!
Output:
I can eat!
Woof!
3.Abstraction: The concept allows us to hide the implementation from the user but shows
only essential information to the user. Using the concept developer can easily make changes
and added over time.
There are the following advantages of abstraction:
 It reduces complexity.
 It avoids delicacy.
 Eases the burden of maintenance
 Increase security and confidentially.

4.Encapsulation: Encapsulation is a mechanism that allows us to bind data and functions


of a class into an entity. It protects data and functions from outside interference and misuse.
Therefore, it also provides security. A class is the best example of encapsulation.
Class
{
data members

49
+
methods (behavior)
}
5.Polymorphism: The word polymorphism is derived from the two words i.e. ploy and
morphs. Poly means many and morphs means forms. It allows us to create methods with the
same name but different method signatures. It allows the developer to create clean, sensible,
readable, and resilient code.

IMPORTANT QUESTIONS

1.Write about Python Basics and Python Objects and Numbers.


2.What are the Sequences in python?
3.Write about Strings, Lists, and Tuples.
4.Write about Mapping and Set Types.
5. Explain about Conditionals and Loops in Python.
6.Write about Files and Input/output.
7.Write about Errors and Exceptions.
8.Write about Functions and Functional Programming.
9. Explain about python Modules.
10. Write about Object oriented programming.

50

You might also like