Open Source Programming
Open Source Programming
writing code that other people can freely use and modify. - GitHub, Bitbucket, SourceForge
A software whose source code is available to the public to view, use, modify, and distribute to any one for any
purpose under a permissive license.
You may or may not be able to modify the code, sell the code depending on the license agreement.'
The most common type of open source license is GNU(GPL). With this one, you can do whatever you want with
the software.
The source code must be open and available under the same terms as which you got the code
Copyleft says that anyone who redistributes the software, with or without changes, must pass along
the freedom to further copy and change it. Copyleft guarantees that every user has freedom.
Cost: Open source software is typically free to use, modify and distribute.
Customization: The source code of open source software is available to everyone, allowing users to
modify and customize it to suit their needs.
Community support: Open source software often has a large community of developers and users who
contribute to its development and provide support.
Transparency: The source code of open source software is open for everyone to see, making it easier
to identify and fix bugs and vulnerabilities.
Flexibility: Open source software can be used on a wide range of platforms and devices.
Support: While open source software does have a large community of developers and users, it may
not always have the same level of professional support as commercial software.
Compatibility: Open source software may not always be compatible with other software applications
and hardware devices.
Security: Because the source code of open source software is available to everyone, it may be easier
for malicious actors to identify and exploit vulnerabilities.
Complexity: Open source software can be more complex and difficult to use than commercial
software, especially for non-technical users.
Documentation: Open source software may not always have the same level of documentation and
user guides as commercial software.
Examples:
2. Free Software
“Free software” means software that respects users’ freedom and community. Roughly, it means that the users
have the freedom to run, copy, distribute, study, change, and improve the software. The term “free software”
is sometimes misunderstood—it has nothing to do with price. It is about freedom.
Freedom: Free software is often accompanied by a set of ethical principles that promote users’
freedom to use, study, modify, and share the software.
Collaboration: Free software often encourages collaboration among developers and users, leading to
faster development and better quality software.
Transparency: The source code of the software is available for public scrutiny.
Flexibility: Free software can be used on a wide range of platforms and devices.
Support: While free software does have a community of developers and users, it may not always have
the same level of professional support as commercial software.
Compatibility: Free software may not always be compatible with other software applications and
hardware devices.
Security: Because free software is available for everyone to use and modify, it may be easier for
malicious actors to identify and exploit vulnerabilities.
Complexity: Free software can be more complex and difficult to use than commercial software,
especially for non-technical users.
Documentation: Free software may not always have the same level of documentation and user guides
as commercial software.
Difference between Free Software and Open Source Software - No license issue
Source code is closed means the public is not given access to the source code
3. Proprietary Software:
Proprietary software is computer software where the source codes are publicly not available. Only the
company that has created them can modify it. Here the software is developed and tested by the individual or
organization by which it is owned not by the public. This software is managed by a closed team of individuals
or groups that developed it. We have to pay to get this software and its commercial support is available for
maintenance. The company gives a valid and authenticated license to the users to use this software. But this
license puts some restrictions on users also like.
Some examples of Proprietary software include Windows, macOS, Internet Explorer, Google Earth, Microsoft
Office, etc.
Users do not need to have any authenticated Users need to have a valid and authenticated license to
license to use this software. use this software.
The price of open source software is very less. The price of closed source software is high.
Open source software fails fast and fix faster. Closed source software has no room for failure.
In open source software no one is responsible for In closed source software the vendor is responsible if
the software. anything happened to software.
Examples Microsoft Windows, macOS, Internet Explorer, Google Earth, Microsoft Office, Adobe Flash Player,
Adobe reader, Skype, etc.
------------------------------------------------------------------------------------------------------------------------------------------------
Need of OSS
For upgraded products with needed features, we should depend on the closed source vendors.
Without asking the owner a variety of development and testing tools, project management tools,
network monitoring, security, content management can be used.
Before buying a software, get familiar with the OSS. If it can do the required job no need to lock in to
another vendor.
If software with strong community backing is used, we can get great support from community members
throughout the world most likely within minutes.
Closed source software consume huge amount of memory and CPU power for the features never used. In
open source software, most features depends on the demand of community.
Many bugs are fixed by the community before they are even reported by the users.
Process
Real-time processes are required to ‘obey’ response time constraints without any regard to the system’s load.
In different words, real-time processes are urgent and cannot be delayed no matter the circumstances.
- Cannot be delayed
1. Interactive - Constantly interact with users, Spend a lot of time waiting for key presses and mouse
operations - IO bound process.
2. Batch - Do not require any user interaction, often run in the background.
It is the basic part of a multitasking operating system. The Linux scheduler supports different scheduling
algorithms to schedule different types of processes. These are known as scheduler classes.
• Scheduler picks the highest priority queue (class) which has at least one ready process
• Selection of a process within the class could have its own policy
Maximize throughput - (amount of tasks completed per time unit) . Complete as many processes as
possible per unit time
Minimize wait time (amount of time passed since the process was ready until it started to execute) - •
Process should not wait long in the ready queue
Minimize response time (amount of time passed since the process was ready until it finished executing)
- CPU should respond immediately
Maximize fairness (distributing resources fairly for each process) - Give each process a fair share of CPU
Initially, the LINUX kernel used the RR or Round-Robin approach to schedule the processes. In the
Round-Robin approach, a circular queue was maintained that held the processes. Linux 1.2
After the introduction of scheduling classes in LINUX Kernel 2.2, the processes were divided into three
process classes:
o Real-time process
o Non-preemptive process(a process does not leave the CPU until the process makes its system
call)
o Normal process.
After the introduction of the O(N) scheduler in LINUX Kernel 2.4, a queue is used to store processes.
At the time of scheduling, the best process in the queue is selected according to the the priority of the
processes.
In the LINUX Kernel 2.6, the complexity of the scheduler got reduced from O(N) to O(1).
After O(1) scheduler, in Linux 2.6.23, CFS, or Completely Fair Scheduler was introduced.
----------------------------------------------------------------------------------------------------------------------------------------------
O(N) Scheduler
The LINUX Kernel used the O(N) scheduler between version 2.4 to 2.6.
O(N) scheduler divides the processor's time into a unit called epochs.
Within each epoch, every task can execute up to its time slice.
If the task is not completed in the specified epoch, then the scheduler adds half of the remaining time
in the next epoch.
Advantage:
O(n) scheduler was better than the earlier used circular queue scheduler because O(N) scheduler could
schedule N-processes at a time.
JVM - Java Virtual Machine
SMP - Symmetric Multi- Processing - refers to the computer architecture where multiple identical processors
are interconnected to a single shared main memory, with full accessibility to all the I/O devices, unlike
asymmetric MP. In other words, all the processors have common shared(common) memory and same data
path or I/O bus
Disadvantage:
If the number of processes is more, the scheduler may use a notable amount of the processor time itself.
Picking the next task to run requires iteration through all currently planned tasks, so the scheduler runs in O(n)
time, where n is the number of the planned processes.
---------------------------------------------------------------------------------------------------------------------------------------------
O(1) Scheduler
O(1) Scheduler was introduced in LINUX Kernel 2.6. O(1) scheduler is also called as constant time scheduler.
As the name suggests, it can schedule the processes within a constant amount of time, regardless of the
number of processes running on the system.
O(1) scheduler uses two ready queues active run queue and expired run queue in each CPU.
Each queue has 40 priority classes(100-139). 100 has highest priority, 139 has lowest priority.
The active processes are placed in a queue that stores the priority value of each process. This queue is
termed as active run queue, or run queue.
The other queue is an array of expired processes called expired queue. Initially it will be empty. When
the allotted time of a process expires, it is placed into the expired queue.
The scheduler gives a priority to interactive tasks and lowers the priorities of the non-interactive tasks.
_____________________________________
Note:
CFS Scheduler
All the processes are inserted into Red-Black trees and whenever a new process arrives, it is inserted
into the tree.
CFS is similar as ideal-based scheduling instead it priorities each process according to their virtual runnable
time.
16
30
25
40
--------------------------------------------------------------------------------------------------------------------------------------------
Personality
In the context of Linux, "personality" refers to a feature of the kernel that allows it to emulate the behavior of
other operating systems. This is useful for compatibility purposes, enabling Linux to run software designed for
other Unix-like systems.
Two ways
Common Personalities:
Example
This code snippet demonstrates how to get and set the personality of a process in C.
Include Headers:
o #include <stdio.h>: Includes the standard I/O library for input and output functions.
o #include <sys/personality.h>: Includes the header file for the personality system call.
Main Function:
This line calls the personality function with the argument 0xFFFFFFFF, which retrieves
the current personality of the process.
o personality(PER_BSD);:
o persona = personality(0xFFFFFFFF);:
This line retrieves the new personality of the process after setting it to BSD.
o return 0;:
To compile and run this code, you can use the following commands in a Linux terminal:
./personality_example
This will compile the C program and produce an executable named personality_example. Running this
executable will show the current and new personality of the process.
Command-Line Utility:
setarch can be used to invoke a program with a different personality. For example:
The command setarch i386 ./myprogram is used to run a program (./myprogram) in a different architecture or
personality environment than the one currently in use.
It allows to specify a particular architecture for running a program, which can be useful for testing or
compatibility purposes.
i386: i386 specifies the architecture to be used.. This is to run a 32-bit application on a 64-bit system.
-------------------------------------------------------------------------------------------------------------------------------------------
Cloning
Creating copies.
1. Disk Cloning
Disk cloning involves copying the entire content of one disk to another. Tools like dd, Clonezilla, and Partimage
are commonly used for this purpose.
Using dd
The dd command is a versatile utility for copying and converting data. To clone a disk:
This provides a controlled way to grant administrative privileges to users without giving them full root access.
2. Partition Cloning
Partition cloning is similar to disk cloning but focuses on individual partitions. Tools like parted, gparted, or dd
can be used for partition cloning.
Using dd
Cloning a file system involves copying all files from one file system to another while preserving file attributes,
permissions, and links. Tools like rsync are ideal for this task.
Using rsync
Process Cloning
In the context of processes, cloning refers to creating a new process that is a copy of an existing process. This
is often achieved using the fork system call in programming.
Example in C
LINUX Signals
A feature of LINUX programming is the idea of sending and receiving signals. A signal is a kind of (usually
software) interrupt, used to announce asynchronous events to a process.
There is a limited list of possible signals; we do not invent our own. (There might be 64 signals, for instance.)
The name of a LINUX signal begins with "SIG". Although signals are numbered, we normally refer to them by
their names. For example:
SIGINT is a signal generated when a user presses Control-C. This will terminate the program from the
terminal.
SIGALRM is generated when the timer set by the alarm function goes off.
When the signal occurs, the process has to handle it. There are three cases:
Ignore it. Many signals can be and are ignored, but not all. Hardware exceptions such as "divide by 0"
(with integers) cannot be ignored successfully and some signals such as SIGKILL cannot be ignored at
all.
Catch and handle the exception. The process has a function to be executed if and when the exception
occurs. The function may terminate the program gracefully or it may handle it without terminating the
program.
Let the default action apply. Every signal has a default action. The default may be:
o ignore
o terminate
Each signal has a current "disposition" which indicates what action will be the default; an additional option is
to have a programmer-defined function to serve as the signal handler.
An example of the use of signals is the use of the waitpid() function. It puts the calling process in a wait state
(action = STOP) until the child process indicated has a change of status, which will be reported by a SIGCHILD
signal (action = resume). By default, waitpid() expects the child to terminate, but there are ways to change this
so other changes of status can be handled.
Most of the Linux users use the key combination Ctr+C to terminate processes in Linux.
Whenever Ctrl+C is pressed, a signal SIGINT is sent to the process. The default action of this signal is to
terminate the process. But this signal can also be handled. The following code demonstrates this:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void sig_handler(int signo)
{
if (signo == SIGINT)
printf("received SIGINT\n");
}
int main(void)
{
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
// A long long wait so that we can easily issue a signal to this process
while(1)
sleep(1);
return 0;
}
-----------------------------------------------------------------------------------------------------------------------------------------------
UNIT II
PHP Variables
As PHP is a loosely typed language, we need not declare the data types of the variables.
$variablename = value;
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
PHP variables are case-sensitive, so $name and $NAME both are treated as different variable
---------------------------------------------------------------------------------------------------------------------------------------
PHP supports 8 primitive data types that can be categorized further in 3 types:
It holds only single value. There are 4 scalar data types in PHP.
It can hold multiple values. There are 2 compound data types in PHP.
1. array 2.object
1. resource 2. NULL
To determine the type of a variable at any time by using PHP ’ s gettype() function.
$test_var = 8.23;
$test_var = 8.23
--------------------------------------------------------------------------------------------------------------------------------------
By default, the data type of the variable accepted through readline() function is string. So for any other data
type, we have to typecast it explicitly as described below.
<?php
We can achieve the same thing without prompting the user also:
$a = readline();
// Input 10 20
// Typecasting to integers
$var1 = (int)$var1;
$var2 = (int)$var2;
echo "The sum of " . $var1 . " and " . $var2 . " is " . ($var1 + $var2);
?>
Output:
<?php
// For input 1 2 3 4 5 6
// For output
print_r($arr);
?>
Output:
Array
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
Method 2:
Using fscanf() function works same as the fscanf() function in C. We can read 2 integers from
Keyboard(STDIN) as below:
<?php
// Input 1 5
// Output
echo "The sum of " . $a . " and " . $b . " is " . ($a + $b);
?>
Output:
-----------------------------------------------------------------------------------------------------------------------------------------------
PHP Operators
1. Arithmetic Operators
2. Assignment Operators
3. Bitwise Operators
4. Comparison Operators
5. Incrementing/Decrementing Operators
6. Logical Operators
7. String Operators
8. Array Operators
9. Type Operators
10. Execution Operators
11. Error Control Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, etc. with numeric values.
Operator Name Example Explanation
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is
"=".
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1,
otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are
set to 1
<< Shift left $a << Left shift the bits of operand $a $b steps
$b
>> Shift right $a >> Right shift the bits of $a operand by $b
$b
number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
<= Less than or equal $a <= Return TRUE if $a is less than or equal $b
to $b
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
return $a
by one
return $a
by one
Logical Operators
Operator Name Example Explanation
xor xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP,
which are given below:
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of
arrays.
=== Identical $a === $b Return TRUE if $a and $b have same value and same type in
same order
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command.
Execution operator and shell_exec() give the same result.
`` backticks echo Execute the shell command and return the result.
`dir`; Here, it will show the directories available in current folder.
<?php
// Statement 1
$result= $hello
// Statement 2
$result= @$hello
?>
** arithmetic Right
(object) (bool) @
| bitwise OR Left
|| logical OR Left
?: ternary Left
or logical Left
---------------------------------------------------------------------------------------------------------
o echo
o print
echo and print are language constructs, and they never behave like a function. Therefore, there is no
requirement for parentheses. However, both the statements can be used with or without parentheses. We
can use these statements to output variables or strings.
echo
o print is also a statement, used as an alternative to echo at many times to display the output.
You can see the difference between echo and print statements with the help of the following programs.
You can pass multiple arguments separated by a comma (,) in echo. It will not generate any syntax error.
1. <?php
2. $fname = "Gunjan";
3. $lname = "Garg";
5. ?>
2. $fname = "Gunjan";
3. $lname = "Garg";
5. ?>
echo statement does not return any value. It will generate an error if you try to display its return value.
1. <?php
2. $lang = "PHP";
4. echo "</br>";
6. ?>
Output:
1. <?php
2. $lang = "PHP";
4. print "</br>";
6. ?>
Output:
_____________________________________________________________________________________
1. If Statement
2. Switch Statement
There are various ways to use if statement in PHP.
o if
o if-else
o if-else-if
o nested if
PHP If Statement
If statement is used to executes the block of code exist inside the if statement only if the specified condition
is true.
Syntax
1. if(condition){
2. //code to be executed
3. }
Flowchart
Example
1. <?php
2. $num=12;
3. If ($num<100) {
5. }
6. ?>
Output:
If-else statement is slightly different from if statement. It executes one block of code if the specified condition
is true and another block of code if the condition is false.
Syntax
1. If (condition) {
3. } else {
5. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num%2==0){
5. }else{
7. }
8. ?>
Output:
12 is even number
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check
multiple conditions using this statement.
Syntax
1. if (condition1){
3. } elseif (condition2) {
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else {
10. }
Flowchart
Example
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
The nested if statement contains the if block inside another if block. The inner if statement executes only
when specified condition in outer if statement is true.
Syntax
1. if (condition) {
3. if (condition) {
5. }
6. }
Flowchart
Example
1. <?php
2. $age = 20;
3. $nationality = "Indian";
5. if ($nationality == "Indian")
6. {
9. }
10. else {
12. }
13. }
14. ?>
1. <?php
6. }
7. }
8. ?>
Output:
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if
statement.
Syntax
1. switch(expression) {
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
11. }
1. The default is an optional statement. Even it is not important, that default must always be the last
statement.
2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all the statements will execute
after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
6. break;
7. case 20:
9. break;
12. break;
13. default:
15. }
16. ?>
_____________________________________________________________________________
2. While Ststement
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is used
when you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
2. {
3. //code to be executed
4. }
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following
meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This
parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE,
the loop execution continues, otherwise the execution of the loop ends.
Flowchart
Example
1. ?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it
will execute infinite.
1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only
when the outer for loop condition is found true.
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is
to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for
1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
Example
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
5. }
6. }
7. ?>
Output:
11
12
13
21
22
23
31
32
33
It works only on array and object. It will issue an error if you try to use it with the variables of different
datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the
elements of an array.
Syntax
1. for each( $array as $var ){
2. //code to be executed
3. }
4. ?>
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. for each( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
Season is: winter
Season is: summer
Season is: winter
Season is: spring
Season is: autumn
Flowchart
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code
repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop.
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer
while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed
9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
Example
1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>
Output:
11
12
13
21
22
23
31
32
33
PHP Infinite While Loop
Syntax
1. while(true) {
2. //code to be executed
3. }
Example
1. <?php
2. while (true) {
3. echo "Hello ";
4. echo "</br>";
5. }
6. ?>
Output:
Hello
Hello
Hello
Hello
.
.
.
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is
guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If we have to execute
the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while
loop.
It executes the code at least one time always because the condition is checked after executing the code.
The do-while loop is very much similar to the while loop except the condition check. The main difference
between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks
the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is
must that the program should not contain any other statements after the do-while loop. In this case, it will
not generate any error.
The while loop is also named as entry control The do-while loop is also named as
loop. exit control loop.
The body of the loop does not execute if the The body of the loop executes at least once, even if the
condition is false. condition is false.
Condition checks first, and then block of Block of statements executes first
statements executes. and then condition checks.
PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If
you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow
of the program at the specified condition and program control resumes at the next statements outside the
loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with
switch case.
Flowchart
The PHP continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition.
The continue statement is used within looping and switch control structure when you immediately jump to
the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop.
The continue statement allows the user to skip the execution of the code for the specified condition.
Example
In the following example, we will print only those values of i and j that are same and skip others.
1. <?php
2. //outer loop
3. for ($i =1; $i<=3; $i++) {
4. //inner loop
5. for ($j=1; $j<=3; $j++) {
6. if (!($i == $j) ) {
7. continue; //skip when i and j does not have same values
8. }
9. echo $i.$j;
10. echo "</br>";
11. }
12. }
13. ?>
Output:
11
22
33
PHP continue Example in while loop
Example
In the following example, we will print the even numbers between 1 to 20.
1. <?php
2. //php program to demonstrate the use of continue statement
3.
4. echo "Even numbers between 1 to 20: </br>";
5. $i = 1;
6. while ($i<=20) {
7. if ($i %2 == 1) {
8. $i++;
9. continue; //here it will skip rest of statements
10. }
11. echo $i;
12. echo "</br>";
13. $i++;
14. }
15. ?>
Output:
Arrays
Array is a list of values. Each value within an array is called an element , and each element is referenced by
its own index , which is unique to that array. To access an element use that element ’ s index.
Indexed arrays — These are arrays where each element is referenced by a numeric index, usually starting
from zero. For example, the first element has an index of 0, the second has an index of 1, and so on
Associative arrays — This type of array is also referred to as a hash or map. With associative arrays, each
element is referenced by a string index. For example, you might create an array element representing a
customer ’ s age and give it an index of “ age.
Creating Arrays
The simplest way to create a new array variable is to use PHP ’ s built - in array() construct. This takes a list of
values and creates an array containing those values, which you can then assign to a variable:
If you want to create an associative array, where each element is identified by a string index rather than a
number, you need to use the => operator, as follows:
Here an associative array is populated in two ways: first using the array() construct, and second using the
square bracket syntax:
This creates an array with three elements: “ The Grapes of Wrath ” , which has an index of “ title “ ; “ John
Steinbeck ”, which has an index of “ author “ ; and 1939 , which has an index of “ pubYear ”.
Accessing Arrays
$authors[2] = “Melville”;
You can ’ t just print an array with print() or echo() , like you can with regular variables, because these
functions can work with only one value at a time. However, PHP does give you a function called print_r() that
you can use to output the contents of an array
print_r ( $authors );
print_r ( $myBook );
To use it, pass it the array to extract the slice from, followed by the position of the first element in the range
(counting from zero), followed by the number of elements to extract.
This example extracts the second and third elements from the $authors array and stores the resulting array in
a new variable, $authorsSlice . The code then uses print_r() to display the slice.
you can use array_slice() with associative arrays. Although associative arrays don ’ t have numeric indices,
PHP does remember the order of the elements in an associative array. So you can still tell array_slice() to
extract, say, the second and third elements of an associative array:
if you leave out the third argument to array_slice() , the function extracts all elements from the start position
to the end of the array:
To preserve the indices, you can pass a fourth argument, true , to array_slice()
Using while
echo “ $element[0] ”;
echo “ $element[1] ”;
To use foreach to retrieve both keys and values, use the following syntax:
“pubYear” = >1939 );
echo “ $value ”;
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
print_r ( $myBooks );
print_r( $myBooks[1] )
array_merge() – – This function is useful for merging two or more arrays together
------------------------------------------------------------------------------------------------------------------------------------------------
Strings
To concatenate two string variables together, use the dot (.) operator −
Output: Hello World 1234
7. trim() function: This function allows us to remove whitespaces or strings from both sides of a string.
Example:
<?php
echo trim("Hello World!", "Hel!");
?>
Output:
llo Worl
8. explode() function: This function converts a string into an array.
Example:
<?php
$input = "Welcome to PHP Class";
print_r(explode(" ",$input));
?>
Output:
Array ( [0] => Welcome [1] => to [2] => PHP [3] => Class )
9. strtolower() function: This function converts a string into the lowercase string.
Example:
<?php
$input = "WELCOME “;
echo strtolower($input);
?>
Output:
welcome
10. strtoupper() function: This function converts a string into the uppercase string.
Example:
<?php
$input = "Welcome ";
echo strtoupper($input);
?>
Output:
WELCOME
__________________________________________________________________________
PHP Functions
Function is a named block of code for a specific task that can be reused many times.
Advantage of Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: No need to write the logic many times. Write the logic only once and reuse it.
Easy to understand: It is easier to understand the flow of the application because every logic is divided in the
form of functions.
Syntax
Example
PHP Function Arguments
We can pass the data in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length
argument list.
1. Call by Value
In call by value, actual value is not affected if it is modified inside the function.
Example:
<?php
function increment($i)
++$i;
$i =10;
Increment($i);
echo $i;
?>
Output
10
2. Call By Reference
In call by reference, actual value is affected if it is modified inside the function. In this case, use &
(ampersand) symbol with formal arguments. The & represents reference of the variable.
Output:
11
In this case, if we don't pass any value to the function, it will use default argument value.
Output:
Total is: 20
Total is: 30
Total is: 80
This means we can pass 0, 1 or n number of arguments in function. To do so, use 3 dots before the argument
name.
Output:
10
Recursive Function
Function calling itself. It is important to specify the base condition to stop recursion. Base condition is the
one which doesn’t call the same function again.
Factorial Number
------------------------------------------------------------------------------------------------------------------------------------------------
UNIT – III
File Handling
To work with a file, first open the file. When you open a file, you create a file handle. A file handle is a
pointer associated with the open file that you can then use to access the file ’ s contents.
The fopen() function opens a file and returns a file handle associated with the file. The first argument passed
to fopen() specifies the name of the file you want to open, and the second argument specifies the mode , or
how the file is to be used.
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Close File
fclose($handle )
Read File
PHP provides various functions to read data from file. The available PHP file read functions are given below.
o fread() - read all file data,
o fgets() - read data line by line
o fgetc() - read data character by character.
fread()
fread( $handle , $length )
Example
1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4. $contents = fread($handle, filesize($filename));//read file
5. echo $contents;//printing data of file
6. fclose($handle);//close file
7. ?>
fgets()
The PHP fgets() function is used to read single line from the file.
Syntax
1. string fgets ( resource $handle [, int $length ] )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function,
use !feof() function inside the while loop.
Syntax
1. string fgetc ( resource $handle )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>
Write File - fwrite()
Syntax
fwrite ( $handle , $string )
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Append to File - fwrite()
The PHP fwrite() function is used to write and append data into file.
Example
1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>
File system permissions determine what different users can do with each file and directory in the file system.
For example, whereas one user might have permission to read and write to a file, another user may only be
allowed to read the file. A third user might not even be allowed to do that.
Generally, PHP automatically gives file read and write permission and gives directory read, write, and execute
permission for all users by default, meaning that anyone can create and delete files within that directory.
There are special functions to change this default permission.
i) Changing Permissions
PHP ’ s chmod() function is used to change the mode, or permissions, of a file or directory. It functions much
like the UNIX chmod command.
To change a file ’ s permissions with chmod() , pass it the filename and the new mode to use.
The 0 (zero) before the 644 is important, because it tells PHP to interpret the digits as an octal number.
File modes are usually expressed as octal numbers containing three digits.
The first digit determines what the file ’ s owner – – usually the user that created the file —
can do with the file.
The second digit determines what users in the file ’ s group — again, usually the group of the
user that created the file — can do with it.
Finally, the last digit dictates what everyone else can do with the file.
The value of each digit represents the access permission for that particular class of user, as follows
chmod() returns true if the permission change was successful, and false if it failed (for example, you ’ re not
the owner of the file).
Examples
[Note that you can only change the permissions of a file or directory if you own it, or if you ’ re the super –
user]
To read the files in a directory, you need to have both read and execute permissions on that
directory.
To create and delete files and subdirectories inside the directory, you need to have write and execute
permissions on the directory.
Example:
Working with Directories
PHP lets you work with directories in much the same way as files, using a variety of equivalent functions.
Some directory functions use a directory handle, whereas others use a string containing the name of the
directory with which you want to work.
A directory handle is similar to a file handle; it ’ s a special variable pointing to a directory, which you can
obtain via the opendir() function:
Directory functions
1. opendir()
If there ’ s a problem in opening the directory (for example, if the directory doesn ’ t exist), opendir() returns
false instead of the directory handle.
closedir()
closedir( $handle );
2. readdir()
[ Each directory contains a list of entries for each of the files and subdirectories inside it, as well as entries
for . (representing the directory) and .. (the parent of the directory).
PHP maintains an internal pointer referring to the next entry in the list, just as a file pointer points to the
position in a file where the next file operation should occur.]
3. rewinddir()
Move the directory pointer back to the start of the list of entries
rewinddir( $handle );
4. chdir()
chdir( “/home/abc/myfolder” );
chdir() returns true if PHP managed to change to the specified directory, or false if there was an error (such
as the directory not being found).
5. mkdir()
Create a directory .
mkdir( “/home/matt/newfolder” );
mkdir() returns true if the directory was created, or false if there was a problem. You can also set
permissions for the directory at the time of creation by passing the mode as the second argument.
6. rmdir()
Deletes a directory
rmdir( “/home/abc/myfolder” );
The rmdir() function removes a given directory. The directory must be empty, and you need appropriate
permissions to remove it.
7. dirname() —
8. basename() –
Example 1
$path = “/home/abc/docs/pgm1.html”;
Example 2:
Steps:
3. If the next entry is a subdirectory, display its name, then call the function recursively to read the
<?php
$dirPath = “/home/abc/images”;
$files = array();
closedir( $handle );
}
traverseDir( $dirPath );
?>
Description
Use readdir() with a while loop to move through each entry in the directory, adding each filename to
the array as it goes (”.” and “..” are skipped).
If a particular filename is a directory, a slash (/) is added to the end of the filename to indicate to the
user (and the rest of the function) that the file is in fact a directory:
$files = array();
A database engine — commonly known as a Database Management System (DBMS) — to store, retrieve,
and modify the data
Database architecture
i) Embedded Databases
An embedded database engine, as its name implies, tied up with the application that uses it (PHP in this
case). Therefore it always runs and stores its data on the same machine as the host application.
The database is not networked, and only one program can connect to it at any given time. Moreover, the
database can ’ t be shared between different machines because each one would simply end up storing and
manipulating its own separate version of the data.
On the plus side, embedded databases tend to be faster, easier to configure, and easier to work with. Long -
standing examples of embedded database engines include dBase and dbm, and PHP supports both these
engines in the form of PHP extensions.
Client - server databases are, generally speaking, more powerful and flexible than embedded databases.
They are usually designed for use over networks, enabling many applications in a network to work
simultaneously with the same data. The database engine itself acts as a server, serving up data to its clients
(much like Web servers serve pages to Web browsers).
This is the kind of database which are more likely to find in a large company, where large quantities of data
need to be shared among many people, where access may be needed from all sorts of different locaions, and
where having a single centralized data store
Fortunately, alternatives are available, such as PostgreSQL and MySQL, which are both open source relational
database systems that have proven very popular with PHP developers for many years.
To specify a literal DATE , DATETIME , or TIMESTAMP value in MySQL, you can use any of the following
formats:
YYYY - MM - DD / YY - MM - DD
YYYY - MM - DD HH:MM:SS / YY - MM - DD HH:MM:SS
YYYYMMDD / YYMMDD
YYYYMMDDHHMMSS / YYMMDDHHMMSS
To actually work with databases and tables, you use SQL statements. Common statements include:
To create a new database, all you have to do is use the CREATE DATABASE command. Type the following to
create a new database called mydatabase :
- >);
[Note: Press Enter at the end of each line. Don ’ t enter the “ -> “ arrows; MySQL displays these automatically
each time you press Enter, to inform you that your statement is being continued on a new line.]
To see a list of tables in your database, use the SHOW TABLES command:
To see the structure of created table by using the EXPLAIN command, as follows:
To retrieve a selected row or rows, introduce a WHERE clause at the end of the SELECT statement. A WHERE
clause filters the results according to the condition in the clause.
change existing data in a table with the UPDATE statement. As with the SELECT statement, a WHERE clause
can be used to specify exactly which rows to update. Otherwise, the entire table gets updated.
mysql > UPDATE fruit SET name = ‘grapefruit’, color = ‘yellow’ WHERE id = 2;
To delete rows, you use the DELETE statement. If you add a WHERE clause, you can choose which row or
rows to delete; otherwise all the data in the table are deleted
To delete a table entirely, use the DROP TABLE statement. Similarly, you can delete an entire database with
DROP DATABASE .
Connecting to MySQL from PHP
i) mysqli (MySQL improved) — This extension is specifically tied to MySQL, and provides the most
complete access to MySQL from PHP. It features both procedural (function - oriented) and object
- oriented interfaces.
ii) PDO (PHP Data Objects) — This is an object - oriented extension that sits between the MySQL
server and the PHP engine. It gives you a nice, simple, clean set of classes and methods that you
can use to work with MySQL databases. Furthermore, you can use the same extension to talk to
lots of other database systems
Making a Connection
To make a connection to a MySQL database in your PHP script, all you need to do is create a new PDO object.
When you create the object, you pass in three arguments:
A string that describes attributes of the connection such as the type of database system, the location of the
database, and the database name.
3. user ’ s password.
The returned PDO object serves as your script ’ s connection to the database:
Example:
$dsn = “mysql:dbname=mydatabase”;
$username = “root”;
$password = “mypass”;
To close the connection, just assign null to your connection variable. This effectively destroys the PDO object,
and therefore the connection:
$conn = null;
Although the PHP engine usually closes connections when a script finishes, it ’ s a good idea to close the
connection explicitly to be on the safe side.
Handling Errors
To set PDO to raise exceptions whenever database errors occur, you use the PDO::SetAttribute method to
set your PDO object ’ s error mode, as follows:
PHP runs the code within the try block. If an exception is raised by PDO, the catch block stores the
PDOException object in $e , then displays the error message with $e - > getMessage() . For example, if the
$password variable in the script contained an incorrect password, you ’ d see a message like this appear
when you ran the script:
Connection failed: SQLSTATE[28000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES)
Reading Data
you can read some data from the database using a SELECT statement. To send SQL statements to the MySQL
server, you use the query method of the PDO object:
If your SQL statement returns rows of data as a result set, you can capture the data by assigning the
The result returned by $conn - > query is actually another type of object, called a PDOStatement object. You
can use this object along with a foreach loop to move through all the rows in the result set. Each row is an
associative array containing all the field names and values for that row in the table. For example:
-----------------------------------------------------------------------------------------------------------------------------------------------
UNIT IV
History of Python
Created by Guido van Rossum - Netherland
Started development in 1989
Launched in 1991 – first version released 0.9.0
1994, Python 1.0
Popular in the decade of 2010
• Van Rossum developed Python as a hobby project
1980s - ABC - Amoeba Operating System.
He had seen some issues with ABC.
He had taken the syntax of ABC, and some of its good features.
• He wanted a
short
unique
mysterious name for his invention.
• Named after a popular BBC’s TV Show
comedy TV show “Monty Python’s Flying Circus”.
• Benevolent dictator for life (BDFL) is a title given by python community.
Features
• Easy-to-learn and use:
Python is clearly defined and easily readable.
The structure of the program is very simple.
It uses few keywords.
• Interpreted:
Python is processed at runtime by the interpreter.
So, there is no need to compile a program before executing it.
You can simply run the program.
• Cross Platform/Portable:
Runs anywhere, including Mac OS X, Windows, Linux, Unix, Android and iOS.
Has the same interface on all platforms.
• Extensible:
Extended easily by adding new modules implemented in C, C++, java etc.
• Free and Open Source:
Doesn't cost anything to download and use Python.
Python can also be freely modified and re-distributed.
• High Level Language:
When writing programs, programmers no need to worry about the low level details.
• Scalable:
Python provides a better structure and support for large programs than shell scripting.
• Libraries
large standard library that supports many common programming tasks.
Interactive
easy to test short snippets of code.
• Object-oriented Language.
Object, class, inheritance, overloading
• Dynamically typed.
Data types are dynamically typed
Mixing incompatible types (e.g. attempting to add a string and a number) will raise
exception
So errors are caught sooner.
Creating Python Programs
Interactive Mode
• When you enter an expression or statement, Python evaluates it and displays its result immediately.
Script Mode
• Type python program in a file called as script
• Python scripts have the extension .py
• Integrated Development Learning Environment (IDLE):
Is a graphical user interface which is completely written in Python.
It is installed along with the python language .
• Features of IDLE:
Multi-window text editor with syntax highlighting
Coloring of input, output and error messages
Auto completion with smart indentation.
Execution Process
Data Types
• A floating-point number can be written using either ordinary decimal notation or scientific
notation.
• Scientific notation is often useful for mentioning very large numbers.
Write the values of the following floating-point numbers in Python’s scientific notation:
a. 355.76 b. 0.007832 c. 4.3212
Arithmetic Expressions
• Type Conversion
2. Strings
• Sequence of characters (alphabets, numbers, special Characters) .
• Various ways to define a string.
single quotes (' ')
Eg. ‘Welcome'
double quotes (" ")
Eg. “Welcome"
triple quotes(""" """) or (’’’ ’’’ ) - (either single or double)
Eg. """ This is a paragraph. It is made up of
multiple lines and sentences.""“
or
’’’ This is a paragraph. It is made up of
multiple lines and sentences.’’’
• Strings are immutable i.e. the contents of the string cannot be changed after it is created.
String in the Python shell with and without the print function
• >>>’Welcome’ >>>”Welcome”
‘Welcome’
• >>>print(‘Welcome’) >>>print(“Welcome”)
Welcome
• When you evaluate a string in the Python shell without the print function, you can see the literal for
the newline character, \n, embedded in the result,
Escape characters can also be used to embed a quote mark within a quoted string
Operations
1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Membership 6.
Comparison
1. Indexing:
• Characters can be accessed using indexing operations
Positive indexing helps in accessing the string from the beginning.
Negative indexing helps in accessing the string from the end.
Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
2. Slicing
To extract part of a string.
Specify 2 values separated by :
Eg. 2:5
2 – first position
5 - Ending position -1
• mystr = ‘language’
>>>Print(mystr[0])
l
>>>Print(mystr[7])
e
>>>Print(mystr[-1])
e
>>>Print(mystr[1:5])
angu
>>>Print(mystr[4:-2])
ua
• Printing without the Newline When you use the print function, it automatically prints a linefeed (\n)
to cause the output to advance to the next line. If you don’t want this to happen after the print
function is finished, you can invoke the print function by passing a special argument end =
where a square box ( ) denotes a blank space. Note that the decimal point is counted as one space.
Formatting in Scientific Notation
If you change the conversion code from f to e, the number will be formatted in scientific
notation. For example,
print(format(57.467657, "10.2e"))
print(format(0.0033923, "10.2e"))
print(format(57.4, "10.2e"))
print(format(57, "10.2e"))
Formatting as a Percentage
You can use the conversion code % to format a number as a percentage. For example
The format 10.2% causes the number to be multiplied by 100 and displayed with a % sign following it. The
total width includes the % sign counted as one space.
Justifying Format
By default, the format of a number is right justified. You can put the symbol < in the format specifier to
specify that the item be left-justified in the resulting format within the specified width. For example,
Formatting Integers
The conversion codes d, x, o, and b can be used to format an integer in decimal, hexadecimal, octal, or binary.
You can specify a width for the conversion. For example
Formatting Strings
You can use the conversion code s to format a string with a specified width. For example
The format specifier 20s specifies that the string is formatted within a width of 20. By default, a string is left
justified. To right-justify it, put the symbol > in the format specifier. If the string is longer than the specified
width, the width is automatically increased to fit the string.
Below table summarizes the format specifiers
LIST
• List is an ordered sequence of comma-separated items (values|elements) between square
brackets[ ].
[5.87, 34, ‘python’, ‘language’]
• Items in the lists can be of different data types.
• Lists are mutable.
Operations on list:
1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5.Updation 6.
Membership 7.Comparison
• What is a[0:3] a[:4] a[1:] a[:] a[0:6:2] a[::-1] a[2:2] a[2,-2]
• List Methods
• Mutability - It is the ability to change after creating .
String Interpolation
String Interpolation is the process of inserting values of variables into placeholders in a string.
To print “hello <name> welcome to geeksforgeeks” where the <name> is the placeholder for the
name of the user.
1. % – Formatting
This is similar to printf style function in C
n1 = 'Arun'
n2 = 'OSP class'
print("Hello % s Welcome to % s." % (n1, n2))
2. Str.format()
In this method, instead of providing a % sign as a placeholder, we define the placeholder
using curly braces { }. The values that we want to replace in the placeholder are passed as
arguments to the format function.
print("Hello {} Welcome to {} ".format(n1,n2))
3. f strings
strings are perhaps the easiest way of performing string interpolation in python. f strings
were introduced after python 3.6
you do not have to define the placeholder and their values separately.
you would write f before quotes
Using f strings you can directly interpolate values into the string by providing the values in curly
brace inside the string.
4. Template
A template is a class inside the string module.
create a template by using the $ sign as a placeholder and then use the substitute function
inside the template class to replace it with placeholder values.
Where it is used
To pass fn as argument
To return fn as result
Map function
Combining two dictionaries with update
• Two lists can be combined using catenation, or append. This concept does not make sense for
dictionary.
• This method takes as argument another dictionary. The values from the argument dictionary are
copied into the receiver, possibly overwriting an existing entry.
Making Copies
• Remember that Python uses reference semantics from assignment. If you simply assign one
dictionary to a new variable, they end up referring to the same collection. A change to one will end
up modifying both:
dicttwo = dictone
dicttwo['xyz'] = 12
print dictone
dicttow = dictone.copy()
dicttwo['xyz'] = 12
print dictone
{'abc': 3, 'def': 7}
• When a dictionary is passed as an argument the parameter is simply assigned the argument value.
Hence both refer to the same value. A change to the dictionary inside the function will remain after
the function returns.
• The function dict takes a list of two-element tuples, and converts them into a dictionary with the first
element in each tuple representing the key and the second representing the value:
• Many times you will find yourself with a list of keys, and separately with a list of values. Zip makes it
easy to convert this into a list of tuples, which can then be used to create a dictionary.
keys = [‘name’,’age’,’weight’]
values = [‘fred’,42,175]
x= dict(zip(keys, values))
• The following syntax shows how to zip together two lists of equal length into one list:
b = [1, 2, 3]
list(zip(a, b))
• The following syntax shows how to zip together two lists of equal length into a dictionary:
values = [1, 2, 3]
dict(zip(keys, values))
{'a': 1, 'b': 2, 'c': 3}
• If your two lists have unequal length, zip() will truncate to the length of the shortest list:
b = [1, 2, 3]
list(zip(a, b))
If you’d like to prevent zip() from truncating to the length of the shortest list, you can instead use the
zip_longest() function from the itertools library.
b = [1, 2, 3]
#zip the two lists together without truncating to length of shortest list
list(zip_longest(a, b))
However, you can use the fillvalue argument to specify a different fill value to use:
b = [1, 2, 3]
list(zip_longest(a, b, fillvalue=0))
UNIT V
Class objects
To add 100 students
Multile objects
Using list
try:
# suspicious code
except:
# code to handle runtime error
1. Place the suspicious code( critical code/sensitive code) in a try: block.
2. After the try: block, include an except: block, to handle the problem
except: block without any exception name catches all the exceptions that occur. Using this kind of
try-except statement is not considered as a good programming practice though, because it catches all
exceptions but does not make the programmer identify the root cause of the problem.
Other clauses
else: block
code to execute if there is no exception
finally: block
code to execute always.( if exception raises or not)
Example
This example tries to open a file where you do not have write permission, so it raises an exception −
try:
fp = open("testfile", "r")
except IOError:
else:
try:
#suspicious code
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
else:
If there is no exception then execute this block.
______________________________________
except:
print ("An error occurred")
-------------
MODULES
A Python module is a Python file that contains classes, functions, or variables that you’d like to include in your
application. A common practice in advanced Python applications is reusable functions or classes combined in
a file, and then imported in other parts of the program.
This is referred to as a Python module. This module can then be imported and the variables and functions can
be reused multiple times without declaring or creating them every time.
We’ll first create a basic method that adds two numbers which it accepts as parameters.
name = "AskPython"
Save the above code as adder.py and we’ll move on to the next step.
Now, this is exactly the same as importing any other module. The only difference is that the module file is
locally located instead of being in the system path. Syntax:
import module_name
module_name.function_name(variable)
import adder
print(nums)
print(nums)
You might have noticed the two variables in our module. We added those to demonstrate how variables can
be directly imported from the module with their values intact.
import adder
nums = adder.add(5, 10)
print(nums)
print(adder.name)
--------------
File Handling
Open a file
Opening a file
All files must first be opened before they can be read from or written to. In Python, when a file is
(successfully) opened, a file object is created that provides methods for accessing the file.
Python provides an open() function that accepts two arguments, file name and access mode in which the file
is accessed. The function returns a file object which can be used to perform various operations like reading,
writing, etc.
Syntax:
The files can be accessed using various modes like read, write, or append. The following are the details about
the access mode to open a file.
1 r It opens the file to read-only mode. The file pointer exists at the beginning. The file is by
default open in this mode if no access mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists at the beginning of the
file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file pointer exists at the
beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously exists or creates a new one if
no file exists with the same name. The file pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file if it exists previously or
creates a new one if no file exists. The file pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the sense that it overwrites
the previous file if one exists whereas r+ doesn't overwrite the previously written file. It creates a new file if
no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file pointer exists at the
beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the previously
written file if exists any. It creates a new file if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer exists at the end of the
previously written file. It creates a new file in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at the end of the file if a file
exists. It creates a new file if no file exists with the same name.
12 ab+ It opens a file to append and read both in binary format. The file pointer remains at the end
of the file.
Example
In the above code, we have passed filename as a first argument and opened file in read mode as we
mentioned r as the second argument. The fileptr holds the file object and if the file is opened
successfully, it will execute the print statement
For working with binary files we need a module called as pickle