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

Scripting Lang

The document outlines a comprehensive curriculum on scripting languages, covering topics such as PERL, PHP, TCL, and Python across five units. Each unit includes fundamental concepts, advanced programming techniques, and practical applications, along with a series of questions to assess understanding. Key areas of focus include web scripting, data structures, security issues, and localization in web applications.

Uploaded by

KeerthiVardhani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Scripting Lang

The document outlines a comprehensive curriculum on scripting languages, covering topics such as PERL, PHP, TCL, and Python across five units. Each unit includes fundamental concepts, advanced programming techniques, and practical applications, along with a series of questions to assess understanding. Key areas of focus include web scripting, data structures, security issues, and localization in web applications.

Uploaded by

KeerthiVardhani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

R22DCS51 - Scripting Languages

Unit 1 :
1. Introduction to PERL and Scripting Scripts and Programs
2. Origin of Scripting , Scripting Today, Characteristics of Scripting Languages,
3. Web Scripting, and the universe of Scripting Languages.
4. PERL- Names and Values, Variables, Scalar Expressions, Control Structures, arrays, list, hashes,
strings, pattern and regular expressions, subroutines,
5. Advance perl - finer points of looping, pack and unpack,
6. filesystem, eval, data structures, packages, modules, objects,
7. interfacing to the operating system,
8. Creating Internet ware applications,
9. Dirty Hands Internet Programming,
10.security Issues
Unit 2:
1. PHP Basics- Features,
2. Embedding PHP Code in your Web pages,
3. Outputting the data to the browser,
4. Datatypes, Variables, Constants, expressions, string interpolation, control structures,
5. Function, Creating a Function, Function Libraries, Arrays, strings and Regular Expressions.
Unit 3:
1. Advanced PHP Programming Php and Web Forms, Files,
2. PHP Authentication and Methodologies - Hard Coded, File Based, Database Based, IP Based,
3. Login Administration, Uploading Files with PHP,
4. Sending Email using PHP, PHP Encryption Functions, the Mcrypt package,
5. Building Web sites for the World — Translating Websites- Updating Web sites Scripts,
6. Creating the Localization Repository, Translating Files, text, Generate Binary Files, Set the
desired language within your scripts,
7. Localizing Dates, Numbers and Times.
Unit 4:
1. TCL Structure, syntax, Variables and Data in TCL, Control Flow, Data Structures, input/output,
procedures, strings, patterns, files,
2. Advance TCL- eval, source, exec and up level commands, Name spaces, trapping errors,
3. event driven programs, making applications internet aware,
4. Nuts and Bolts Internet Programming,
5. Security Issues, C Interface.
6. Tk- Visual Tool Kits, Fundamental Concepts of Tk, Tk by example,
7. Events and Binding , Perl-Tk.
Unit 5:
1. Python Introduction to Python language,
2. python-syntax, statements, functions, Built-in-functions and Methods, Modules in python,
Exception Handling,
3. Integrated Web Applications in Python — Building Small,
4. Efficient Python Web Systems,
5. Web Application Framework.
Scripting Languages Questions
Unit 1:
1. Explain about scripting language.
2. What are the characteristics of scripting languages? Discuss.
3. Explain about List and Hashes in PERL.
4. Explain last and next control statements in PERL.
5. Discuss in brief about control structures of PERL.
6. Write a program to check whether given number is Armstrong number or not.
7. Explain about web scripting.
8. Write a program to find greatest of 3 numbers using PERL.
9. With examples, discuss about the control structures and subroutines used in Perl.
10.How to make use of file system and packages in Perl? Illustrate with examples.
11.Explain about operators in PERL.
12.Explain in detail about string functions in PERL.
13.Explain about PERL Subroutines.
14.Write a program to print prime numbers using PERL.
15.Describe how to use and implement packages and modules in a PERL script.
16.Give a brief account on various security issues in PERL scripting language.
Unit 2:
1. Explain about function libraries in PHP.
2. How to embed PHP code in a web page? Explain.
3. Explain about features of PHP.
4. Write down the differences between PHP and Java Script.
5. Explain in detail about outputting the data to the browser with an example
6. Write a program to explain about Merging, Slicing, Splicing, and Dissecting Arrays.
7. Explain about embedding PHP code in your web pages with an example.
8. Discuss in brief about string interpolation.
9. What are the features of PHP? Write about the data types, variables and constants used in PHP.
10.How to create functions in PHP? Explain about function libraries in PHP.
11.Explain about control structures of PHP.
12.Explain about regular expressions with an example.
13.Explain about functions in PHP and give an example.
14.Explain about function libraries in PHP.
15.Give the syntax of various control structures used in PHP coding and explain them briefly.
16.Explain the purpose of superglobal array in PHP.
17.What’s the difference between htmlentities( ) and htmlspecialchars( )?
Unit 3:
1. Explain about IP Based authentication.
2. Demonstrate the use of Mcrypt package.
3. Explain about File Based authentication.
4. How to execute a PHP script using command line arguments? Explain with an example script.
5. Explain about PHP Authentication and Methodologies.
6. Explain about Localizing Dates, Numbers, and Times in PHP.
7. Write a program for uploading files with PHP.
8. Explain about translating websites with Gettext.
9. Write about file uploading directives and functions in PHP with examples.
10.Explain the process of sending an email using PHP.
11.How to create localization repository in PHP? Explain.
12.Explain sending email using PHP with a program.
13.Explain about Mcrypt package in PHP.
14.Explain about PHP encryption functions.
15.Write a program to explain about PHP and Web Forms with an example.
16.Describe Database Based, IP Based authentication methodologies in detail.
17.Explain various PHP functions used in updating websites scripts.
Unit 4:
1. Explain about procedures.
2. Write about the patterns available in TCL.
3. Explain about control flow in TCL.
4. Discuss briefly about namespaces in TCL.
5. Explain about operators in TCL.
6. Explain about Nuts and Bolts internet programming.
7. Explain about trapping errors in TCL.
8. Discuss in detail about Visual Tool Kits in Tk.
9. Explain the fundamental concepts of TK with an example.
10.Write about the data structures used in TCL.
11.Discuss about events, binding and its usage in TK with examples.
12.Explain about event driven programs with an example.
13.Explain about binding in Tk.
14.Explain about events in Tk and its usage.
15.Discuss about security issues.
16.What is an event? Explain event and its usage in Tk with examples.
17.How to build and work with list data structure in TCL? Give an example code.
Unit 5:
1. Explain in detail about operators in python.
2. How to build a small web application using Python? Explain.
3. Explain about control statements in python.
4. Write about filter( ) and format( ) built-in functions in python.
5. Explain about modules in python with an example.
6. Discuss in detail about built in functions of python and list at least ten functions.
7. Explain about data types in python.
8. Write a python program to find given number is prime or not.
9. Discuss about built-in-functions, Methods and Modules used in python.
10.Write a detailed note on web application framework using Python.
11.Discuss in detail about exception handling in python.
12.Write a recursive program to print factorial of a number using python.
13.Explain about web application framework.
14.Write a python program to check whether given number is palindrome or not
15.Explain the exception handling mechanism in python.
16.Discuss the steps in building efficient Python Web Systems.

Unit 1
Explain about scripting language.

What are the characteristics of scripting languages? Discuss.

Explain about List and Hashes in PERL.

Explain last and next control statements in PERL.

Discuss in brief about control structures of PERL.

Write a program to check whether given number is Armstrong number or not.


Explain about web scripting.

Write a program to find greatest of 3 numbers using PERL.

With examples, discuss about the control structures and subroutines used in Perl.

How to make use of file system and packages in Perl? Illustrate with examples.

Explain about operators in PERL.

Explain in detail about string functions in PERL.

Explain about PERL Subroutines.

Write a program to print prime numbers using PERL.

Describe how to use and implement packages and modules in a PERL script.

Give a brief account on various security issues in PERL scripting language.

--------------------------------------------------------------------------------------------------------------------------------

Unit 2
Explain about function libraries in PHP.

How to embed PHP code in a web page? Explain.


Explain about features of PHP.

Write down the differences between PHP and Java Script.

Explain in detail about outputting the data to the browser with an example

Write a program to explain about Merging, Slicing, Splicing, and Dissecting Arrays.

Explain about embedding PHP code in your web pages with an example.

Discuss in brief about string interpolation.

What are the features of PHP? Write about the data types, variables and constants used in PHP.

How to create functions in PHP? Explain about function libraries in PHP.

Explain about control structures of PHP.

Explain about regular expressions with an example.

Explain about functions in PHP and give an example.

Explain about function libraries in PHP.

Give the syntax of various control structures used in PHP coding and explain them briefly.
Explain the purpose of superglobal array in PHP.

What’s the difference between htmlentities( ) and htmlspecialchars( )?

--------------------------------------------------------------------------------------------------------------------------------
Explain about IP Based authentication.

Demonstrate the use of Mcrypt package.

Explain about File Based authentication.

How to execute a PHP script using command line arguments? Explain with an example script.

Explain about PHP Authentication and Methodologies.

Explain about Localizing Dates, Numbers, and Times in PHP.

Write a program for uploading files with PHP.

Explain about translating websites with Gettext.

Write about file uploading directives and functions in PHP with examples.

Explain the process of sending an email using PHP.

How to create localization repository in PHP? Explain.


Explain sending email using PHP with a program.

Explain about Mcrypt package in PHP.

Explain about PHP encryption functions.

Write a program to explain about PHP and Web Forms with an example.

Describe Database Based, IP Based authentication methodologies in detail.

Explain various PHP functions used in updating websites scripts.

--------------------------------------------------------------------------------------------------------------------------------

Explain about procedures.


Procedures are nothing but code blocks with series of commands that provide a specific reusable
functionality. It is used to avoid same code being repeated in multiple locations. Procedures are
equivalent to the functions used in many programming languages and are made available in Tcl with
the help of proc command.
The syntax of creating a simple procedure is shown below −
proc procedureName {arguments} {
body
}
A simple example for procedure is given below −
#!/usr/bin/tclsh

proc helloWorld {} {
puts "Hello, World!"
}
helloWorld
When the above code is executed, it produces the following result −
Hello, World!
Procedures with Multiple Arguments
An example for procedure with arguments is shown below −
#!/usr/bin/tclsh

proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
When the above code is executed, it produces the following result −
40

Procedures with Variable Arguments


An example for procedure with arguments is shown below −
#!/usr/bin/tclsh

proc avg {numbers} {


set sum 0
foreach number $numbers {
set sum [expr $sum + $number]
}
set average [expr $sum/[llength $numbers]]
return $average
}
puts [avg {70 80 50 60}]
puts [avg {70 80 50 }]
When the above code is executed, it produces the following result −
65
66

Procedures with Default Arguments


Default arguments are used to provide default values that can be used if no value is provided. An
example for procedure with default arguments, which is sometimes referred as implicit arguments is
shown below −
#!/usr/bin/tclsh

proc add {a {b 100} } {


return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]
When the above code is executed, it produces the following result −
40
110

Recursive Procedures
An example for recursive procedures is shown below −
#!/usr/bin/tclsh

proc factorial {number} {


if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number - 1]]]

}
puts [factorial 3]
puts [factorial 5]
When the above code is executed, it produces the following result −
6
120

TCL script to demonstrate procedures


In this article, we will know how to use procedures in TCL. Procedures are just like functions we use in
any other programming language such as C, Java, Python, etc. Just like functions, procedures take
arguments and return some value. Let’s go through a simple program that calls procedures to print
add, subtract, multiply, divide, and modulo two numbers step-by-step.
Pre-requisite –
If you want to know the basics of TCL script then kindly go through this
article https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/.
Overview:
We will try to understand the syntax of a procedure in TCL by exploring the code block-by-block.
Furthermore, we will also look at the syntax for procedures in C programming to compare with and
understand better.
TCL script to demonstrate procedures :
Let’s discuss the following steps as follows.
Step-1 :
Let’s first define our procedures. We do that using the proc keyword. The procedures addnumbers
{}, sub numbers {}, mulnumbers {}, divnumbers {} and modnumbers {} are created to
compute the sum, difference, product, division, and modulo of two numbers respectively.
TCL script -

//Addition
proc addnumbers { a b } {
return [expr $a + $b]
}

//Subtraction
proc subnumbers { a b } {
return [expr $a - $b]
}

//Multiplication
proc mulnumbers { a b } {
return [expr $a * $b]
}

//Division
proc divnumbers { a b } {
return [expr $a / $b]
}

//Modulus
proc modnumbers { a b } {
return [expr $a % $b]
}
As shown above, the syntax can be generalized as follows.
proc procedurename {arguments} {
#body of the procedure
}
Note –
The syntax has to be exactly as shown above. If you neglect the spaces or type the opening curly
brace in a new line, the result will be an error. The same syntax is followed by all conditional
statements in TCL. Also note that procedures like functions, may or may not have a return type. Now
let’s look at how the above set of functions would look like in C programming.
 C

//Addition
int addnumbers(int a, int b) {
return a + b; }

//Subtraction
int subnumbers(int a, int b) {
return a - b; }

//Multiplication
int mulnumbers(int a, int b) {
return a * b; }
//Division
float divnumbers(float a, float b) {
return a / b; }

//Modulus
int modnumbers(int a, int b) {
return a % b; }

Step-2 :
The next step is to read two numbers a and b using gets.
puts "Enter the first number"
gets stdin a
puts "Enter the second number"
gets stdin b
Step-3 :
The final step is to print all the required values. Here, we will also look at the syntax in C
programming to understand how we call a function in TCL.
puts "The sum of two numbers is [addnumbers $a $b]"
puts "The difference between the two numbers is [subnumbers $a $b]"
puts "The product of the two numbers is [subnumbers $a $b]"
puts "The division of the two numbers is [divnumbers $a $b]"
puts "The modulo of the two numbers is [modnumbers $a $b]"
So, we saw above the syntax to call a procedure would look like the following.
[procedurename $argument1 $argument2 .....]
Now let’s compare with the syntax in C programming to call a function.
functionname(argument1,argument2,.....)
Step-4 :
Finally, we view the entire code with the output as follows.
Code –
//Addition
proc addnumbers {a b} {
return [expr $a+$b]
}

//Subtraction
proc subnumbers {a b} {
return [expr $a-$b]
}

//Multiplication
proc mulnumbers {a b} {
return [expr $a*$b]
}

//Division
proc divnumbers {a b} {
return [expr $a/$b]
}

//Modulus
proc modnumbers {a b} {
return [expr $a%$b]
}

//Input-1
puts "Enter the first number"
gets stdin a

//Input-2
puts "Enter the second number"
gets stdin b

//called procedures
puts "The sum of two numbers is [addnumbers $a $b]"
puts "The difference between the two numbers is [subnumbers $a $b]"
puts "The product of the two numbers is [subnumbers $a $b]"
puts "The division of the two numbers is [divnumbers $a $b]"
puts "The modulo of the two numbers is [modnumbers $a $b]"
Output :

Output for a=123 and b=486

Write about the patterns available in TCL.


Tcl - Regular Expressions
The "regexp" command is used to match a regular expression in Tcl. A regular expression is a
sequence of characters that contains a search pattern. It consists of multiple rules and the following
table explains these rules and corresponding use.
Sr.No Rule & Description
.
1 x
Exact match.
2 [a-z]
Any lowercase letter from a-z.
3 .
Any character.
4 ^
Beginning string should match.
5 $
Ending string should match.
6 \^
Backlash sequence to match special character ^.Similarly you can use for other characters.
7 ()
Add the above sequences inside parenthesis to make a regular expression.
8 x*
Should match 0 or more occurrences of the preceding x.
9 x+
Should match 1 or more occurrences of the preceding x.
10 [a-z]?
Should match 0 or 1 occurrence of the preceding x.
11 {digit}
Matches exactly digit occurrences of previous regex expression. Digit that contains 0-9.
12 {digit,}
Matches 3 or more digit occurrences of previous regex expression. Digit that contains 0-9.
13 {digit1,digit2}
Occurrences matches the range between digit1 and digit2 occurrences of previous regex
expression.
Syntax
The syntax for regex is given below −
regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn
Here, regex is the command. We will see about optional switches later. Patterns are the rules as
mentioned earlier. Search string is the actual string on which the regex is performed. Full match is any
variable to hold the result of matched regex result. Submatch1 to SubMatchn are optional subMatch
variable that holds the result of sub match patterns.
Let's look at some simple examples before diving into complex ones. A simple example for a string
with any alphabets. When any other character is encountered the regex, search will be stopped and
returned.
#!/usr/bin/tclsh

regexp {([A-Za-z]*)} "Tcl Tutorial" a b


puts "Full Match: $a"
puts "Sub Match1: $b"
When the above code is executed, it produces the following result −
Full Match: Tcl
Sub Match1: Tcl

Multiple Patterns
The following example shows how to search for multiple patterns. This is example pattern for any
alphabets followed by any character followed by any alphabets.
#!/usr/bin/tclsh

regexp {([A-Za-z]*).([A-Za-z]*)} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"
When the above code is executed, it produces the following result −
Full Match: Tcl Tutorial
Sub Match1: Tcl
Sub Match2: Tutorial
A modified version of the above code to show that a sub pattern can contain multiple patterns is
shown below −
#!/usr/bin/tclsh

regexp {([A-Za-z]*.([A-Za-z]*))} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"
When the above code is executed, it produces the following result −
Full Match: Tcl Tutorial
Sub Match1: Tcl Tutorial
Sub Match2: Tutorial

Switches for Regex Command


The list of switches available in Tcl are,
 nocase − Used to ignore case.
 indices − Store location of matched sub patterns instead of matched characters.
 line − New line sensitive matching. Ignores the characters after newline.
 start index − Sets the offset of start of search pattern.
 Marks the end of switches
In the above examples, I have deliberately used [A-Z, a-z] for all alphabets, you can easily use -
nocase instead of as shown below −
#!/usr/bin/tclsh

regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"
When the above code is executed, it produces the following result −
Full Match: Tcl Tutorial
Sub Match1: Tcl Tutorial
Sub Match2: Tutorial
Another example using switches is shown below −
#!/usr/bin/tclsh

regexp -nocase -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b


puts "Full Match: $a"
puts "Sub Match1: $b"
regexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b
puts "Full Match: $a"
puts "Sub Match1: $b"
When the above code is executed, it produces the following result −
Full Match: Tcl
Sub Match1: Tcl
Full Match: Tutorial
Sub Match1: Tutorial

Explain about control flow in TCL.


Tcl - If else Statement

Discuss briefly about namespaces in TCL.


Tcl - Namespaces

Explain about operators in TCL.


Tcl - Operators

Explain about Nuts and Bolts internet programming.

Explain about trapping errors in TCL.


Tcl - Error Handling

Discuss in detail about Visual Tool Kits in Tk.

Explain the fundamental concepts of TK with an example.


Write about the data structures used in TCL.

Discuss about events, binding and its usage in TK with examples.

Explain about event driven programs with an example.

Explain about binding in Tk.

Explain about events in Tk and its usage.

Discuss about security issues.

What is an event? Explain event and its usage in Tk


with examples.
Tk - Events

How to build and work with list data structure in


TCL? Give an example code.
Tcl - Lists

--------------------------------------------------------------------------------------------------------------------------------

Explain in detail about operators in python.


Python Operators
In Python programming, Operators in general are used to perform operations on values and variables.
These are standard symbols used for logical and arithmetic operations. In this article, we will look into
different types of Python operators.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an
integer. To obtain an integer result in Python 3.x floored (// integer) is used.
Operato Description Syntax
r
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by x%y
the second
** Power: Returns first raised to power second x ** y
Example of Arithmetic Operators in Python
Division Operators
In Python programming language Division Operators allow you to divide two numbers and return a
quotient, i.e., the first number or number at the left is divided by the second number or number at the
right and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:
Example: The code performs division operations and prints the results. It demonstrates that both
integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’, and ‘-
10/2’ results in ‘-5.0’.
[GFGTABS] Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
[/GFGTABS]
Output:
1.0
5.0
-5.0
10.0

Integer division( Floor division)


The quotient returned by this operator is dependent on the argument being passed. If any of the
numbers is float, it returns output in float. It is also known as Floor division because, if any number is
negative, then the output will be floored. For example:
Example: The code demonstrates integer (floor) division operations using the // in Python
operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’,
and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less than or equal to the
division result.
[GFGTABS] Pythons
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
[/GFGTABS]
Output:
3
-3
2.0
-3.0

Precedence of Arithmetic Operators in Python


The precedence of Arithmetic Operators in Python is as follows:
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the same precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same precedence)
6. S – Subtraction
The modulus of Python operators helps us extract the last digit/s of a number. For example:
 x % 10 -> yields the last digit
 x % 100 -> yield last two digits
Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power
Here is an example showing how different Arithmetic Operators in Python work:
Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’. It adds (‘+’),
subtracts (‘-‘), multiplies (‘*’), computes the remainder (‘%’), and raises a to the power of ‘b (**)’.
The results of these operations are printed.
[GFGTABS] Python
a=9
b=4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
[/GFGTABS]
Output:
13
5
36
1
6561

Note: Refer to Differences between / and // for some interesting facts about these two Python
operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or x >= y
equal to the right
<= Less than or equal to True if the left operand is less than or equal to x <= y
the right
= is an assignment operator and == comparison operator.
Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than the arithmetic operators. All the
operators within comparison operators have the same precedence order.
Example of Comparison Operators in Python
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators
and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or
equal to, and less than or equal to ‘b’.
[GFGTABS] Python
a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
[/GFGTABS]
Output
False
True
False
True
False
True

Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used
to combine conditional statements.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x
Precedence of Logical Operators in Python
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python
The following code shows how to implement Logical Operators in Python:
Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are
true (‘and’), if at least one of them is true (‘or’), and negates the value of ‘a’ using ‘not’. The results
are printed accordingly.
[GFGTABS] Python
a = True
b = False
print(a and b)
print(a or b)
print(not a)
[/GFGTABS]
Output
False
True
False

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on
binary numbers.
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in Python is as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Bitwise Operators in Python
Here is an example showing how Bitwise Operators in Python work:
Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’. It
performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift
(<<) operations and prints the results. These operations manipulate the binary representations of the
numbers.
[GFGTABS] Python
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
[/GFGTABS]
Output
0
14
-11
14
2
40

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.
Operat Description Syntax
or
= Assign the value of the right side of the expression to the left side x=y+z
operand
+= Add AND: Add right-side operand with left-side operand and then a+=b a=a+b
assign to left operand
-= Subtract AND: Subtract right operand from left operand and then a-=b a=a-b
assign to left operand
*= Multiply AND: Multiply right operand with left operand and then a*=b a=a*b
assign to left operand
/= Divide AND: Divide left operand with right operand and then assign a/=b a=a/b
to left operand
%= Modulus AND: Takes modulus using left and right operands and a%=b a=a%b
assign the result to left operand
//= Divide(floor) AND: Divide left operand with right operand and then a//=b a=a//b
assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value using a**=b a=a**b
operands and assign value to left operand
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left a>>=b
operand a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left a <<= b a= a
operand << b
Assignment Operators in Python
Let’s see an example of Assignment Operators in Python.
Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of
operations: addition, subtraction, multiplication, and a left shift operation on ‘b’. The results of each
operation are printed, showing the impact of these operations on the value of ‘b’.
[GFGTABS] Python
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
[/GFGTABS]
Output
10
20
10
100
102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

Example Identity Operators in Python


Let’s see an example of Identity Operators in Python.
Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the
same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object
as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).
[GFGTABS] Python
a = 10
b = 20
c=a

print(a is not b)
print(a is c)
[/GFGTABS]
Output
True
True

Membership Operators in Python


In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

Examples of Membership Operators in Python


The following code shows how to implement Membership Operators in Python:
Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not
each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed
messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.
[GFGTABS] Python
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
[/GFGTABS]
Output
x is NOT present in given list
y is present in given list

Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions are operators that evaluate
something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax : [on_true] if [expression] else [on_false]
Examples of Ternary Operator in Python
The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional
assignment to determine the smaller of the two values and assigns it to the variable ‘min’. Finally, it
prints the value of ‘min’, which is 10 in this case.
[GFGTABS] Python
a, b = 10, 20
min = a if a < b else b

print(min)
[/GFGTABS]
Output:
10

Precedence and Associativity of Operators in Python


In Python, Operator precedence and associativity determine the priorities of the operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different precedence to determine
which operation to perform first.
Let’s see an example of how Operator Precedence in Python works:
Example: The code first calculates and prints the value of the expression 10 + 20 * 30, which is
610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the
name is “Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”
[GFGTABS] Python
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")
[/GFGTABS]
Output
610
Hello! Welcome.

Operator Associativity in Python


If an expression contains two or more operators with the same precedence then Operator
Associativity is used to determine. It can either be Left to Right or from Right to Left.
The following code shows how Operator Associativity in Python works:
Example: The code showcases various mathematical operations. It calculates and prints the results
of division and multiplication, addition and subtraction, subtraction within parentheses, and
exponentiation. The code illustrates different mathematical calculations and their outcomes.
[GFGTABS] Python
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)
[/GFGTABS]
Output
100.0
6
0
512
How to build a small web application using Python?
Explain.
Creating a Web Application with Python: A Comprehensive Guide for Beginners
Python, a versatile and beginner-friendly programming language, is widely used for web development
due to its simplicity, readability, and robust ecosystem. In this article, we will take you on a journey
through the process of creating a web application using Python, step by step. We will cover everything
from setting up your development environment to deploying your application. So, let’s dive in!
Choosing the Right Framework:
When it comes to web development with Python, you have several options for frameworks. Two
popular choices are Django and Flask. Django is a full-featured framework that provides everything
you need to build complex web applications, while Flask is a lightweight framework that offers more
flexibility. For the purpose of this article, we will focus on Flask, as it is more suitable for beginners.
Setting Up Your Development Environment:
Before you start building your web application, you need to set up your development environment.
First, make sure Python is installed on your machine. You can download the latest version from the
official Python website. Additionally, it’s recommended to use a virtual environment to isolate your
project dependencies. You can create a virtual environment using the following command in your
terminal:
$ python3 -m venv myen
Installing Flask:
To use Flask, you need to install it in your virtual environment. Activate your virtual environment and
run the following command:
$ pip install flask
Creating a Flask Application:
Now that Flask is installed, let’s create a simple web application. Create a new Python file, such as
`app.py`, and open it in your favorite text editor. Import the Flask module and create an instance of
the Flask class:

from flask import Flask


app = Flask(__name__)
Defining Routes and View:
In Flask, routes define the URLs that your application will respond to, and views are the functions that
handle those requests. Let’s create a simple route that displays “Hello, World!” when the root URL is
accessed:

@app.route(‘/’)
def hello():
return ‘Hello, World!’
Running the Application:
To run your Flask application, you need to set the `FLASK_APP` environment variable to the name of
your Python file (`app.py` in this case). In your terminal, run the following command:
$ export FLASK_APP=app.py
$ flask run
You should see an output similar to:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open your web browser and navigate to `http://127.0.0.1:5000/`, and you should see the “Hello,
World!” message.
Building Templates:
In real-world web applications, you’ll often need to render dynamic HTML pages. Flask provides a
powerful templating engine called Jinja2 for this purpose. Create a new folder called `templates` in
your project directory, and inside that folder, create a new HTML file called `index.html`. In
`index.html`, add the following content:
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
Rendering Templates:
To render the `index.html` template, modify the `hello` view function in your `app.py` file as follows:

from flask import render_template

@app.route('/')
def hello():
return render_template('index.html', message='Hello, World!')
Form Handling:
Web applications often require user input through forms. Flask provides convenient tools for handling
form submissions. Let’s create a simple form that takes a name as input and displays a personalized
greeting. First, modify the `index.html` template to include a form:

<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>{{ message }}</h1>
<form action=”/greet” method=”POST”>
<input type=”text” name=”name” placeholder=”Enter your name” />
<button type=”submit”>Submit</button>
</form>
</body>
</html>
Handling Form Submissions:
Create a new route in your `app.py` file to handle the form submission:
from flask import request

@app.route(‘/greet’, methods=[‘POST’])
def greet():
name = request.form[‘name’]
return f’Hello, {name}!’
Adding Database Support:
Many web applications require persistent data storage. Flask integrates well with various database
systems. One popular choice is SQLite, a lightweight and serverless database. To use SQLite with
Flask, install the `sqlite3` package:
$ pip install sqlite
Creating Database Models:
Define your database models using Flask’s built-in ORM, SQLAlchemy. Create a new file called
`models.py` and import the necessary modules:

from flask_sqlalchemy import SQLAlchemy


from app import app

db = SQLAlchemy(app)
Create a `User` model that represents a user in your application
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)

def __repr__(self):
return f'<User {self.username}>'
Database Migration:
To create the necessary database tables based on your models, use Flask-Migrate, an extension that
integrates Flask with Alembic, a database migration framework. Install Flask-Migrate using pip:

$ pip install flask-migrate


Initialize Flask-Migrate by running the following commands:

$ flask db init
$ flask db migrate -m “Initial migration”
$ flask db upgrade
Deploying Your Application:
Once your web application is ready, you’ll want to deploy it to a production server. Popular hosting
platforms like Heroku and PythonAnywhere make it easy to deploy Flask applications. Simply create
an account, follow the provided instructions, and your application will be up and running in no time.

Explain about control statements in python.


Control Statements in Python
Loops are employed in Python to iterate over a section of code continually. Control statements are
designed to serve the purpose of modifying a loop's execution from its default behaviour. Based on a
condition, control statements are applied to alter how the loop executes. In this tutorial, we are
covering every type of control statement that exists in Python.
Control Statements in Python
if Statements
The if statement is arguably the most used statement to control loops. For instance:
Code
# Python program to show how if statements control loops
n=5
for i in range(n):
if i < 2:
i += 1
if i > 2:
i -= 2
print(i)
Output:
1
2
2
1
2

Break Statements
In Python, the break statement is employed to end or remove the control from the loop that contains
the statement. It is used to end nested loops (a loop inside another loop), which are shared with both
types of Python loops. The inner loop is completed, and control is transferred to the following
statement of the outside loop.
Code
1. # Python program to show how to control the flow of loops with the break statement
2.
3. Details = [[19, 'Itika', 'Jaipur'], [16, 'Aman', 'Bihar']]
4. for candidate in Details:
5. age = candidate[0]
6. if age <= 18:
7. break
8. print (f"{candidate[1]} of state {candidate[2]} is eligible to vote")
Output:
Itika of state Jaipur is eligible to vote
In the above code, if a candidate's age is less than or equal to 18, the interpreter won't generate the
statement of eligibility. Otherwise, the interpreter will print a message mentioning that the candidate
is eligible to vote in the console.

Continue Statements
When a Python interpreter sees a continue statement, it skips the present iteration's execution if the
condition is satisfied. If the condition is not satisfied, it allows the implementation of the current
iteration. It is employed to keep the program running even when it meets a break while being
executed.
Code
# Python program to show how to control the flow of a loop using a continue statement
# Printing only the letters of the string
for l in 'I am a coder':
if l == ' ':
continue
print ('Letter: ', l)
Output:
Letter: I
Letter: a
Letter: m
Letter: a
Letter: c
Letter: o
Letter: d
Letter: e
Letter: r
In this code, when the if-statement encounters a space, the loop will continue to the following letter
without printing the space.

Pass Statements
If the condition is met, the pass statement, or a null operator, is used by the coder to leave it as it is.
Python's pass control statement changes nothing and moves on to the following iteration without
stopping the execution or skipping any steps after completing the current iteration.
A coder can put the pass statement to prevent the interpreter from throwing an error when a loop or a
code block is left empty.
Code
# Python program to show how to create empty code blocks using a pass statement
for l in 'Python':
if l == 't':
pass
print('Letter: ', l)
Output:
Letter: P
Letter: y
Letter: t
Letter: h
Letter: o
Letter: n
Even if the condition was satisfied in the code above, as we can see, the pass statement had no
effect, and execution went on to the subsequent iteration.

else in Loop
The else statement is used with the if clause, as we have previously learned. Python supports
combining the else keyword with the for and the while loop. After the code block of the loop, the else
block is displayed. After completing all the iterations, the interpreter will carry out the code in the else
code block. Only when the else block has been run does the program break from the loop.
Code
# Python program to show how to use else statements with a loop
for n in range(5):

print(f"Current iteration: {n+1}")


else:
print("This is the else block")
print("Outside the loop")
Output:
Advertisement
Current iteration: 1
Current iteration: 2
Current iteration: 3
Current iteration: 4
Current iteration: 5
This is the else block
Outside the loop

match Statements
A match statement compares the value of an expression to a series of patterns. These patterns are
presented as some case blocks. Contrary to appearances, this is more akin to pattern checking in
other languages like Rust than to switching clauses in C, Java (or any other coding languages). It can
also pull components (sequential elements or object characteristics) from the values into variables,
and only the first matching pattern is executed.
The most straightforward form contrasts a subject value with one or more regular expressions:
Code
# Python program to show how match control statement is used
def error(error_status):
match error_status:
case 400:
return "Error 400: Bad request"
case 404:
return "Error 404: Link Not found"
case 418:
return "Error 418: Server Is Down"
case _:
return "Check Your Internet Connection"
print(error(400))
print(error(404))
Output:
Error 400: Bad request
Error 404: Link Not found

Write about filter( ) and format( ) built-in functions in


python.
filter() in python
The filter() method filters the given sequence with the help of a function that tests each element in
the sequence to be true or not. Let’s see a simple example of filter() function in python:
Example Usage of filter()
# Function to check if a number is even
def even(n):
return n % 2 == 0
a = [1, 2, 3, 4, 5, 6]
b = filter(even, a)
# Convert filter object to a list
print(list(b))

Output
[2, 4, 6]
Explanation:
 Function: even function checks if a number is divisible by 2.
 Filter: The filter() applies this function to each item in numbers.
 Result: A new iterable containing only even numbers is returned.
Let’s explore filter() in detail:
Python filter() Syntax
The filter() method in Python has the following syntax:
Syntax: filter(function, sequence)
 function: A function that defines the condition to filter the elements. This function should
return True for items you want to keep and False for those you want to exclude.
 iterable: The iterable you want to filter (e.g., list, tuple, set).
The result is a filter object, which can be converted into a list, tuple or another iterable type.
Let us see a few examples of the filter() function in Python.
Using filter() with lambda
For concise conditions, we can use a lambda function instead of defining a named function.

a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)
print(list(b))

Output
[2, 4, 6]
Here, the lambda function replaces even and directly defines the condition x % 2 == 0 inline.
Combining filter() with Other Functions
We can combine filter() with other Python functions like map() or use it in a pipeline to process data
efficiently.
Example: Filtering and Transforming Data

a = [1, 2, 3, 4, 5, 6]
# First, filter even numbers
b = filter(lambda x: x % 2 == 0, a)
# Then, double the filtered numbers
c = map(lambda x: x * 2, b)
print(list(c))
Output
[4, 8, 12]
Explanation:
 The filter() function extracts even numbers from numbers.
 The map() function doubles each filtered number.
 The combination simplifies complex data pipelines.

Explain about modules in python with an example.


Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are
many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own simple module,
Import Python modules, From statements in Python, we can use the alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also makes the
code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file with .py extension. Let’s
understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and another subtract.

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

Import module in Python


We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is present
in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a module.
For example, to import the module calc.py, we need to put the following command at the top of the
script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a module without importing the
module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the names from a module to a
current namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from
the module, it is not recommended to use *, else do so.

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it will check
for the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python
interpreter searches for the module in the following manner –
 First, it searches for the module in the current directory.
 If the module isn’t found in the current directory, Python then searches each directory in the
shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of
directories.
 If that also fails python checks the installation-dependent list of directories configured at the
time Python is installed.
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the
interpreter will search for the required module.

# importing sys module


import sys

# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-
dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’,
‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))

Output
4.0
720

Discuss in detail about built in functions of python and


list at least ten functions.
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
# importing built-in module math
import math

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)
# 2 radians = 114.59 degrees

print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))
# print random floating point number between 0 and 1
print(random.random())

# random number between 0 and 100


print(random.random() * 100)

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing


# a random element from a set such as a list
print(random.choice(List))

# importing built in module datetime


import datetime
from datetime import date
import time

# Returns the number of seconds since the


# Unix Epoch, January 1st 1970
print(time.time())

# Converts a number of seconds to a date object


print(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87

Explain about data types in python.


Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in
Python programming, Python data types are classes and variables are instances (objects) of these
classes. The following are the standard or built-in data types in Python:
 Numeric – int, float, complex
 Sequence Type – string, list, tuple
 Mapping Type – dict
 Boolean – bool
 Set Type – set, frozenset
 Binary Types – bytes, bytearray, memoryview

DataTypes
This code assigns variable ‘x’ different values of various Python data types. It
covers string , integer , float , complex , list , tuple , range , dictionary , set , frozenset , bool
ean , bytes , bytearray , memoryview , and the special value ‘None’ successively. Each
assignment replaces the previous value, making ‘x’ take on the data type and value of the most
recent assignment.

x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None
If you’re eager to deepen your understanding of Python and how it handles data, our Python
Programming Self Paced Course is the perfect place to start. This course covers everything from
the fundamentals to more advanced topics, giving you the hands-on experience needed to
confidently work with Python in real-world projects.
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can
be an integer, a floating number, or even a complex number. These values are defined as Python
int , Python float , and Python complex classes in Python .
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example – 2+3j
Example: This code demonstrates how to determine the data type of variables in Python
using type() function. It prints the data types of three variables : a (integer) , b (float) , and c
(complex). The output shows the respective data type Python for each variable.

a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Output
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence data types of Python:
 Python String
 Python List
 Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote, or triple-quote. In Python, there is no character
data type Python, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even triple quotes.
Example: This Python code showcases various string creation methods. It uses single quotes, double
quotes, and triple quotes to create strings with different content and includes a multiline string. The
code also demonstrates printing the strings and checking their data types.
s1 = 'Welcome to the Geeks World'
print("String with Single Quotes: ", s1)
# check data type
print(type(s1))
s2 = "I'm a Geek"
print("String with Double Quotes: ", s2)
s3 = '''I'm a Geek and I live in a world of "Geeks"'''
print("String with Triple Quotes: ", s3)
s4 = '''Geeks
For
Life'''
print("Multiline String: ", s4)

Output
String with Single Quotes: Welcome to the Geeks World
<class 'str'>
String with Double Quotes: I'm a Geek
String with Triple Quotes: I'm a Geek and I live in a world of "Geeks"
Multiline String: G...
Accessing elements of String
In Python programming , individual characters of a String can be accessed by using the method of
Indexing. Negative Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
Example: This Python code demonstrates how to work with a string named ‘ String1′ . It initializes
the string with “GeeksForGeeks” and prints it. It then showcases how to access the first character
( “G” ) using an index of 0 and the last character ( “s” ) using a negative index of -1.
s = "GeeksForGeeks"
# accessing first character of string
print(s[0])
# accessing last character of string
print(s[-1])

Output
G
s
Note – To know more about strings, refer to Python String .
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
Example: This Python code demonstrates list creation and manipulation. It starts with an empty list
and prints it. It creates a list containing a single string element and prints it. It creates a list with
multiple string elements and prints selected elements from the list.
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]

Python Access List Items


In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-
last item, etc.

a = ["Geeks", "For", "Geeks"]


print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Note – To know more about Lists, refer to Python List.


Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’
with or without the use of parentheses for grouping the data sequence. Tuples can contain any
number of elements and of any datatype (like strings, integers, lists, etc.). Note: Tuples can also be
created with a single element, but it is a bit tricky. Having one element in the parentheses is not
sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example: This Python code demonstrates different methods of creating and working with tuples. It
starts with an empty tuple and prints it. It creates a tuple containing string elements and prints it. It
converts a list into a tuple and prints the result. It creates a tuple from a string using
the tuple() function. It forms a tuple with nested tuples and displays the result.
# initiate empty tuple
t1 = ()
t2 = ('Geeks', 'For')
print("\nTuple with the use of String: ", t2)

Output
Tuple with the use of String: ('Geeks', 'For')

Note – The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to access an
item in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing.
The code creates a tuple named ‘ tuple1′ with five elements: 1, 2, 3, 4, and 5 . Then it prints the
first, last, and third last elements of the tuple using indexing.
t1 = tuple([1, 2, 3, 4, 5])
print("First element of tuple")
print(t1[0])
print("\nLast element of tuple")
print(t1[-1])
print("\nThird last element of tuple")
print(t1[-3])

Output
First element of tuple
Last element of tuple
Third last element of tuple

Note – To know more about tuples, refer to Python Tuples .


3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class
bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
Example: The first two lines will print the type of the boolean values True and False, which is <class
‘bool’>. The third line will cause an error, because true is not a valid keyword in Python. Python is
case-sensitive, which means it distinguishes between uppercase and lowercase letters. You need to
capitalize the first letter of true to make it a boolean value.

print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and has
no duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values

# initializing empty set


s1 = set()
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
s2 = set(["Geeks", "For", "Geeks"])

print("Set with the use of List: ", s2)

Output
Set with the use of String: {'e', 'G', 's', 'F', 'o', 'r', 'k'}
Set with the use of List: {'For', 'Geeks'}

Access Set Items


Set items cannot be accessed by referring to an index, since sets are unordered the items have no
index. But you can loop through the set items using a for loop, or ask if a specified value is present in
a set, by using the in the keyword.
Example: This Python code creates a set named set1 with the
values “Geeks” , “For” and “Geeks” . The code then prints the initial set, the elements of the set
in a loop, and checks if the value “Geeks” is in the set using the ‘ in’ operator

set1 = set(["Geeks", "For", "Geeks"])


print("\nInitial set")
print(set1)
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
print("Geeks" in set1)

Output
Initial set
{'Geeks', 'For'}

Elements of set:
Geeks For True
Note – To know more about sets, refer to Python Sets .
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like a map,
unlike other Python Data Types that hold only a single value as an element, a Dictionary holds a key:
value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary in Python
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas
keys can’t be repeated and must be immutable. The dictionary can also be created by the built-in
function dict(). An empty dictionary can be created by just placing it in curly braces{}. Note –
Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
Example: This code creates and prints a variety of dictionaries. The first dictionary is empty. The
second dictionary has integer keys and string values. The third dictionary has mixed keys, with one
string key and one integer key. The fourth dictionary is created using the dict() function, and the fifth
dictionary is created using the [(key, value)] syntax
# initialize empty dictionary
d = {}
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
# creating dictionary using dict() constructor
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Accessing Key-value in Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. There is also a method called get() that will also help in accessing the element from a
dictionary.
Example: The code in Python is used to access elements in a dictionary. Here’s what it does, It
creates a dictionary Dict with keys and values as { 1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’} . It prints
the value of the element with the key ‘name’ , which is ‘For’ . It prints the value of the element with
the key 3, which is ‘Geeks’ .
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Accessing an element using key
print(d['name'])
# Accessing a element using get
print(d.get(3))

Output
For
Geeks
Write a python program to find given number is prime
or not.
Python Program to Check Prime Number
Given a positive integer N, the task is to write a Python program to check if the number is Prime or
not in Python.
Example: Check Prime Number

num = 11
# Negative numbers, 0 and 1 are not primes
if num > 1:
# Iterate from 2 to n // 2
for i in range(2, (num//2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Output
11 is a prime number
Explanation: The idea to solve this problem is to iterate through all the numbers starting from 2 to
(N/2) using a for loop and for every number check if it divides N. If we find any number that divides,
we return false. If we did not find any number between 2 and N/2 which divides N then it means that
N is prime and we will return True.

Discuss about built-in-functions, Methods and Modules used in python.

Write a detailed note on web application framework using Python.

Discuss in detail about exception handling in python.


Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).
In this article, we will discuss how to handle exceptions in Python using try, except, and finally
statements with the help of proper examples.
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a
program due to which the program will stop the execution. On the other hand, exceptions are raised
when some internal events occur which change the normal flow of the program.
Different types of exceptions in python:

In Python, there are several built-in Python exceptions that can be raised when an error occurs during
the execution of a program. Here are some of the most common types of exceptions in Python:
 SyntaxError: This exception is raised when the interpreter encounters a syntax error in the
code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is not found in the
current scope.
 IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
 ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is not found on an
object, such as trying to access a non-existent attribute of a class instance.
 IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to divide a number by
zero.
 ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python. It’s
important to handle exceptions properly in your code using try-except blocks or other error-handling
techniques, in order to gracefully handle errors and prevent the program from crashing.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to
the termination of the program.
Example:
There is a syntax error in the code . The ‘if' statement should be followed by a colon (:), and
the ‘print' statement should be indented to be inside the ‘if' block.
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Output:

Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in
an error. This error does not stop the execution of the program, however, it changes the normal flow
of the program.
Example:
Here in this code as we are dividing the ‘marks’ by zero so a error will occur known
as ‘ZeroDivisionError’. ‘ZeroDivisionError’ occurs when we try to divide any number by 0.
marks = 10000
a = marks / 0
print(a)
Output:

In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the exception
hierarchy here.
Example:
1) TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type. Here’s an example:
Here a ‘TypeError’ is raised as both the datatypes are different which are being added.
x=5
y = "hello"
z=x+y
output:
Traceback (most recent call last):
File "7edfa469-9a3c-4e4d-98f3-5544e60bff4e.py", line 4, in <module>
z=x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try catch block to resolve it:
The code attempts to add an integer (‘x') and a string (‘y') together, which is not a valid operation,
and it will raise a ‘TypeError'. The code used a ‘try' and ‘except' block to catch this exception and
print an error message.
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")

Output
Error: cannot add an int and a str
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python. Statements that can
raise exceptions are wrapped inside the try block and the statements that handle the exception are
written inside except block.
Example: Here we are trying to access the array element whose index is out of bound and handle the
corresponding exception.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try statement
(second print statement in our case). The second print statement tries to access the fourth element of
the list which is not there and this throws an exception. This exception is then caught by the except
statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions.
Please note that at most one handler will be executed. For example, we can add IndexError in the
above code. The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
The code defines a function ‘fun(a)' that calculates b based on the input a. If a is less than 4, it
attempts a division by zero, causing a ‘ZeroDivisionError'. The code calls fun(3) and fun(5) inside a
try-except block. It handles the ZeroDivisionError for fun(3) and prints “ZeroDivisionError Occurred
and Handled.” The ‘NameError' block is not executed since there are no ‘NameError' exceptions
in the code.
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)

try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError occurs.
Try with Else Clause
In Python, you can also use the else clause on the try-except block which must be present after all the
except clauses. The code enters the else block only if the try clause does not raise an exception.
Try with else clause
The code defines a function AbyB(a, b) that calculates c as ((a+b) / (a-b)) and handles a
potential ZeroDivisionError. It prints the result if there’s no division by zero error. Calling AbyB(2.0,
3.0) calculates and prints -5.0, while calling AbyB(3.0, 3.0) attempts to divide by zero, resulting in
a ZeroDivisionError, which is caught and “a/b results in 0” is printed.
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks. The final
block always executes after the normal termination of the try block or after the try block terminates
due to some exception. The code within the finally block is always executed.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It catches
the exception and prints “Can’t divide by zero.” Regardless of the exception, the finally block is
executed and prints “This is always executed.”
try:
k = 5//0
print(k)

except ZeroDivisionError:
print("Can't divide by zero")

finally:
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument
in raise indicates the exception to be raised. This must be either an exception instance or an
exception class (a class that derives from Exception).
This code intentionally raises a NameError with the message “Hi there” using the raise statement
within a try block. Then, it catches the NameError exception, prints “An exception,” and re-raises
the same exception using raise. This demonstrates how exceptions can be raised and handled in
Python, allowing for custom error messages and further exception propagation.
try:
raise NameError("Hi there")
except NameError:
print ("An exception")
raise
The output of the above code will simply line printed as “An exception” but a Runtime error will also
occur in the last due to the raise statement in the last line. So, the output on your command line will
look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Advantages of Exception Handling:
 Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
 Simplified error handling: Exception handling allows you to separate error handling code
from the main program logic, making it easier to read and maintain your code.
 Cleaner code: With exception handling, you can avoid using complex conditional statements
to check for errors, leading to cleaner and more readable code.
 Easier debugging: When an exception is raised, the Python interpreter prints a traceback that
shows the exact location where the exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
 Performance overhead: Exception handling can be slower than using conditional statements
to check for errors, as the interpreter has to perform additional work to catch and handle the
exception.
 Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex error
handling logic.
 Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it’s important to handle
exceptions carefully and avoid exposing too much information about your program.

Write a recursive program to print factorial of a


number using python.
Python program to find the factorial of a number using recursion
A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than
or equal to n.
For example:
In this article, we are going to calculate the factorial of a number using recursion.
Examples:
Input: 5
Output: 120

Input: 6
Output: 720
Implementation:
If fact(5) is called, it will call fact(4), fact(3), fact(2) and fact(1). So it means keeps calling itself by
reducing value by one till it reaches 1.

# Python 3 program to find


# factorial of given number
def factorial(n):

# Checking the number


# is 1 or 0 then
# return 1
# other wise return
# factorial
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))

# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))

Output
number : 5
Factorial : 120
Time complexity: O(n)
Space complexity: O(n)

Explain about web application framework.

Write a python program to check whether given


number is palindrome or not
Python program to check if number is palindrome (one-liner)
In this article, we are given a number and we have to check whether the number is palindrome or not
in one-liner code. The output will be True if it’s a Palindrome number otherwise it would be False. Let’s
discuss how to find whether a number is palindrome or not in this article.
Input1: test_number = 12321
Output1: True
Input2: test_number = 1234
Output2: False
Palindrome Number Program in Python
Below are the following ways by which we can check if the number is palindrome or not in Python in
one line:
 Using math.log() + recursion + list comprehension
 Using str() + string slicing
 Using user input + string slicing
 Using all() and zip()
Palindrome Program using math.log() + recursion + list comprehension
In this example, we are using math.log(), recursion, and list comprehension to check if the number is
palindrome or not. Here, the logs function extracts the number of digits which is powered by 10 to get
the number for that iteration for comparison and then recursion test for palindrome.

import math

def rev(num):
return int(num != 0) and ((num % 10) * \
(10**int(math.log(num, 10))) + \
rev(num // 10))

test_number = 9669669
print ("The original number is : " + str(test_number))

res = test_number == rev(test_number)


print ("Is the number palindrome ? : " + str(res))

Output
The original number is : 9669669
Is the number palindrome ? : True

Time Complexity: O(n)


Auxiliary Space: O(n)
Python Check Palindrome Using str() + string slicing
In this example, we are converting the number into a string and then reversing it using the string
slicing method and comparing it whether the number is palindrome or not
# initializing number
test_number = 9669669
print ("The original number is : " + str(test_number))

# using str() + string slicing


# for checking a number is palindrome
res = str(test_number) == str(test_number)[::-1]
print ("Is the number palindrome ? : " + str(res))

Output
The original number is : 9669669
Is the number palindrome ? : True

Time Complexity: O(n)


Auxiliary Space: O(1)
Python Palindrome Number using user input + string slicing
In this example, we are taking user input in string and then check if the number is palindrome or not.

num = input("Enter a number")


if num == num[::-1]:
print("Yes its a palindrome")
else:
print("No, its not a palindrome")

Time Complexity: O(n)


Auxiliary Space: O(1)
Palindrome Program in Python Using all() and zip()
In this example, we are using a generator expression with the zip() function and the all() function to
check whether the number is palindrome or not. The generator expression (a == b for a, b in
zip(str(12321), reversed(str(12321)))) generates a generator that returns True if the elements a and b
are equal, and False otherwise. The all function returns True if all of the elements in the generator are
True, and False otherwise. In this case, it would return True because all of the elements in the
generator are True.

# Using the all function and a generator


# expression to check if a number is a palindrome
print(all(a == b for a, b in zip(str(12321),
reversed(str(12321)))))
# prints True
print(all(a == b for a, b in zip(str(1234),
reversed(str(1234)))))
# prints False

Output
True
False

Time complexity: O(n), where n is the length of the number.


Space complexity: O(1)

Explain the exception handling mechanism in python.

Discuss the steps in building efficient Python Web


Systems.
Building efficient Python web systems involves several key steps, including setting up the
development environment, selecting the appropriate tools and frameworks, optimizing performance,
ensuring scalability, and addressing security. Below is a detailed discussion of the steps involved in
building efficient Python web systems:
1. Requirements and Planning
Before starting the development process, it is important to define clear requirements and plan the
architecture of the system. This includes:
 Defining Functional Requirements: Understand the features and functionalities your web
application should provide. This might include user authentication, data processing,
integrations with third-party APIs, etc.
 Identifying Non-Functional Requirements: This includes performance, scalability, security,
and maintenance needs.
 Choosing the Right Architecture: Decide on the overall system architecture (e.g.,
monolithic, microservices, serverless, etc.) and ensure that it meets the scalability and
performance requirements.
2. Setting Up the Development Environment
To build an efficient Python web system, you must first set up the development environment:
 Install Python: Ensure that you have the latest stable version of Python installed. You can
manage multiple Python versions using tools like pyenv.
 Virtual Environments: Use virtual environments (e.g., venv or virtualenv) to isolate the
dependencies for each project. This helps in preventing version conflicts between different
projects.
 Install Dependencies: Set up the required libraries and frameworks for the project. Popular
Python web frameworks include:
o Django: A high-level web framework for building scalable web applications.
o Flask: A lightweight web framework for building microservices and simple web
applications.
o FastAPI: A modern framework for building APIs with fast performance, automatic
validation, and auto-generated documentation.
o Tornado: A scalable web framework for handling asynchronous I/O.
pip install django flask fastapi
3. Select the Appropriate Web Framework
Choosing the right Python web framework is essential for building an efficient web system. The
selection depends on your project needs:
 Django: Ideal for larger, more complex applications with built-in features such as an admin
panel, authentication, ORM, and scalability options.
 Flask: Perfect for lightweight applications or microservices where you need more control and
flexibility.
 FastAPI: Excellent choice for building high-performance APIs due to its async support and
automatic generation of OpenAPI documentation.
 Tornado: Use this when you need a high-performance, non-blocking, asynchronous web server.
4. Design the Database and Data Models
Efficient Python web systems require proper database design to ensure scalability and fast data
access:
 Choosing the Database: Choose a database based on the project needs. You can opt for:
o Relational Databases (e.g., PostgreSQL, MySQL, SQLite) for structured data with
complex relationships.
o NoSQL Databases (e.g., MongoDB, Redis) for unstructured or semi-structured data, or
when horizontal scalability is required.
 ORM (Object-Relational Mapping): Use an ORM like Django ORM (for Django projects) or
SQLAlchemy (for Flask and FastAPI) to abstract the database and interact with it using Python
objects, making it easier to maintain and scale the application.
 Database Optimization: Design efficient data models by ensuring:
o Proper indexing to speed up queries.
o Normalization or denormalization based on the application needs.
o Proper use of foreign keys, unique constraints, and transactions.
5. Handle User Authentication and Authorization
Efficient user authentication and authorization are critical in web applications:
 Authentication: Implement user authentication mechanisms using tools like:
o Django Authentication System (if using Django) for handling login, logout, and user
sessions.
o OAuth or JWT (JSON Web Tokens) for API-based authentication in RESTful applications.
o Third-party Authentication like Google or Facebook OAuth for easier user sign-ups.
 Authorization: Implement fine-grained access control using role-based access control (RBAC)
or permissions-based models. In Django, this can be achieved using the built-in permissions
system, while Flask can use libraries like Flask-Login and Flask-Principal.
6. Develop the Application Logic
Develop the core business logic for the application. Ensure that the code is modular, maintainable,
and testable:
 Separation of Concerns: Ensure that the application’s presentation, business logic, and data
layers are separate. This makes the application more maintainable and scalable.
 Services: Use services or helper functions to handle business logic, making the code easier to
test and extend.
 Asynchronous Programming: For high-performance applications that require handling
multiple tasks simultaneously, use asyncio, celery, or frameworks like FastAPI (which
natively supports asynchronous programming).
7. Implement Caching Mechanisms
Caching helps in reducing latency and improving the performance of your web system:
 In-memory Caching: Use caching tools like Redis or Memcached to store frequently
accessed data in memory, reducing database load and improving response times.
 Page Caching: Cache entire HTML responses for frequently visited pages.
 Database Query Caching: Cache the results of database queries to avoid repeated expensive
database calls.
8. Ensure Scalable and Efficient API Design
When building APIs, efficiency and scalability are key factors:
 RESTful APIs: Use Django REST Framework (DRF) or FastAPI to build RESTful APIs. Ensure
that you use proper HTTP status codes, pagination for large datasets, and filtering for resource
management.
 GraphQL: If your system requires flexible queries, consider using Graphene or Ariadne in
Python to implement GraphQL APIs.
 Rate Limiting: Implement rate limiting to prevent API abuse and ensure fair usage among
users. Tools like django_ratelimit or Flask-Limiter can be useful.
 API Documentation: Use automatic API documentation tools such as Swagger or Redoc.
FastAPI provides automatic Swagger UI and ReDoc docs out of the box.
9. Optimize Performance
Optimizing the performance of your web system ensures that it can handle high traffic while
delivering fast responses:
 Database Optimization: Use efficient queries, batch inserts, and avoid N+1 query issues.
Index frequently queried fields.
 Compression: Enable gzip compression on the server to reduce the size of responses sent
over the network.
 Load Balancing: Use a load balancer to distribute traffic evenly across multiple application
instances. Tools like Nginx or HAProxy can be used to balance traffic.
 Asynchronous Tasks: Use background task queues like Celery for handling long-running
tasks asynchronously.
10. Ensure Security Best Practices
Security should be a primary concern when building web systems:
 HTTPS: Ensure all communication between the client and server is encrypted using SSL/TLS.
 Data Validation and Sanitization: Validate and sanitize user inputs to prevent attacks such
as SQL injection, XSS, and CSRF.
 CSRF Protection: Implement Cross-Site Request Forgery (CSRF) protection. Frameworks like
Django provide built-in CSRF protection.
 Sensitive Data Protection: Encrypt sensitive data, such as passwords (using bcrypt or
Argon2) and API keys.
 Access Control: Implement role-based access control (RBAC) and enforce the principle of least
privilege for system users.
11. Testing and Debugging
Testing is vital for ensuring the reliability and stability of the system:
 Unit Testing: Use unittest or pytest to write tests for individual components of the system.
 Integration Testing: Test the system as a whole, ensuring all components work together.
 End-to-End Testing: Simulate user interactions with tools like Selenium or Playwright to
test the entire user flow.
 Performance Testing: Use Locust or Apache JMeter to perform load and stress testing to
understand how the system handles high traffic.
12. Deployment and Monitoring
Once the system is built and tested, it is time to deploy and monitor the application in a production
environment:
 Deployment: Use Docker to containerize your Python web system and Kubernetes for
container orchestration. Platforms like Heroku, AWS, or Google Cloud provide scalable
infrastructure to deploy web applications.
 Continuous Integration and Continuous Deployment (CI/CD): Implement CI/CD pipelines
using GitLab CI, Jenkins, or GitHub Actions to automate testing, building, and deployment.
 Monitoring and Logging: Use monitoring tools like Prometheus, Grafana, or Datadog for
monitoring the system’s performance. For logging, use ELK Stack (Elasticsearch, Logstash,
Kibana) or Fluentd to aggregate logs and monitor error rates and system health.

You might also like