top of page
Writer's pictureHit Govani

Python Programming BCA sem-4

Updated: May 24, 2023

1. What is Python?

Ans. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.


Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.



2. Explain features of Python.

Ans. Python provides many useful features which make it popular and valuable from the other programming languages. It supports object-oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features.


1) Easy to Learn and Use:

Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners.


2) Expressive Language:

Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print("Hello World"). It will take only one line to execute, while Java or C takes multiple lines.


3) Interpreted Language:

Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable.


4) Cross-platform Language:

Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once.


5) Free and Open Source:

Python is freely available for everyone. It is freely available on its official website www.python.org. It has a large community across the world that is dedicatedly working towards make new python modules and functions. Anyone can contribute to the Python community. The open-source means, "Anyone can download its source code without paying any penny."


6) Object-Oriented Language:

Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code.


7) Extensible:

It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code. It converts the program into byte code, and any platform can use that byte code.


8) Large Standard Library:

It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.


9) GUI Programming Support:

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.


10) Integrated:

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to debug the code.


11. Embeddable:

The code of the other programming language can use in the Python source code. We can use Python source code in another programming language as well. It can embed other language into our code.


12. Dynamic Memory Allocation:

In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.



3. Explain PVM.

Ans. We know that computers understand only machine code that comprises 1s and 0s. Since computer understands only machine code, it is imperative that we should convert any program into machine code before it is submitted to the computer for execution. For this purpose, we should take the help of a compiler. A compiler normally converts the program source code into machine code.


A Python compiler does the same task but in a slightly different manner. It converts the program source code into another code, called byte code. Each Python program statement is converted into a group of byte code instructions. Then what is byte code? Byte code represents the fixed set of instructions created by Python developers representing all types of operations. The size of each byte code instruction is 1 byte (or 8bits) and hence these are called byte code instructions. Python organization says that there may be newer instructions added to the existing byte code instructions from time to time. We can find byte code instructions in the .pyc file. Following Figure shows the role of virtual machine in converting byte code instructions into machine code:



The role of Python Virtual Machine (PVM) is to convert the byte code instructions into machine code so that the computer can execute those machine code instructions and display the final output. To carry out this conversion, PVM is equipped with an interpreter. The interpreter converts the byte code into machine code and sends that machine code to the computer processor for execution. Since interpreter is playing the main role, often the Python Virtual Machine is also called an interpreter.



4. Comparison between c and Python.

Ans.

c

Python

An Imperative programming model is basically followed by C.

An object-oriented programming model is basically followed by Python.

Variables are declared in C.

Python has no declaration.

C doesn’t have native OOP.

Python has OOP which is a part of the language.

Pointers are available in C language.

No pointers functionality is available in Python.

C is a compiled language.

Python is an interpreted language.

There is a limited number of built-in functions available in C.

There is a large library of built-in functions in Python.

Implementation of data structures requires its functions to be explicitly implemented.

It is easy to implement data structures in Python with built-in insert, append functions.

C is compiled directly to machine code which is executed directly by the CPU

Python is firstly compiled to a byte-code and then it is interpreted by a large C program.

Declaring of variable type in C is a necessary condition.

There is no need to declare a type of variable in Python.

C does not have complex data structures.

Python has some complex data structures.

Syntax of C is harder than python because of which programmers prefer to use python instead of C

It is easy to learn, write and read Python programs than C.

C programs are saved with .c extension.

Python programs are saved by .py extension.

An assignment is allowed in a line.

The assignment gives an error in line. For example, a=5 gives an error in python.

In C language testing and debugging is harder.

In Python, testing and debugging are directly not harder than in C.

C is complex than Python.

Python is much easier than C.

The basic if statement in c is represented as:

if ()

The basic if statement in Python is represented as:

if:

C language is fast.

Python programming language is slow

C uses {} to identify a separate block of code.

Python uses indentation to identify separate blocks of code.



5. Comparison between Java and Python.

Ans.

Parameters

Python

Java

Code

Python has generally fewer lines of code.

Java has long lines of code.


Framework

Compare to JAVA, Python has a lower number of Frameworks. Popular ones are Django and Flask.

Java has a large number of Frameworks. Popular ones are Spring, Hibernate, etc.

Syntax

The syntax is easy to remember almost similar to human language.

The syntax is complex as it throws errors if you miss semicolons or curly braces.

Key Features

Less line no of code, Rapid deployment, and dynamic typing.

Self-memory management, Robust, Platform independent

Speed

Python is slower since it uses an interpreter and also determines the data type at run time.

Java is faster in speed as compared to python.

Databases

Python’s database access layers are weaker than Java’s JDBC. This is why it is rarely used in enterprises.

(JDBC)Java Database Connectivity is the most popular and widely used to connect with databases.

Machine Learning Liabraries

Tensorflow, Pytorch.

Weka, Mallet, Deeplearning4j, MOA

Practical Agility

Python has always had a presence in the agile space and has grown in popularity for many reasons, including the rise of the DevOps movement.

Java enjoys more consistent refactoring support than Python thanks on one hand to its static type system which makes automated refactoring more predictable and reliable, and on the other to the prevalence of IDEs in Java development.

Multiple Inheritance

Python supports multiple Inheritance.

Java partially supports Multiple Inheritance through interfaces.



6. List out datatypes in python explain any two datatypes with example.

Ans. 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, data types are actually classes and variables are instances (object) of these classes. The following are the standard or built-in data types in Python:

  • Numeric

  • Sequence Type

  • Boolean

  • Set

  • Dictionary

  • Binary Types( memoryview, bytearray, bytes)


Boolean Data Type in 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). But 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.

# Python program to

# demonstrate Boolean type

print(type(True))

print(type(False))

print(type(true))

Output:

<class 'bool'>

<class 'bool'>


Numeric Data Type 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 – Complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j

Note – type() function is used to determine the type of data type.


# Python program to

# demonstrate numeric value

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'>



7. What is the difference between list and tuple?

Ans.

S. No.

LIST

TUPLE

1

Lists are mutable

Tuples are immutable

2

The implication of iterations is Time-consuming

The implication of iterations is comparatively Faster

3

The list is better for performing operations, such as insertion and deletion.

A Tuple data type is appropriate for accessing the elements

4

Lists consume more memory

Tuple consumes less memory as compared to the list

5

Lists have several built-in methods

Tuple does not have many built-in methods.

6

Unexpected changes and errors are more likely to occur

In a tuple, it is hard to take place.



8. Explain variable in python with example.

Ans. Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program.


Example of Variable in Python:

An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s terms, we can say that Variable in Python is containers that store values.

Here we have stored “Geeksforgeeks” in a var which is variable, and when we call its name the stored information will get printed.


Var = "Geeksforgeeks"

print(Var)

Output:

Geeksforgeeks


Rules for Python variables:

A Python variable name must start with a letter or the underscore character.

A Python variable name cannot start with a number.

A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).

The reserved words(keywords) in Python cannot be used to name the variable in Python.

Example : # valid variable name

geeks = 1

Geeks = 2

Ge_e_ks = 5

_geeks = 6

geeks_ = 7

_GEEKS_ = 8

print(geeks, Geeks, Ge_e_ks)

print(_geeks, geeks_, _GEEKS_)

Output:

1 2 5

6 7 8


Variables Assignment in Python:

Here, we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name.

Ex. # An integer assignment

age = 45

# A floating point

salary = 1456.8

# A string

name = "John"

print(age)

print(salary)

print(name)

Output:

45

1456.8

John


Declaration and Initialization of Variables:

Let’s see how to declare the variable and print the variable.

Ex. # declaring the var

Number = 100


# display

print( Number)

Output:

100


Redeclaring variables in Python:

We can re-declare the Python variable once we have declared the variable already.

Ex. # declaring the var

Number = 100

# display

print("Before declare: ", Number)

# re-declare the var

Number = 120.3

print("After re-declare:", Number)

Output:

Before declare: 100

After re-declare: 120.3


Python Assign Values to Multiple Variables :

Also, Python allows assigning a single value to several variables simultaneously with “=” operators.

For example:

a = b = c = 10

print(a)

print(b)

print(c)

Output:

10

10

10


Assigning different values to multiple variables:

Python allows adding different values in a single line with “,” operators.

a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)

print(b)

print(c)

Output:

1

20.2

GeeksforGeeks


Can we use the same name for different types?

If we use the same name, the variable starts referring to a new value and type.

Ex. a = 10

a = "GeeksforGeeks"

print(a)

Output:

GeeksforGeeks


How does + operator work with variables?

The Python plus operator + provides a convenient way to add a value if it is a number and concatenate if it is a string. If a variable is already created it assigns the new value back to the same variable.

Ex. a = 10

b = 20

print(a+b)


a = "Geeksfor"

b = "Geeks"

print(a+b)

Output:

30

GeeksforGeeks


Can we use + for different Datatypes also?

No use for different types would produce an error.

Ex.

a = 10

b = "Geeks"

print(a+b)

Output :

TypeError: unsupported operand type(s) for +: 'int' and 'str'


Global and Local Python Variables:

Local variables in Python are the ones that are defined and declared inside a function. We can not call this variable outside the function.

Ex. # This function uses global variable s

def f():

s = "Welcome geeks"

print(s)

f()

Output:

Welcome geeks


Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function.

Ex. # This function has a variable with

# name same as s.

def f():

print(s)


# Global scope

s = "I love Geeksforgeeks"

f()

Output:

I love Geeksforgeeks



9. List out the rules for identifiers.

Ans. Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names to identifiers to make the code understandable.

We can also use the Python string isidentifier() method to check whether a string is a valid identifier or not.


Rules for Naming Python Identifiers:

It cannot be a reserved python keyword.

It should not contain white space.

It can be a combination of A-Z, a-z, 0-9, or underscore.

It should start with an alphabet character or an underscore ( _ ).

It should not contain any special character other than an underscore ( _ ).


Examples of Python Identifiers:

Valid identifiers:

var1

_var1

_1_var

var_1

Invalid Identifiers

!var1

1var

1_var

var#1

var 1



10. Explain Keyword in Python.

Ans. Python has a set of keywords that are reserved words that cannot be used as variable names, function names, or any other identifiers:

Keyword

Description

and

A logical operator

as

To create an alias

assert

For debugging

break

To break out of a loop

class

To define a class

continue

To continue to the next iteration of a loop

def

To define a function

del

To delete an object

elif

Used in conditional statements, same as else if

else

Used in conditional statements

except

Used with exceptions, what to do when an exception occurs

False

Boolean value, result of comparison operations

finally

Used with exceptions, a block of code that will be executed no matter if there is an exception or not

for

To create a for loop

from

To import specific parts of a module

global

To declare a global variable

if

To make a conditional statement

import

To import a module

in

To check if a value is present in a list, tuple, etc.

is

To test if two variables are equal

lambda

To create an anonymous function

None

Represents a null value

nonlocal

To declare a non-local variable

not

A logical operator

or

A logical operator

pass

A null statement, a statement that will do nothing

raise

To raise an exception

return

To exit a function and return a value

True

Boolean value, result of comparison operations

try

To make a try...except statement

while

To create a while loop

with

Used to simplify exception handling

yield

To end a function, returns a generator



11. Explain type conversion with example.

Ans. In this tutorial, we will learn about the Python Type conversion with the help of examples.

In programming, type conversion is the process of converting data of one type to another. For example: converting int data to str.

There are two types of type conversion in Python.

Implicit Conversion - automatic type conversion

Explicit Conversion - manual type conversion

  • Python Implicit Type Conversion:

In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion.

Example 1: Converting integer to float

Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.

integer_number = 123

float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type

print("Value:",new_number)

print("Data Type:",type(new_number))

Run Code


Output:

Value: 124.23

Data Type: <class 'float'>

  • Explicit Type Conversion:

In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Example 2: Addition of string and integer Using Explicit Conversion:

num_string = '12'

num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)

print("Data type of num_sum:",type(num_sum))

Run Code


Output:

Data type of num_string before Type Casting: <class 'str'>

Data type of num_string after Type Casting: <class 'int'>

Sum: 35

Data type of num_sum: <class 'int'>



12. Explain arithmetic operator with example.

Ans. There are 7 arithmetic operators in Python. The lists are given below:

Operator

Description

Syntax

+

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 the second

x % y

**

Power (Exponent): Returns first raised to power second

x ** y

Python Arithmetic Operators Examples:

Addition Operator:

In Python, + is the addition operator. It is used to add 2 values.

Ex. val1 = 2

val2 = 3

# using the addition operator

res = val1 + val2

print(res)

Output: 5


Subtraction Operator:

In Python, – is the subtraction operator. It is used to subtract the second value from the first value.

Ex. val1 = 2

val2 = 3

# using the subtraction operator

res = val1 - val2

print(res)

Output: -1


Multiplication Operator:

In Python, * is the multiplication operator. It is used to find the product of 2 values.

Ex. val1 = 2

val2 = 3

# using the multiplication operator

res = val1 * val2

print(res)

Output : 6


Division Operator :

In Python, / is the division operator. It is used to find the quotient when the first operand is divided by the second.

Ex. val1 = 3

val2 = 2

# using the division operator

res = val1 / val2

print(res)

Output: 1.5


Modulus Operator:

In Python, % is the modulus operator. It is used to find the remainder when the first operand is divided by the second.

Ex. val1 = 3

val2 = 2

# using the modulus operator

res = val1 % val2

print(res)


Output: 1


Exponentiation Operator:

In Python, ** is the exponentiation operator. It is used to raise the first operand to the power of the second.

Ex. val1 = 2

val2 = 3

# using the exponentiation operator

res = val1 ** val2

print(res)

Output: 8


Floor Division Operator:

In Python, // is used to conduct the floor division. It is used to find the floor of the quotient when the first operand is divided by the second.

Ex. val1 = 3

val2 = 2

# using the floor division

res = val1 // val2

print(res)

Output: 1



13. Explain membership operator with example.

Ans. Membership operators are used to test if a sequence is presented in an object:

Operator : in

Description: Returns True if a sequence with the specified value is present in the object

Example : x in y

x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list

Output: True


Operator : not in

Description : Returns True if a sequence with the specified value is not present in the object

Example: x not in y

x = ["apple", "banana"]

print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is not in the list

Output: True



14. Explain identify operator with example.

Ans. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Operator: is

Description: Returns true if both variables are the same object

Example: x is y

x = ["apple", "banana"]

y = ["apple", "banana"]

z = x

print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y, even if they have the same content

print(x == y)

# to demonstrate the difference between "is" and "==": this comparison returns True because x is equal to y


Output:

True

False

True


Operator : is not

Description: Returns true if both variables are not the same object

Example: x is not y

x = ["apple", "banana"]

y = ["apple", "banana"]

z = x

print(x is not z)

# returns False because z is the same object as x

print(x is not y)

# returns True because x is not the same object as y, even if they have the same content

print(x != y)

# to demonstrate the difference between "is not" and "!=": this comparison returns False because x is equal to y


Output :

False

True

False



15. Explain if loop with example.

Ans. If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use if statement to accomplish this in programming. In this guide, we will learn how to use if statements in Python programming with the help of examples.


Syntax of If statement in Python:

The syntax of if statement in Python is pretty simple.


if condition:

block_of_code

If statement flow diagram:


Python – If statement Example:

flag = True

if flag==True:

print("Welcome")

print("To")

print("BeginnersBook.com")


Output:

Welcome

To

BeginnersBook.com


16. Write a program of print the largest of the three numbers in python.

Ans. Source Code:

# Python program to find the largest number among the three input numbers


# change the values of num1, num2 and num3

# for a different result

num1 = 10

num2 = 14

num3 = 12


# uncomment following lines to take three numbers from user

#num1 = float(input("Enter first number: "))

#num2 = float(input("Enter second number: "))

#num3 = float(input("Enter third number: "))


if (num1 >= num2) and (num1 >= num3):

largest = num1

elif (num2 >= num1) and (num2 >= num3):

largest = num2

else:

largest = num3


print("The largest number is", largest)


Output:

The largest number is 14.0



17. Write a program to check whether a number is even or not.

Ans. Source Code:

# Python program to check if the input number is odd or even.

# A number is even if division by 2 gives a remainder of 0.

# If the remainder is 1, it is an odd number.


num = int(input("Enter a number: "))

if (num % 2) == 0:

print("{0} is Even".format(num))

else:

print("{0} is Odd".format(num))


Output:

Enter a number: 43

43 is Odd



18. Explain for loop with example.

Ans. For Loop in Python:

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.


Syntax:

for iterator_var in sequence:

statements(s)


# Python program to illustrate

# Iterating over range 0 to n-1

n = 4

for i in range(0, n):

print(i)


Output:

0

1

2

3


Example with List, Tuple, string, and dictionary iteration using For Loops in Python

We can use for loop to iterate lists, tuples, strings and dictionaries in Python.


# Python program to illustrate

# Iterating over a list

print("List Iteration")

l = ["geeks", "for", "geeks"]

for i in l:

print(i)

# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t = ("geeks", "for", "geeks")

for i in t:

print(i)

# Iterating over a String

print("\nString Iteration")

s = "Geeks"

for i in s:

print(i)

# Iterating over dictionary

print("\nDictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d:

print("%s %d" % (i, d[i]))

# Iterating over a set

print("\nSet Iteration")

set1 = {1, 2, 3, 4, 5, 6}

for i in set1:

print(i),


Output:

List Iteration

geeks

for

geeks

Tuple Iteration

geeks

for

geeks

String Iteration

G

e

e

k

s

Dictionary Iteration

xyz 123

abc 345

Set Iteration

1

2

3

4

5

6


Iterating by the index of sequences:

We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length. See the below example:


# Python program to illustrate

# Iterating by index

list = ["geeks", "for", "geeks"]

for index in range(len(list)):

print(list[index])


Output:

geeks

for

geeks


Using else statement with for loop in Python:

We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.


# Python program to illustrate

# combining else with for

list = ["geeks", "for", "geeks"]

for index in range(len(list)):

print(list[index])

else:

print("Inside Else Block")


Output:

geeks

for

geeks

Inside Else Block



19. Explain while loop with example. Write a program on sum= 1+2+3+....+n using while loop.

Ans. While Loop in Python:

In python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.


Syntax:

while expression:

statement(s)


All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.


Example of Python While Loop :

Let’s see a simple example of while loop in Python.

# Python program to illustrate while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")


Output:

Hello Geek

Hello Geek

Hello Geek


Using else statement with While Loop in Python:

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.


Syntax of While Loop with else statement:

while condition:

# execute these statements

else:

# execute these statements


Examples of While Loop with else statement

Here is an example of while loop with else statement in Python:


# Python program to illustrate

# combining else with while

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")

else:

print("In Else Block")


Output:

Hello Geek

Hello Geek

Hello Geek

In Else Block


Infinite While Loop in Python:

If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so.


# Python program to illustrate

# Single statement while block

count = 0

while (count == 0):

print("Hello Geek")


Program:

Source Code:

# Sum of natural numbers up to num

num = 16

if num < 0:

print("Enter a positive number")

else:

sum = 0

# use while loop to iterate until zero

while(num > 0):

sum += num

num -= 1

print("The sum is", sum)


Output:

The sum is 136



20. How to use pass statement in python?

Ans. The Python pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored.


The Syntax of the pass statement:

pass


Why Python Needs “pass” Statement?

If we do not use pass or simply enter a comment or a blank here, we will receive an IndentationError error message.


Examples of Python pass statement

Let’s see some of the examples to understand pass statements in Python more clearly.


Use of pass keyword in Function:

Python Pass keyword can be used in empty functions. To read more click here


def function:

pass


Use of pass keyword in Python Class:

The pass keyword can also be used in an empty class in Python.


class geekClass:

pass


Use of pass keyword in Python Loop :

The pass keyword can be used in Python for loop, when a user doesn’t know what to code inside the loop in Python.


n = 10

for i in range(n):

# pass can be used as placeholder

# when code is to added later

pass


Use of pass keyword in Conditional statement:

Python pass keyword can be used with conditional statements.


a = 10

b = 20

if(a<b):

pass

else:

print("b<a")


Let’s take another example in which the pass statement gets executed when the condition is true.


li =['a', 'b', 'c', 'd']

for i in li:

if(i =='a'):

pass

else:

print(i)


Output:

b

c

d



21. How to declare function in python ? Explain with example.

Ans. A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create two functions to solve this problem:

create a circle function

create a color function


Types of function:

There are two types of function in Python programming:

Standard library functions - These are built-in functions in Python that are available to use.

User-defined functions - We can create our own functions based on our requirements.


Python Function Declaration:

The syntax to declare a function is:


def function_name(arguments):

# function body

return


Example: Python Function:

def greet():

print('Hello World!')

# call the function

greet()

print('Outside function')


Output:

Hello World!

Outside function


Python Function Arguments:

As mentioned earlier, a function can also have arguments. An argument is a value that is accepted by a function. For example,

# function with two arguments

def add_numbers(num1, num2):

sum = num1 + num2

print('Sum: ',sum)

# function with no argument

def add_numbers():

# code


Example 1: Python Function Arguments

# function with two arguments

def add_numbers(num1, num2):

sum = num1 + num2

print("Sum: ",sum)

# function call with two values

add_numbers(5, 4)


# Output: Sum: 9


Example 2: Function return Type

# function definition

def find_square(num):

result = num * num

return result

# function call

square = find_square(3)

print('Square:',square)


# Output: Square: 9


Example 3: Add Two Numbers

# function that adds two numbers

def add_numbers(num1, num2):

sum = num1 + num2

return sum

# calling function with two values

result = add_numbers(5, 4)

print('Sum: ', result)


# Output: Sum: 9


Example 4: Python Library Function

import math

# sqrt computes the square root

square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power

power = pow(2, 3)

print("2 to the power 3 is",power)


Output:

Square Root of 4 is 2.0

2 to the power 3 is 8



22. Write a program in python to find enter no is even or odd using function.

Ans. Using modular operator:

num=int(input("Enter a number for check odd or even: "))

def find_Evenodd(num):

if(num%2==0):

print(num," Is an even")

else:

print(num," is an odd")

find_Evenodd(num);//function call


OUTPUT:

Case 1:

Enter a number for check odd or even: 349

349 is an odd

Case 2:

Enter a number for check odd or even: 234

234 is an even


Using Bitwise operator:

num=int(input("Enter a number for check odd or even: "))

def find_Evenodd(num)://function definition

if(num&1==1):

print(num, "is an odd number");

else:

print(num, "is an even number");

find_Evenodd(num);//function call


OUTPUT:

Case 1:

Enter a number for check odd or even: 678

678 is an even number

Case 2:

Enter a number for check odd or even: 765

765 is an odd number


Using the division operator:

num=int(input("Enter a number for check odd or even: "))

def find_Evenodd(num)://function definition

number=(num/2)*2

if(number==num):

print(num, "is a even number");

else:

print(num, "is a odd number");

find_Evenodd(num);//call the function


OUTPUT:

Case 1:

Enter a number for check odd or even: 678

678 is a even number

Case 2:

Enter a number for check odd or even: 987

987 is a odd number



23. Write a program in Python to find Fibonacci series using function.

(Output like this: 0 1 1 2 3 5 8 13 ....)

Ans. In this program, you'll learn to print the Fibonacci sequence using while loop.


To understand this example, you should have the knowledge of the following Python programming topics:

Python if...else Statement

Python while Loop


A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.


Source Code:

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0


# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1


Output:

How many terms? 7

Fibonacci sequence:

0

1

1

2

3

5

8


If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.



24. Write a program to perform pyramid pattern using range() function.

1

1 2

1 2 3

1 2 3 4

Ans. Source Code:

rows = int(input("Enter number of rows: "))


for i in range(rows):

for j in range(i+1):

print(j+1, end=" ")

print("\n")


In the above program, let's see how the pattern is printed.

First, we get the height of the pyramid rows from the user.

In the first loop, we iterate from i = 0 to i = rows.

In the second loop, we print numbers starting from 1 to j, where j ranges from 0 to i.

After each iteration of the first loop, we print a new line.



25. Explain recursion with example.

Ans. In this tutorial, you will learn to create a recursive function (a function that calls itself).

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.


In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions.


Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.


Example of a recursive function:

def factorial(x):

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * factorial(x-1))

num = 3

print("The factorial of", num, "is", factorial(num))


Output:

The factorial of 3 is 6


IMAGE PROCESS


Advantages of Recursion:

Recursive functions make the code look clean and elegant.

A complex task can be broken down into simpler sub-problems using recursion.

Sequence generation is easier with recursion than using some nested iteration.


Disadvantages of Recursion:

Sometimes the logic behind recursion is hard to follow through.

Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

Recursive functions are hard to debug.



26. What is lambda function? Explain with example.

Ans. A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.


Python lambda Function Declaration

We use the lambda keyword instead of def to create a lambda function. Here's the syntax to declare the lambda function:

lambda argument(s) : expression


Here,

argument(s) - any value passed to the lambda function

expression - expression is executed and returned


Let's see an example,

greet = lambda : print('Hello World')


To execute this lambda function, we need to call it. Here's how we can call the lambda function

# call the lambda

greet()

The lambda function above simply prints the text 'Hello World'.


Example: Python lambda Function:

# declare a lambda function

greet = lambda : print('Hello World')

# call lambda function

greet()


# Output: Hello World


Python lambda Function with an Argument

Similar to normal functions, the lambda function can also accept arguments. For example,

# lambda that accepts one argument

greet_user = lambda name : print('Hey there,', name)

# lambda call

greet_user('Delilah')


# Output: Hey there, Delilah



27. List out the characteristics of the list. How to add and remove element in list explain with example.

Ans. The important characteristics of Python lists are as follows:

Lists are ordered.

Lists can contain any arbitrary objects.

List elements can be accessed by index.

Lists can be nested to arbitrary depth.

Lists are mutable.

Lists are dynamic.


Python remove() Method:

A built-in method in Python that we can use with the list data type is remove(). It helps to eliminate the first item from the list that matches the given item.


Syntax:

list.remove(element)

element:- The item of the list we would like to remove.


When there are duplicate elements in a list, the first item that matches the provided item is eliminated. If the supplied element does not exist in the list, an exception will be thrown stating that the element does not exist in the list. There is no value returned by the delete () function. The value is passed as a parameter to delete(). Therefore, it must be of the right datatype.


Code:

# Python program to remove an element from a list using the remove() function

my_list = ['Javatpoint', 'Python', 'Tutorial', 'List',

'Element', 'Removal']

print("Initial List is :", my_list)

# through remove() deleting 'Python' from the my_list

my_list.remove('Python')

print( "After using the function :", my_list )


Output:

Initial List is : ['Javatpoint', 'Python', 'Tutorial', 'List', 'Element', 'Removal']

After using the function : ['Javatpoint', 'Tutorial', 'List', 'Element', 'Removal']


Add Elements to a List in Python:

Use append() to add an element (string, number, iterable, etc.) to the end of a list.

Use insert() to add an element at a specific index in a list.

Use extend() add iterable (e.g. list, tuple) to the end of the list.

Use + operator to concatenate two lists together.

Use list comprehension to add elements to a list based on a certain condition or operation.


Ex.: Add Elements to List Using append():


# Add an element to the list

technology = ['Spark','Python','Pyspark']

print("Actual List",technology)

# Add 'Java' to the list

technology.append('Java')

print("Updated List: ",technology)


Output:

Actual List ['Spark','Python','Pyspark']

Updated List: ['Spark','Python','Pyspark','Java']



28. Explain count() and index() method in tuple.

Ans. Python Tuple count()

In this tutorial, you will learn about the Python Tuple count() method with the help of examples.

The count() method returns the number of times the specified element appears in the tuple.

count() Syntax

The syntax of the count() method is:


vowels.count('i')

Here, vowels is the tuple and 'i' is an element to count.


count() Parameter

The count() method takes a single parameter:


'i' - an element to count in the tuple

count() Return Value

The count() method returns:


a number of times the given element i is present in the tuple.


Example 1: Python Tuple count():

# tuple of numbers

numbers = (1, 3, 4, 1, 6 ,1 )

# counts the number of 1's in the tuple

count = numbers.count(1)

print('The count of 1 is:', count)

# counts the number of 7's in the tuple

count = numbers.count(7)

print('The count of 7 is:', count)


Output:

The count of 1 is: 3

The count of 7 is: 0



29. What are classes and object in Python?

Ans. Creating a Python Class:

Here, the class keyword indicates that you are creating a class followed by the name of the class (Dog in this case).

class Dog:

sound = "bark"


Object of Python Class:

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.


An object consists of:

State: It is represented by the attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.

Identity: It gives a unique name to an object and enables one object to interact with other objects.


Declaring Claas Objects (Also called instantiating a class):

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.


Example of Python Class and object:

Creating an object in Python involves instantiating a class to create a new instance of that class. This process is also referred to as object instantiation.

# Python3 program to

# demonstrate instantiating

# a class

class Dog:

# A simple class

# attribute

attr1 = "mammal"

attr2 = "dog"

# A sample method

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()


Output:

mammal

I'm a mammal

I'm a dog



30. Explain _init_() function.

Ans. The Default __init__ Constructor in C++ and Java. Constructors are used to initializing the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.


Example of __init__ :

# A Sample class with init method

class Person:

# init method or constructor

def __init__(self, name):

self.name = name

# Sample Method

def say_hi(self):

print('Hello, my name is', self.name)

# Creating different objects

p1 = Person('Nikhil')

p2 = Person('Abhinav')

p3 = Person('Anshul')

p1.say_hi()

p2.say_hi()

p3.say_hi()


Output:

Hello, my name is Nikhil

Hello, my name is Abhinav

Hello, my name is Anshul



31. What are classes and object in python?

Ans.

Q. 29th answer



32. What is constructor? Explain types of constructor with example.

Ans. Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.


Syntax of constructor declaration :

def __init__(self):

# body of the constructor

Types of constructors :


default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.


parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.


Example of default constructor :

class GeekforGeeks:


# default constructor

def __init__(self):

self.geek = "GeekforGeeks"

# a method for printing data members

def print_Geek(self):

print(self.geek)

# creating object of the class

obj = GeekforGeeks()

# calling the instance method using the object obj

obj.print_Geek()


Output:

GeekforGeeks



Example of the parameterized constructor :

class Addition:

first = 0

second = 0

answer = 0

# parameterized constructor

def __init__(self, f, s):

self.first = f

self.second = s

def display(self):

print("First number = " + str(self.first))

print("Second number = " + str(self.second))

print("Addition of two numbers = " + str(self.answer))

def calculate(self):

self.answer = self.first + self.second

# creating object of the class

# this will invoke parameterized constructor

obj1 = Addition(1000, 2000)

# creating second object of same class

obj2 = Addition(10, 20)

# perform Addition on obj1

obj1.calculate()

# perform Addition on obj2

obj2.calculate()

# display result of obj1

obj1.display()

# display result of obj2

obj2.display()


Output:

First number = 1000

Second number = 2000

Addition of two numbers = 3000

First number = 10

Second number = 20

Addition of two numbers = 30



33. What is inheritance? Explain types of inheritance.

Ans. Inheritance is defined as the mechanism of inheriting the properties of the base class to the child class. Here we a going to see the types of inheritance in Python.


Types of Inheritance in Python:

Types of Inheritance depend upon the number of child and parent classes involved. There are four types of inheritance in Python:


Single Inheritance:

Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code.


IMAGE Single


Multiple Inheritance:

When a class can be derived from more than one base class this type of inheritance is called multiple inheritances. In multiple inheritances, all the features of the base classes are inherited into the derived class.


IMAGE Multiple


Multilevel Inheritance :

In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather.


IMAGE Multilevel


Hierarchical Inheritance:

When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.


IMAGE Hierarchical


Hybrid Inheritance:

Inheritance consisting of multiple types of inheritance is called hybrid inheritance.


IMAGE Hybrid



34. What is the use of super keyword?

Ans. The Python super() function returns objects represented in the parent’s class and is very useful in multiple and multilevel inheritances to find which class the child class is extending first.


Syntax of super() in Python:

Syntax: super()

Return : Return a proxy object which represents the parent’s class.


Example of super() function in Python:

class Emp():

def __init__(self, id, name, Add):

self.id = id

self.name = name

self.Add = Add

# Class freelancer inherits EMP

class Freelance(Emp):

def __init__(self, id, name, Add, Emails):

super().__init__(id, name, Add)

self.Emails = Emails

Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")

print('The ID is:', Emp_1.id)

print('The Name is:', Emp_1.name)

print('The Address is:', Emp_1.Add)

print('The Emails is:', Emp_1.Emails)


Output:

The ID is: 103

The Name is: Suraj kr gupta

The Address is: Noida

The Emails is: KKK@gmails



35. What is method overriding? Explain with example.

Ans. Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.


IMAGE Animal Dog


The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.


Example:

# Python program to demonstrate

# method overriding

# Defining parent class

class Parent():

# Constructor

def __init__(self):

self.value = "Inside Parent"

# Parent's show method

def show(self):

print(self.value)

# Defining child class

class Child(Parent):

# Constructor

def __init__(self):

self.value = "Inside Child"

# Child's show method

def show(self):

print(self.value)

# Driver's code

obj1 = Parent()

obj2 = Child()

obj1.show()

obj2.show()


Output:

Inside Parent

Inside Child


Method overriding with multiple and multilevel inheritance:


Multiple Inheritance: When a class is derived from more than one base class it is called multiple Inheritance.

Example: Let’s consider an example where we want to override a method of one parent class only. Below is the implementation.

# Python program to demonstrate

# overriding in multiple inheritance

# Defining parent class 1

class Parent1():

# Parent's show method

def show(self):

print("Inside Parent1")

# Defining Parent class 2

class Parent2():

# Parent's show method

def display(self):

print("Inside Parent2")

# Defining child class

class Child(Parent1, Parent2):

# Child's show method

def show(self):

print("Inside Child")

# Driver's code

obj = Child()

obj.show()

obj.display()


Output:

Inside Child

Inside Parent2


Multilevel Inheritance: When we have a child and grandchild relationship.

Example: Let’s consider an example where we want to override only one method of one of its parent classes. Below is the implementation.

# Python program to demonstrate

# overriding in multilevel inheritance

# Python program to demonstrate

# overriding in multilevel inheritance

class Parent():

# Parent's show method

def display(self):

print("Inside Parent")

# Inherited or Sub class (Note Parent in bracket)

class Child(Parent):

# Child's show method

def show(self):

print("Inside Child")

# Inherited or Sub class (Note Child in bracket)

class GrandChild(Child):

# Child's show method

def show(self):

print("Inside GrandChild")

# Driver code

g = GrandChild()

g.show()

g.display()


Output:

Inside GrandChild

Inside Parent



36. What is self-variable constructor?

Ans. self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.


The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.


self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.


Another Example of Using SELF:

class car():

# init method or constructor

def __init__(self, model, color):

self.model = model

self.color = color

def show(self):

print("Model is", self.model )

print("color is", self.color )

# both objects have different self which

# contain their attributes

audi = car("audi a4", "blue")

ferrari = car("ferrari 488", "green")

audi.show() # same output as car.show(audi)

ferrari.show() # same output as car.show(ferrari)

#note:we can also do like this

print("Model for audi is ",audi.model)

print("Colour for ferrari is ",ferrari.color)

#this happens because after assigning in the constructor the attributes are linked to that particular object

#here attributes(model,colour) are linked to objects(audi,ferrari) as we initialize them

# Behind the scene, in every instance method

# call, python sends the instances also with

# that method call like car.show(audi)


Output:

Model is audi a4

color is blue

Model is ferrari 488

color is green



37. What is Exception handling in Python?

Ans. 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 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:

# initialize the amount variable

amount = 10000

# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount > 2999)

print("You are eligible to purchase Dsa Self Paced")


Output:

File "/home/ac3580186f4ca7978956ff46697139.py",line 4

if (amount>2999)

syntax error: invalid syntax


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:

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)


Output:

Traceback (most recent call last):

File "/home/f3ad05420ab851d4bd106ffb0422997.py", line 4, in <module>

a=mark/0

ZeroDivisonError: Divison by zero


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.


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 kept inside the try clause and the statements that handle the exception are written inside except clause.


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)


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.


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.


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).


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.


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.



38. Explain Try, except and finally keyword with example.

Ans. Try Except in Python:

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.


Syntax:

try:

# Some Code

except:

# Executed if error in the

# try block


How try() works?

First, the try clause is executed i.e. the code between try.

If there is no exception, then only the try clause will run, except clause is finished.

If any exception occurs, the try clause will be skipped and except clause will run.

If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.

A try statement can have more than one except clause


Code 1: No exception, so the try clause will run.

# Python code to illustrate

# working of try()

def divide(x, y):

try:

# Floor Division : Gives only Fractional Part as Answer

result = x // y

print("Yeah ! Your answer is :", result)

except ZeroDivisionError:

print("Sorry ! You are dividing by zero ")


# Look at parameters and note the working of Program

divide(3, 2)


Auxiliary Space: O(1)

Output :

Yeah ! Your answer is : 1


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 exceptions.

Syntax:

try:

# Some Code

except:

# Executed if error in the

# try block

else:

# execute if no exception

finally:

# Some code .....(always executed)


Code:

# Python program to demonstrate finally

# No exception Exception raised in try block

try:

k = 5//0 # raises divide by zero exception.

print(k)

# handles zerodivision exception

except ZeroDivisionError:

print("Can't divide by zero")

finally:

# this block is always executed

# regardless of exception generation.

print('This is always executed')


Output:

Can't divide by zero

This is always executed



39. Explain different types of file access modes.

Ans. File Handling in Python :

File handling is an important activity in every web app. The types of activities that you can perform on the opened file are controlled by Access Modes. These describe how the file will be used after it has been opened.

These modes also specify where the file handle should be located within the file. Similar to a pointer, a file handle indicates where data should be read or put into the file.


In Python, there are six methods or access modes, which are:

Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the handle is located. It raises the I/O error if the file does not exist. This is the default mode for opening files as well.


Read and Write ('r+’): This method opens the file for both reading and writing. The start of the file is where the handle is located. If the file does not exist, an I/O error gets raised.


Write Only ('w’): This mode opens the file for writing only. The data in existing files are modified and overwritten. The start of the file is where the handle is located. If the file does not already exist in the folder, a new one gets created.


Write and Read ('w+’): This mode opens the file for both reading and writing. The text is overwritten and deleted from an existing file. The start of the file is where the handle is located.


Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet exist, a new one gets created. The handle is set at the end of the file. The newly written data will be added at the end, following the previously written data.


Append and Read (‘a+’): Using this method, you can read and write in the file. If the file doesn't already exist, one gets created. The handle is set at the end of the file. The newly written text will be added at the end, following the previously written data.


How to Write to a File in Python:

There are two methods of writing to a file in Python, which are:

The write() method:

This function inserts the string into the text file on a single line.

Based on the file we have created above, the below line of code will insert the string into the created text file, which is "myfile.txt.”

file.write("Hello There\n")

The writelines() method:

This function inserts multiple strings at the same time. A list of string elements is created, and each string is then added to the text file.

Using the previously created file above, the below line of code will insert the string into the created text file, which is "myfile.txt.”

f.writelines(["Hello World ", "You are welcome to Fcc\n"])


The readline() method:

This function reads a line from a file and returns it as a string. It reads at most n bytes for the specified n. But even if n is greater than the length of the line, it does not read more than one line.

f = open("myfiles.txt", "r")

print(f.readline())

The readlines() method:

This function reads all of the lines and returns them as string elements in a list, one for each line.

You can read the first two lines by calling readline() twice, reading the first two lines of the file:

f = open("myfiles.txt", "r")

print(f.readline())

print(f.readline())


40. How to open and close .txt file in python?

Ans. Opening a file in Python:

There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).

Note: The file should exist in the same directory as the Python script, otherwise, the full address of the file should be written.

Syntax: File_object = open(“File_Name”, “Access_Mode”)

Parameters:

File_Name: It is the name of the file that needs to be opened.

Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python


Example 1: Open and read a file using Python

# open the file using open() function

file = open("sample.txt")

# Reading from file

print(file.read())

Output:

Hello Geek!

This is a sample text file for the example.


Closing a file in Python:

As you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.

Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file.

Example: Read and close the file using Python

# open the file using open() function

file = open("sample.txt")

# Reading from file

print(file.read())

# closing the file

file.close()

# Attempt to write in the file

file.write(" Attempt to write on a closed file !")

Output:

ValueError: I/O operation on closed file.



41. How to create MySQL database connection using python.

Ans. Creating MySQL Database:

To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class.

import mysql.connector

mydb = mysql.connector.connect(

host = "localhost",

user = "yourusername",

password = "your_password"

)

# Creating an instance of 'cursor' class

# which is used to execute the 'SQL'

# statements in 'Python'

cursor = mydb.cursor()

# Creating a database with a name

# 'geeksforgeeks' execute() method

# is used to compile a SQL statement

# below statement is used to create

# the 'geeksforgeeks' database

cursor.execute("CREATE DATABASE geeksforgeeks")

Output:


If the database with the name ‘geeksforgeeks’ already exists then you will get an error, otherwise no error. So make sure that the new database that you are creating does not have the same name as the database already you created or exists previously. Now to check the databases that you created, use “SHOW DATABASES” – SQL statement i.e. cursor.execute(“SHOW DATABASES”)

Notes:

mysql.connector allows Python programs to access MySQL databases.

connect() method of the MySQL Connector class with the arguments will connect to MySQL and would return a MySQLConnection object if the connection is established successfully.

user = “yourusername”, here “yourusername” should be the same username as you set during MySQL installation.

password = “your_password”, here “your_password” should be the same password as you set during MySQL installation.

cursor() is used to execute the SQL statements in Python.

execute() method is used to compile a SQL statement.

..

21 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Connect To Me 

  • YouTube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
  • Pinterest
bottom of page