Scripting Lang
Scripting Lang
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.
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.
Describe how to use and implement packages and modules in a PERL script.
--------------------------------------------------------------------------------------------------------------------------------
Unit 2
Explain about function libraries in PHP.
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.
What are the features of PHP? Write about the data types, variables and constants used 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.
--------------------------------------------------------------------------------------------------------------------------------
Explain about IP Based authentication.
How to execute a PHP script using command line arguments? Explain with an example script.
Write about file uploading directives and functions in PHP with examples.
Write a program to explain about PHP and Web Forms with an example.
--------------------------------------------------------------------------------------------------------------------------------
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
Recursive Procedures
An example for recursive procedures is shown below −
#!/usr/bin/tclsh
}
puts [factorial 3]
puts [factorial 5]
When the above code is executed, it produces the following result −
6
120
//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 :
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
--------------------------------------------------------------------------------------------------------------------------------
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
print(a is not b)
print(a is c)
[/GFGTABS]
Output
True
True
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
print(min)
[/GFGTABS]
Output:
10
@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:
@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:
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:
$ 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.
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):
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
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.
# 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
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
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]
Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
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
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
Output
Set with the use of String: {'e', 'G', 's', 'F', 'o', 'r', 'k'}
Set with the use of List: {'For', 'Geeks'}
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'}
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.
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.
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.
# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))
Output
number : 5
Factorial : 120
Time complexity: O(n)
Space complexity: O(n)
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))
Output
The original number is : 9669669
Is the number palindrome ? : True
Output
The original number is : 9669669
Is the number palindrome ? : True
Output
True
False