Unit-5 ch-2 Function in Python
Unit-5 ch-2 Function in Python
Unit-5 ch-2 Function in Python
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.
• 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
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")
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".
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:
a = 2
b = 330
print("A") if a > b else print("B")
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")
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.
1 while loop
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.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 pass statement
• while loops
• for loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
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")
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.
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.
Example:
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:
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
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:
The for loop does not require an indexing variable to set beforehand.
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":
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Example
Using the range() function:
for x in range(6):
print(x)
Example
Using the start parameter:
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:
for x in adj:
for y in fruits:
print(x, y)
Example
for x in [0, 1, 2]:
pass
str = "Python"
for i in str:
print(i)
Output:
P
y
t
h
o
n
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
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Output:
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:
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.
for i in range(10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Output:
Output:
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
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
Output:
Output:
1
22
333
4444
55555
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.
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.
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.
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:
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
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;
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])
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 –
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
It runs on the web server. The scripts are run on the client browser.
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
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!
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.
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.
• 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.
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.
Node.js eliminates the waiting, and simply continues with the next request.
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.
Concepts
The following diagram depicts some important parts of Node.js which we will discuss in
detail in the subsequent chapters.
Node.js tutorial provides basic and advanced concepts of Node.js. Our Node.js tutorial
is designed for beginners and professionals both.
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.
?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.
Features of Node.js
Following is a list of some important features of Node.js that makes it the first choice of
software architects.
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.