You are on page 1of 39

UNIT V - CONTROL FLOW

if, if-else, for, while, break, continue, pass Functions - Defining Functions, Calling Functions,
Passing Arguments, Default Arguments, Variable-length arguments, Fruitful Functions (Function
Returning Values), Scope of the Variables in a Function - Global and Local Variables.
Development of sample scripts and web applications. Client Side Scripting, Server-Side Scripting,
Managing data with SQL, Cookies, use the cookies, advantages of the cookies and how to create
cookies. Introduction to Node.js.

if, if-else, for, while, break, continue, pass

Python If ... Else


Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if


statements" and loops.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.

Example
If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.

Example
One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:
Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

The pass Statement


if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting an
error.

Example
a = 33
b = 200

if b > a:
pass
Loop:

Python Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language provides following types of loops to handle looping
requirements.

Sr.No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is TRUE. It


tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 nested loops

You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

Sr.No. Control Statement & Description


1 break statement

Terminates the loop statement and transfers execution to the statement


immediately following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

3 pass statement

The pass statement in Python is used when a statement is required syntactically


but you do not want any command or code to execute.

Python has two primitive loop commands:

• while loops
• for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is
true.

Example
Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue forever.


The while loop requires relevant variables to be ready, in this example we need
to define an indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is
true:

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement


With the continue statement we can stop the current iteration, and continue
with the next:

Example
Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no
longer is true:

Example
Print a message once the condition is false:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python While loop


The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.

The syntax is given below.

1. while expression:
2. statements

Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.

Loop Control Statements


We can change the normal sequence of while loop's execution using the loop control
statement. When the while loop's execution is completed, all automatic objects defined
in that scope are demolished. Python offers the following control statement to use within
the while loop.

1. Continue Statement - When the continue statement is encountered, the control


transfer to the beginning of the loop. Let's understand the following example.

Example:

1. # prints all letters except 'a' and 't'


2. i = 0
3. str1 = 'javatpoint'
4.
5. while i < len(str1):
6. if str1[i] == 'a' or str1[i] == 't':
7. i += 1
8. continue
9. print('Current Letter :', a[i])
10. i += 1

Output:

Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n

2. Break Statement - When the break statement is encountered, it brings control out of
the loop.

Example:

1. # The control transfer is transfered


2. # when break statement soon it sees t
3. i = 0
4. str1 = 'javatpoint'
5.
6. while i < len(str1):
7. if str1[i] == 't':
8. i += 1
9. break
10. print('Current Letter :', str1[i])
11. i += 1

Output:

Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a

3. Pass Statement - The pass statement is used to declare the empty loop. It is also used
to define empty class, function, and control statement. Let's understand the following
example.

Example -

# An empty loop
str1 = 'javatpoint'
i=0

while i < len(str1):


i += 1
pass
print('Value of i :', i)
Python For Loops
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.

With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through all
the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Example
Exit the loop when x is "banana", but this time the break comes before the
print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):

Example
Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):
Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by
a break statement.

Example
Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

Python for loop


The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)

For loop Using Sequence


Example-1: Iterating string using for loop

str = "Python"
for i in str:
print(i)

Output:

P
y
t
h
o
n

Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

Output:

C++ vs Java
5
10
15
20
25
30
35
40
45
50s

Example-4: Program to print the sum of the given list.

list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)

Output:

The sum is: 183


For loop Using range() function
The range() function

The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function
is given below.

Syntax:

1. range(start, stop, step size)

o The start represents the beginning of the iteration.

o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.

o The step size is used to skip the specific numbers from the iteration. It is
optional to use. By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

for i in range(10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9

Example - 2: Program to print table of given number.

n = int(input("Enter the number "))


for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)

Output:

Enter the number 10


10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Example-3: Program to print even number using step size in range().

n = int(input("Enter the number "))


for i in range(2,n,2):
print(i)

Output:

Enter the number 20


2
4
6
8
10
12
14
16
18

We can also use the range() function with sequence of numbers. The len() function is
combined with range() function which iterate through a sequence using indexing.
Consider the following example.

list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])

Output:

Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is given
below.

Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements

Example- 1: Nested for loop

# User input for number of rows


rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

Output:

Enter the rows:5


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

Example-2: Program to number pyramid.


rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()

Output:

1
22
333
4444
55555

Using else statement with for loop


Unlike other languages like C, C++, or Java, Python allows us to use the else statement
with the for loop which can be executed only when all the iterations are exhausted.
Here, we must notice that if the loop contains any of the break statement then the else
statement will not be executed.

Example 1

for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")

Output:

0
1
2
3
4
for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2

for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")

In the above example, the loop is broken due to the break statement; therefore, the
else statement will not be executed. The statement present immediate next to else
block will be executed.

Output:

The loop is broken due to the break statement...came out of the loop. We will learn
more about the break statement in next tutorial.
Python Function

Definition of Function
➢ A function is a block of code which only runs when it is called.

➢ You can pass data, known as parameters, into a function.

➢ A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

def show(name):
print("My name is ::"+name)
n=input("Enter your name")
show(n)

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)
my_function("Emil", "Refsnes")

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Default arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
Name: miki
Age 35

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example –

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −


Output is:
10
Output is:
70
60
50

The return Statement


The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a
function as follows −
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total;

# Now you can call sum function


t = sum( 10, 20 );
print ("Outside the function : ", t)

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −

• Global variables
• Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought
into scope. Following is a simple example −
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −


Inside the function local total : 30
Outside the function global total : 0
Difference Between Server-Side Scripting And
Client-Side Scripting
BASIS OF
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON
It is used at the backend where
It is used at the front end which
the source code is not viewable or
Use users can see from the
hidden at the client side
browser.
(browser).
A web server runs the script for A browser runs the script for
server-side scripting that creates client-side scripting that is
Script Running
the page which needs to be sent already present in the user’s
to the browser. computer.
It happens when a user’s browser It happens when the browser
initiates a server request. Dynamic possesses all the codes and the
Occurrence
pages are then created based on page in later changed according
several conditions. to the user’s input.
The scripting process of client
The scripting process for the
server is executed on a local
server side is done on remote
computer and thus the
Execution computer and hence the response
response is comparatively
is comparatively slower than the
quicker when compared to
client side one.
server side scripting.
A browser can perform the
A server can carry out a server-
client-side scripting after
Operation side script, but cannot perform the
receiving the page sent by the
client side scripting.
server.
It helps in connecting to the It does not connect to the
Connection to
databases that are already present databases that are on the web
the database
in the web server. server.
It is excellent for any case
It is excellent for any area that
Suitability which requires user
requires loading of dynamic data.
interaction.
Languages commonly used for
Languages used in server scripting
client-side scripting are
Languages are Ruby on Rails, PHP,
Javascript, HTML, CSS, VB
ColdFusion, Python, ASP, Perl etc
script etc.
Access To It has access to all the files It has no access to all the files
Files present in the web server. present in the web server.
It is more secure than client side
It is less secure because the
scripting as the server side scripts
Security scripts are usually not hidden
are usually hidden from the client
from the client end.
end.
Server-side Scripting Client-side Scripting

It helps work with the back


It helps work with the front end.
end.

It doesn’t depend on the


It is visible to the users.
client.

It runs on the web server. The scripts are run on the client browser.

It helps provide a response to


every request that comes in It runs on the user/client’s computer.
from the user/client.

This is not visible to the client


It depends on the browser’s version.
side of the application.

It requires the interaction with


It doesn’t interact with the server to process
the server for the data to be
data.
process.
Server side scripting requires
languages such as PHP, Client side scripting involves languages
ASP.net, ColdFusion, Python, such as HTML, CSS, JavaScript.
Ruby on Rails.
It is considered to be a secure
It is considered to be less secure in
way of working with
comparison to client side scripting.
applications.

It can be used to customize


It helps reduce the load on the server.
web pages.

It can also be used to provide


dynamic websites.
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.

What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO standard, there are different versions of the SQL
language.

However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.

Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:

• An RDBMS database program (i.e. MS Access, SQL Server, MySQL)


• To use a server-side scripting language, like PHP or ASP
• To use SQL to get the data you want
• To use HTML / CSS to style the page

RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a


collection of related data entries and it consists of columns and rows.

Look at the "Customers" table:

Example
SELECT * FROM Customers;

Every table is broken up into smaller entities called fields. The fields in the
Customers table consist of CustomerID, CustomerName, ContactName,
Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.

A record, also called a row, is each individual entry that exists in a table. For
example, there are 91 records in the above Customers table. A record is a
horizontal entity in a table.

A column is a vertical entity in a table that contains all information associated


with a specific field in a table.
What is cookie?
A cookie is a small piece of text file stored on user's computer in the form of name-value pair.
Cookies are used by websites to keep track of visitors e.g. to keep user information like username
etc. If any web application using cookies, Server send cookies and client browser will store it. The
browser then returns the cookie to the server at the next time the page is requested. The most
common example of using a cookie is to store User information, User preferences, Password
Remember Option etc

Some facts about Cookie

Here are a few facts to know about cookies:

• Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another
domain. This is done by the browser for security purpose.
• Cookies are browser specific. Each browser stores the cookies in a different location. The cookies
are browser specific and so a cookie created in one browser(e.g in Google Chrome) will not be
accessed by another browser(Internet Explorer/Firefox). Most of the browsers store cookies in text
files in clear text. So it’s not secure at all and no sensitive information should be stored in cookies.
• Most of the browsers have restrictions on the length of the text stored in cookies. It is 4096(4kb)
in general but could vary from browser to browser.
• Some browsers limit the number of cookies stored by each domain(20 cookies). If the limit is
exceeded, the new cookies will replace the old cookies.
• Cookies can be disabled by the user using the browser properties. So unless you have control
over the cookie settings of the users (for e.g. intranet application), cookies should not be used.
• Cookie names are case-sensitive. E.g. UserName is different than username.

Advantages of using cookies


Here are some of the advantages of using cookies to store session state.
• Cookies are simple to use and implement.
• Occupies less memory, do not require any server resources and are stored on the user's
computer so no extra burden on server.
• We can configure cookies to expire when the browser session ends (session cookies) or they can
exist for a specified length of time on the client’s computer (persistent cookies).
• Cookies persist a much longer period of time than Session state.

Disadvantages of using cookies


Here are some of the disadvantages:
• As mentioned previously, cookies are not secure as they are stored in clear text they may pose a
possible security risk as anyone can open and tamper with cookies. You can manually encrypt and
decrypt cookies, but it requires extra coding and can affect application performance because of the
time that is required for encryption and decryption
• Several limitations exist on the size of the cookie text(4kb in general), number of cookies(20 per
site in general), etc.
User has the option of disabling cookies on his computer from browser’s setting .
• Cookies will not work if the security level is set to high in the browser.
• Users can delete a cookies.
• Users browser can refuse cookies,so your code has to anticipate that possibility.
• Complex type of data not allowed (e.g. dataset etc). It allows only plain text (i.e. cookie allows
only string content)
Node.js Introduction
What is Node.js?
• Node.js is an open source server environment
• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• Node.js uses JavaScript on the server

Why Node.js?
Node.js uses asynchronous programming!

A common task for a web server can be to open a file on the server and return
the content to the client.

Here is how PHP or ASP handles a file request:

1. Sends the task to the computer's file system.


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the
content to the client.

Node.js eliminates the waiting, and simply continues with the next request.

Node.js runs single-threaded, non-blocking, asynchronously programming,


which is very memory efficient.

What Can Node.js Do?


• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete, and close files on the server
• Node.js can collect form data
• Node.js can add, delete, modify data in your database

What is a Node.js File?


• Node.js files contain tasks that will be executed on certain events
• A typical event is someone trying to access a port on the server
• Node.js files must be initiated on the server before having any effect
• Node.js files have extension ".js"

What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8
Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36.
The definition of Node.js as supplied by its official documentation is as follows −
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect for data-intensive real-time applications
that run across distributed devices.
Node.js is an open source, cross-platform runtime environment for developing server-
side and networking applications. Node.js applications are written in JavaScript, and can
be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
Node.js = Runtime Environment + JavaScript Library

Features of Node.js
Following are some of the important features that make Node.js the first choice of
software architects.
• Asynchronous and Event Driven − All APIs of Node.js library are asynchronous,
that is, non-blocking. It essentially means a Node.js based server never waits for
an API to return data. The server moves to the next API after calling it and a
notification mechanism of Events of Node.js helps the server to get a response
from the previous API call.
• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library
is very fast in code execution.
• Single Threaded but Highly Scalable − Node.js uses a single threaded model
with event looping. Event mechanism helps the server to respond in a non-
blocking way and makes the server highly scalable as opposed to traditional
servers which create limited threads to handle requests. Node.js uses a single
threaded program and the same program can provide service to a much larger
number of requests than traditional servers like Apache HTTP Server.
• No Buffering − Node.js applications never buffer any data. These applications
simply output the data in chunks.
• License − Node.js is released under the MIT license.

Who Uses Node.js?


Following is the link on github wiki containing an exhaustive list of projects, application
and companies which are using Node.js. This list includes eBay, General Electric,
GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few.
• Projects, Applications, and Companies Using Node

Concepts
The following diagram depicts some important parts of Node.js which we will discuss in
detail in the subsequent chapters.

Where to Use Node.js?


Following are the areas where Node.js is proving itself as a perfect technology partner.
• I/O bound Applications
• Data Streaming Applications
• Data Intensive Real-time Applications (DIRT)
• JSON APIs based Applications
• Single Page Applications

Where Not to Use Node.js?


It is not advisable to use Node.js for CPU intensive applications.
Node.js Tutorial

Node.js tutorial provides basic and advanced concepts of Node.js. Our Node.js tutorial
is designed for beginners and professionals both.

Node.js is a cross-platform environment and library for running JavaScript applications


which is used to create networking and server-side applications.

Our Node.js tutorial includes all topics of Node.js such as Node.js installation on
windows and linux, REPL, package manager, callbacks, event loop, os, path, query
string, cryptography, debugger, URL, DNS, Net, UDP, process, child processes, buffers,
streams, file systems, global objects, web modules etc. There are also given Node.js
interview questions to help you better understand the Node.js technology.

What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript
applications outside the browser. It is used for creating server-side and networking web
applications. It is open source and free to use. It can be downloaded from this
link https://nodejs.org/en/

Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used
to run real-time server applications.

The definition given by its official documentation is as follows:

How to find Nth Highest Salary in SQL

?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect for data-intensive real-time applications
that run across distributed devices.?
Node.js also provides a rich library of various JavaScript modules to simplify the
development of web applications.

1. Node.js = Runtime Environment + JavaScript Library

Different parts of Node.js

The following diagram specifies some important parts of Node.js:

Features of Node.js
Following is a list of some important features of Node.js that makes it the first choice of
software architects.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so


its library is very fast in code execution.

2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So a Node.js based server never waits for an
API to return data. The server moves to the next API after calling it and a
notification mechanism of Events of Node.js helps the server to get a response
from the previous API call. It is also a reason that it is very fast.
3. Single threaded: Node.js follows a single threaded model with event looping.

4. Highly Scalable: Node.js is highly scalable because event mechanism helps the
server to respond in a non-blocking way.

5. No buffering: Node.js cuts down the overall processing time while uploading
audio and video files. Node.js applications never buffer any data. These
applications simply output the data in chunks.

6. Open source: Node.js has an open source community which has produced
many excellent modules to add additional capabilities to Node.js applications.

7. License: Node.js is released under the MIT license.

You might also like