Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Chapter- 1- Introduction and Syntax of Python Program

Q.1.) Name the different Modes of Python. (2


Marks) Ans.)
There are 2 Modes in Python, namely:-
1.) Interactive Mode, and
2.) Script Mode.
Interactive Mode:-
 Interactive etymologically means “working simultaneously and creating impact of our
work on the other’s work”. Interactive mode is based on this ideology. In this mode, as we
enter a command and press enter, the very next step we get the output. The output of the
code is influenced by the last command we give.
 Interactive mode in Python is a way of running the Python interpreter, which allows you
to enter Python commands one by one and see their results immediately. It is an
interactive shell where you can type in code and see the output instantly.
 To access the interactive mode, you can simply open the terminal or command prompt
on your computer and type python followed by the enter key. This will start the Python
interpreter in interactive mode, and you will see the >>> prompt, indicating that you can
now enter Python commands.
 For example, you can type print(“Hello, world!”) and hit enter. The interpreter will
immediately execute the command and display the output “Hello, world!” on the next
line.
 It’s a useful tool for quickly testing small pieces of code or trying out different approaches
to a problem. To exit the interactive mode, you can type exit() or quit() or use the
keyboard shortcut Ctrl+Z on Windows or Ctrl+D on Unix-like systems.
 This mode is very suitable for beginners in programming as it helps them evaluate
their code line by line and understand the execution of code well. It is very convenient
for writing very short lines of code.
Script Mode:-
 Script etymologically means a system of writing. In the script mode, a python program
can be written in a file. This file can then be saved, with a “.py” extension, and can be
executed.
 In the script file, you can write your Python code, including function definitions, variable
assignments, and statements. Once you have saved your Python script file, you can run it
in script mode.
 We can view the code at any time by opening the file and editing becomes quite easy as
we can open and view the entire code as many times as we want. Script mode is very
suitable for writing long pieces of code. The file made in the script mode is by default
saved in the Python installation folder.
 Overall, script mode is a convenient and powerful way to write and run Python code, and
it is widely used for everything from small scripts to large-scale applications.

Q.2.) List the different Object- Oriented Features, supported by Python. (2 Marks)
Ans.)
Encapsulation,
Inheritance,
Polymorphism,
Abstraction.
Q.3.) Describe Python Interpreter. (2 Marks)
Ans.)
 An interpreter is a kind of program that executes other programs. When you write Python
programs, it converts source code written by the developer into intermediate language
which is again translated into the native language / machine language that is executed.
 It is basically the program that runs Python code.
 It is a command-line program that allows you to execute Python commands and scripts
interactively or from a file. The interpreter reads and executes each line of code one by one,
interpreting the code and producing output as it goes. It is available on most operating
systems, including Windows, macOS, and Linux. It can be run from a command prompt or
terminal window, and it can be used interactively or to execute Python scripts.
 The Python interpreter first reads the command, then evaluates the command, prints the
results, and then again loops it back to read the command and because of this only Python
is known as REPL i.e., (Read, Evaluate, Print, Loop).

Q.4.) State how to perform Comments in Python. (2


Marks) Ans.)
It’s important to use comments in your code to make it more readable and understandable,
especially for other people who might read your code in the future. However, it’s also important
to use comments sparingly and only when necessary, as too many comments can make your code
harder to read. In Python, there are two ways to perform comments:
1.) Single- Line Comments, and
2.) Multiple- Line Comments.
Single–Line comments: Single-line comments start with the hash symbol (#) and continue
until the end of the line. Anything written after the hash symbol will be ignored by the Python
interpreter.
For example:
# This is a single-line comment
print(“Hello, World!”) # This is also a single-line comment
Output:-

Jupyter Notebook:-

Multiple- Line Comments:- Multi-line comments are used to explain multiple lines of code.
In Python, multi-line comments are enclosed in triple quotes (“””). They can span across
multiple lines and are typically used to provide documentation for functions or modules.
If we see, we use Strings as a Multiple- Line Comments. This is because, Strings will not get
stored, or displayed, until they are assigned to some variable. So, this is the reason for using
Triple Quotes as a Double- Line Comments.
For example:
“””
This is a multi-line comment.
It can span across multiple
lines. “””
print(“Hello, World!”)
Output:-

Jupyter Notebook:-

Q.5.) Explain Variables in Python, with it’s Rules and Conventions of it’s declaration. (2 Marks)
Ans.)
In Python, a variable is a reserved memory location used to store data values. Variables in
Python are dynamic, which means they don’t need to be declared with a specific data type
before they are assigned a value. The data type of the variable is determined automatically based
on the type of value assigned to it.
Rules for declaring variables in Python:
 Variable names must begin with a letter or an underscore. They cannot begin with a number.
 Variable names can contain letters, numbers, and underscores.
 Variable names are case sensitive.
 Variable names should be descriptive and meaningful.
Conventions for declaring variables in Python:
 Use lowercase letters for variable names.
 Use underscores to separate words in variable names. For example, “first_name” instead of
“firstName”.
 Use camelCase notation for function names.
 Avoid using reserved words as variable names. For example, “if” and “while” are
reserved words in Python.
Overall, the conventions for variable naming in Python are focused on readabilityOverall, the
conventions for variable naming in Python are focused on readability and clarity, making it
easier for programmers to understand the purpose and use of each variable in their code.
Q.6.) List the Features of Python. (2 Marks)
Ans.)

1 .Simple and Easy to Learn:


Python is a simple programming language. When we read Python program, we can feel like
reading English statements.
The syntaxes are very simple and only 30+ key words are available.
When compared with other languages, we can write programs with very less number of lines.
Hence more readability and simplicity is obtained.
We can reduce development and cost of the project.
2. Freeware and Open Source:
We can use Python software without any license and it is freeware.
Its source code is open, so that we can customize it, based on our requirement. Eg: Jython is
customized version of Python to work with Java Applications.
3. High Level Programming Language:
Python is a high level programming language and hence, it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory
management and security etc..
4. Platform Independent:
Once we write a Python program, it can run on any platform, without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.
5. Portability:
Python programs are portable, i.e, we can migrate from one platform to another platform very
easily. Python programs will provide same results on any platform.
6. Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are assigning the value,
based on value, type will be allocated automatically. Hence Python is considered as dynamically
typed language.
But Java, C, etc. are Statically Typed Languages because we have to provide type of the variable
at the beginning only.
This dynamic typing nature will provide more flexibility to the programmer.
7. Both Procedure Oriented and Object Oriented:
Python language supports both Procedure oriented (like C, Pascal etc) and object oriented (like
C++, Java) features. Hence we can get benefits of both, like security and reusability.
8. Interpreted:
We are not required to compile Python programs explicitly. Internally, the Python Interpreter
will take care that compilation.
If compilation fails, the interpreter raises syntax errors. Once compilation is successful, then
Python’s Virtual Machine (Dalvik Virtual Machine) is responsible to execute.
9. Extensible:
We can use other language programs in Python. The main advantages of this approach are:
1. We can use already existing legacy non- Python code.
2. We can improve performance of the application.
10. Embedded:
We can use Python programs in any other language programs, i.e. we can embed Python
programs anywhere.
11. Extensive Library:
Python has a rich In- Built Library.
Being a programmer, we can use this library directly and we are not responsible to implement
the functionality.

Q.7.) Explain any 4 Built- In Numeric Data- Types in Python. (4


Marks) Ans.)
 Python Data Types are used to define the type of a variable.
 Data types refer to the types of values that can be stored and manipulated in a program. Every
value in Python has a data type, which determines what operations can be performed on it
and how it is stored in memory.
 Each data type has its own set of operations and methods that can be used to manipulate the
data. Understanding the data types in Python is essential for writing efficient and effective
code.
 In Python, there are several Numeric Data Types that can be used to represent numbers. These
include:
 Integer (int):
This data type represents whole numbers, both positive and negative, without a decimal
point. For example, 1, -5, and 0 are all integers.
 Float:
This data type represents real numbers, with a decimal point. For example, 3.14 and -2.5
are floats.
 Complex:
This data type represents complex numbers, which are numbers with both a real and
imaginary component. Complex numbers are expressed in the form of a+bj, where a is the
real part, b is the imaginary part, and j is the square root of -1.
 Booleans (bool):
Booleans are logical values that represent True or False. In Python, the bool data type is
used to represent 5ooleans. For example, the expression 1 < 2 evaluates to True, while
3
== 5 evaluates to False.
Q.8.) Write the Steps to install Python, and run the Python Code. (4 Marks)
Ans.)
To install Python and run Python code, follow these steps:
1.) Download the latest version of Python from the official website:
https://www.python.org/downloads/
2.) Click on the download button for the version you want to download.
3.) Open the downloaded file and run the installer.
4.) Follow the installation instructions on the screen, including selecting the appropriate
installation location, and checking the box to add Python to your system path.
5.) Once the installation is complete, open a terminal or command prompt and type “python”
to verify that the installation was successful. This should launch the Python interpreter.
6.) To run a Python script, open a text editor and write your Python code. Save the file with a
.py extension.
7.) Open a terminal or command prompt and navigate to the directory where you saved your
Python file.
8.) Type “python <filename.py>” to run the code. Replace “<filename.py>” with the name of
your Python file.
9.) Press enter and your Python code will run in the terminal.
10.) Alternatively, you can also use an integrated development environment (IDE) such as
PyCharm, Visual Studio Code or IDLE to write and run your Python code. These
environments provide a more user-friendly interface for working with Python code.

Q.9.) Explain Data- Types available in Python, with an Example. (4 Marks)


Ans.)
In Python, there are several built-in data types that can be used to represent different kinds of
values. Here are some of the most commonly used data types:
 Integer (int):- This data type is used to represent whole
numbers. For example: x = 5
 Float:- This data type is used to represent decimal
numbers. For example: y = 3.14
 Boolean (bool):- This data type is used to represent true or false
values. For example: z = True
 String (str) – This data type is used to represent
text. For example: name = “John”
 List – This data type is used to represent a collection of
values. For example: my_list = [1, 2, 3, 4, 5]
 Tuple – This data type is similar to a list but it is immutable, meaning it cannot be
changed once created.
For example: my_tuple = (1, 2, 3, 4, 5)
 Dictionary – This data type is used to represent key-value pairs.
For example: my_dict = {“name”: “John”, “age”: 30, “city”: “New York”}
 Set – This data type is used to represent a collection of unique
values. For example: my_set = {1, 2, 3, 4, 5}
These are just a few examples of the many data types available in Python. Each data type has its
own unique properties and uses, and choosing the right data type for your program is important
for efficient and effective programming.
Q.10.) Write the Output of the following, if the variable fruit= “banana”. (4 Marks)
>>> fruit[:3]
>>>fruit[3:]
>>>fruit[3:3]
>>>fruit[:]
Ans.)
 The output for each of the following expressions, given that fruit=”banana”, would
be: fruit[:3]
‘ban’
 This expression would return the first three characters of the string “banana”, which are
‘b’, ‘a’, and ‘n’.
fruit[3:]
‘ana’
 This expression would return all characters of the string “banana” starting from the fourth
character, which are ‘a’, ‘n’, and ‘a’.
fruit[3:3]
‘’
 This expression would return an empty string since the starting index is the same as
the ending index.
Fruit[:]
‘banana’
This expression would return the entire string “banana” since no specific index range is
specified.

Chapter- 2:- Python Operators and Control Flow Statements


Q.1.) List the Identity Operators in Python. (2
Marks) Ans.)
There are two Identity Operators in Python:
is: Returns True if both variables are the same object.
is not: Returns True if both variables are not the same object.
Code:-
x = [1, 2, 3]
y = [1, 2, 3]
z=x
print(x is y) # False - x and y have the same value, but they are not the same object
print(x is z) # True - x and z are the same object
print(x is not y) # True - x and y are not the same object
Output:-
Jupyter Notebook:-

Q.2.) Mention the use of Floor Division (//), Exponential Operator (**), and Modulo Operator
(%). (2 Marks)
Ans.)
1.) Floor Division (//):
The floor division operator in Python is represented by //. It returns the integer quotient of
dividing the left operand by the right operand. Unlike the regular division operator /, the
result of floor division is always rounded down to the nearest integer. This operator is useful
when you want to find how many times one number fits into another without considering the
remainder.
Example:
10 // 3 # Output: 3
2.) Exponential Operator (**):
The exponential operator in Python is represented by **. It raises the left operand to the
power of the right operand. This operator is useful when you want to perform calculations
involving exponents.
Example:
2 ** 3 # Output: 8
3.) Modulo Operator (%):
The modulo operator in Python is represented by %. It returns the remainder of dividing the
left operand by the right operand. This operator is useful when you want to perform
operations that involve finding the remainder of a division.
Example:
10 % 3 # Output: 1

Q.3.) Explain Relational Operators in Python. (2 Marks)


Ans.)
In Python, relational operators are used to compare two values or expressions and return a
Boolean value (True or False) depending on the result of the comparison. These operators are
used to establish relationships between different values or expressions. The following are the
relational operators in Python:
1.) Equality Operator (==): It is used to check whether two values are equal or not. If the
values are equal, it returns True, otherwise False.
Example:
x=5
y = 10
print(x == y) # Output: False
z=5
print(x == z) # Output: True
2.) Not Equal Operator (!=): It is used to check whether two values are not equal. If the values
are not equal, it returns True, otherwise False.
Example:
x=5
y = 10
print(x != y) # Output: True
z=5
print(x != z) # Output: False

3.) Greater Than Operator (>): It is used to check whether the first value is greater than the
second value. If the first value is greater than the second value, it returns True, otherwise
False.
Example:
x=5
y = 10
print (y > x) # Output: True
z=5
print (y > z) # Output: True

4.) Less Than Operator (<): It is used to check whether the first value is less than the second
value. If the first value is less than the second value, it returns True, otherwise False.
Example:
x=5
y = 10
print (x < y) # Output: True
z=5
print (z < y) # Output: True

5.) Greater Than or Equal To Operator (>=): It is used to check whether the first value is
greater than or equal to the second value. If the first value is greater than or equal to the
second value, it returns True, otherwise False.
Example:
x=5
y = 10
print(y >= x) # Output: True
z=5
print(x >= z) # Output: True

6.) Less Than or Equal To Operator (<=): It is used to check whether the first value is less
than or equal to the second value. If the first value is less than or equal to the second value, it
returns True, otherwise False.
Example:
x=5
y = 10
print(x <= y) # Output: True
z=5
print(z <= x) # Output: True
Q.4.) Explain Building Blocks of Python. (4
Marks) Ans.)
In Python, the basic building blocks are:
1.) Variables:
These are containers that hold values, such as numbers or text strings. In Python, you
don't need to specify the type of a variable; the type is inferred based on the value it holds.
2.) Data Types:
Python has several built-in data types, including integers, floating-point numbers, strings,
lists, tuples, and dictionaries. Each data type has its own set of methods and functions
that you can use to manipulate the data.
3.) Operators:
These are symbols or words that perform operations on values or variables. Python has
arithmetic operators (such as +, -, *, and /), comparison operators (such as ==, !=, <, and >),
and logical operators (such as and, or, and not).
4.) Control Structures:
These are constructs that allow you to control the flow of your program. Python has if/else
statements, for and while loops, and try/except blocks for error handling.
5.) Functions: These are reusable blocks of code that perform a specific task. You can define
your own functions in Python or use built-in functions from the standard library.
6.) Modules:
These are files that contain Python code that you can import into your own programs.
Python has a large standard library of modules for tasks such as file I/O, networking, and
web development.
7.) Classes and Objects:
These are constructs for creating own data types and functions that operate on them.
Python is an object-oriented language, so everything in Python is an object.

Q.5.) Explain Membership and Assignment Operators, with Examples. (4 Marks)


Ans.)
Membership Operators: Python has two membership operators: in and not in. They are used to
check whether a value is present in a sequence (like a list, tuple, set, or string).
 in: It returns True if a value is present in a sequence.
 not in: It returns True if a value is not present in a sequence.
Example:
fruits = ['apple', 'banana',
'orange'] if 'banana' in fruits:
print("Yes, banana is in the fruit
list.") if 'pear' not in fruits:
print("Yes, pear is not in the fruit list.")

Output:
Yes, banana is in the fruit list.
Yes, pear is not in the fruit
list.
Assignment Operators:- Assignment operators are used to assign values to variables. These
operators are a combination of the equal sign (=) and another arithmetic or bitwise operator. The
resulting value is then assigned to the variable on the left-hand side of the operator.
Here are some examples of assignment operators in Python:
1.) Addition Assignment Operator (+=): The addition assignment operator adds the value on
the right-hand side to the value on the left-hand side and assigns the result to the left-hand
side variable.
Example:-
x=5
x += 3 # equivalent to x = x + 3
print(x) # Output: 8
2.) Subtraction Assignment Operator (-=): The subtraction assignment operator subtracts the
value on the right-hand side from the value on the left-hand side and assigns the result to the
left-hand side variable.
Example:-
x = 10
x -= 4 # equivalent to x = x - 4
print(x) # Output: 6
3.) Multiplication Assignment Operator (*=): The multiplication assignment operator
multiplies the value on the left-hand side by the value on the right-hand side and assigns the
result to the left-hand side variable.
Example:-
x=2
x *= 5 # equivalent to x = x * 5
print(x) # Output: 10
4.) Division Assignment Operator (/=): The division assignment operator divides the value on
the left-hand side by the value on the right-hand side and assigns the result to the left-hand
side variable.
Example:-
x = 20
x /= 4 # equivalent to x = x / 4
print(x) # Output: 5.0
5.) Modulus Assignment Operator (%=): The modulus assignment operator finds the
remainder of the division of the value on the left-hand side by the value on the right-hand
side and assigns the result to the left-hand side variable.
Example:-
x = 17
x %= 5 # equivalent to x = x % 5
print(x) # Output: 2
6.) Exponentiation Assignment Operator (**=): The exponentiation assignment operator
raises the value on the left-hand side to the power of the value on the right-hand side
and assigns the result to the left-hand side variable.
Example:-
x=3
x **= 4 # equivalent to x = x ** 4
print(x) # Output: 81
7.) Floor Division Assignment Operator (//=): The floor division assignment operator divides
the value on the left-hand side by the value on the right-hand side and returns the floor of
the quotient. The result is then assigned to the left-hand side variable.
Example:-
x = 23
x //= 4 # equivalent to x = x // 4
print(x) # Output: 5
These assignment operators are useful for reducing the amount of code needed to perform
common operations on variables.

Q.6.) Explain Decision Making Statements- If- Else (4 Marks)


- If- Elif- Else
Ans.)
In Python, decision-making statements are used to execute different blocks of code based on
certain conditions. Two commonly used decision-making statements in Python are the "if-else"
and "if-elif-else" statements.

1.) If-Else Statement:


The "if-else" statement allows you to execute a block of code if a condition is true, and another
block of code if the condition is false. Here is the general syntax of the "if-else" statement:
if condition:
# code to execute if the condition is
true else:
# code to execute if the condition is false

2.) If-Elif-Else Statement:


The "if-elif-else" statement allows you to test multiple conditions and execute different blocks
of code based on the condition that is true. Here is the general syntax of the "if-elif-else"
statement:
if condition1:
# code to execute if condition1 is
true elif condition2:
# code to execute if condition2 is
true elif condition3:
# code to execute if condition3 is true
...
else:
# code to execute if all conditions are false
Q.7.) Write a Python Program to print the entered number id Prime Number or not. (4 Marks)
Ans.)
num = int(input("Enter a number: "))
is_prime = True
if num <= 1:
is_prime =
False
else:
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime =
False break
if is_prime:
print(f"{num} is a prime
number") else:
print(f"{num} is not a prime number")

Here's how the program works:


1.) The user is asked to enter a number, which is then converted to an integer using the int()
function and stored in the variable num.
2.) A Boolean variable is_prime is initialized to True.
3.) If the entered number num is less than or equal to 1, it cannot be a prime number, so
is_prime is set to False.
4.) Otherwise, a for loop is used to iterate over all the numbers from 2 to the square root of num
(inclusive) using the range() function. Note that we only need to check up to the square root
of num because if num has a factor greater than its square root, then it must also have a
factor smaller than its square root.
5.) For each number in the range, the program checks if num is divisible by that number using
the modulo operator (%). If num is divisible by any number in the range, then it is not a
prime number and is_prime is set to False. The loop is also broken using the break keyword
since we have already found a factor of num.
6.) Finally, the program checks the value of is_prime. If it is True, then the entered number num
is a prime number, and a message is printed saying so. Otherwise, the entered number is not
a prime number, and a different message is printed.
Q.8.) Write a Python Program to print Fibonacci Series of “n” terms. (4 Marks)
Ans.)
n = int(input("Enter the number of terms:
")) # Initializing the first two terms
a, b = 0, 1
# First check if n is less than or equal to
0 if n <= 0:
print("Please enter a positive integer")
# If n is equal to 1, print only the first
term elif n == 1:
print("Fibonacci sequence upto", n, ":")
print(a)
# For n greater than
1 else:
print("Fibonacci sequence:")
for i in range(n):
print(a, end='
') c = a + b
# update
values a = b
b=c

This program first takes the input of the number of terms 'n' from the user. It then initializes the
first two terms of the sequence as 'a' and 'b', which are 0 and 1 respectively. Then it checks if the
input value of 'n' is positive or not, and if it's equal to or greater than 1.

Finally, it prints the Fibonacci sequence by iterating through the range of 'n' terms, and updating
the values of 'a' and 'b' at each iteration.

Q.9.) Explain different Loops available in Python, with suitable Example. (4 Marks)
Ans.)
In Python, loops are used to execute a block of code repeatedly until a specific condition is met.
There are two main types of loops in Python: for and while.

1.) For Loop


A for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a
block of code for each item in the sequence. Here is the basic syntax for a for loop in Python:
for variable in
sequence: # code to
be executed
The variable represents the current item in the sequence, and the code inside the loop is
executed once for each item in the sequence.
Example:-
fruits = ["apple", "banana",
"cherry"] for fruit in fruits:
print(fruit)
Output:-
apple
banana
cherry
2.) While Loop
A while loop is used to execute a block of code repeatedly as long as a specific condition is
true. Here is the basic syntax for a while loop in Python:
while condition:
# code to be executed
The code inside the loop will be executed repeatedly until the condition becomes false.
Example:-
i=0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
3.) Nested Loops
Python also allows you to nest one loop inside another loop. This can be useful for iterating
over nested data structures like lists of lists.
Example:-
for i in range(1, 11):
for j in range(1, 11):
print(i, "*", j, "=",
i*j) print()
Output:-
This will print all the Multiplication Tables from 1 to 10.

Q.10.) List the Loop Manipulation Statements in Python, and explain any 2 in detail. (4 Marks)
Ans.)
In Python, loop manipulation statements are used to control the execution of loops. There are
three main loop manipulation statements in Python:
1.) Break:- The break statement is used to exit a loop prematurely. When executed inside a
loop, it immediately terminates the loop and control flows to the statement following
the loop. For Example:
for i in range(1, 11):
if i == 6:
break
print(i)
Output:
12 3 4 5
2.) Continue
The continue statement is used to skip the current iteration of a loop and move on to the next
iteration. For Example:
for i in range(1, 11):
if i == 6:
continue
print(i)
Output:
1 2 3 4 5 7 8 9 10
3.) Pass
The pass statement is used as a placeholder when a statement is required syntactically but
you don’t want to execute any code. For Example:
for i in range(1, 11):
if i == 6:
pass
else:
print(i)
Output:
1 2 3 4 5 7 8 9 10
Note:- In this example, the pass statement does nothing, but it’s required syntactically to
create a valid if/else block.

You might also like