BCA 5 Semester UNIT 4 & 5
BCA 5 Semester UNIT 4 & 5
th
BCA 5 semester
IV And V Units
1
BCA502 UNIXPROGRAMMING
Credits: 4
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
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:
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 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
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.
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
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
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
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);
$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;
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;
}
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
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;
}
<?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
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
</body>
</html>
Output:
1
22
<body>
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
</body>
</html>
Output:
Visit W3Schools!
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str);
?>
</body>
</html>
Output:
Visit W3Schools!
****************************************************************************************************************
23
<body>
</body>
</html>
Create html file as follows : save as formget.html
<!DOCTYPE HTML>
<html>
<body>
</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]
24
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
<!DOCTYPE HTML>
<html>
<body>
</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]
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.
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
27
Start a PHP Session
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 .
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.
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.
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
********************************************************************************************************************************
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:
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'>
"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:
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
2. Set Types
Sets (set):
Syntax:
my_set = {1, 2, 3, 4}
Key Features:
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}
****************************************************************************
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.
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.
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.
Example:
# Print numbers from 1 to 5 using a while loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
12345
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)
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.
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
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
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.
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.
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.
****************************************************************************
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.
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
50