0% found this document useful (0 votes)
45 views32 pages

Unit-2 Important Questions

The document outlines various concepts related to Python programming, including types of operators, control flow statements, variable scope, and the differences between data structures like tuples and dictionaries. It explains the syntax and functionality of control statements such as if, for, and while loops, as well as the use of break and continue statements. Additionally, it covers type conversion, assignment types, and provides examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views32 pages

Unit-2 Important Questions

The document outlines various concepts related to Python programming, including types of operators, control flow statements, variable scope, and the differences between data structures like tuples and dictionaries. It explains the syntax and functionality of control statements such as if, for, and while loops, as well as the use of break and continue statements. Additionally, it covers type conversion, assignment types, and provides examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT-2

2MARKS

1. What are the types of operators in Python?


Types of Python Operators
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
Bitwise Operators

2. Define control flow statement


 Control statements: which controls the flow of execution
 Control statements in Python are used to manage the flow of execution of a program
based on certain conditions.
 Control statements in Python are a powerful tool for managing the flow of execution.
 They allow developers to make decisions based on specific conditions and modify the
normal sequential flow of a program.

3. Discover the difference between logical and bitwise operator.


 Logical operators (and, or, not) are used to perform logical operations on boolean
values (True or False). They evaluate expressions and return a boolean result.

 Bitwise operators (&, |, ^, ~, <<, >>) operate on the binary representation of


integers. They perform bit-by-bit operations, altering individual bits in binary
representations of integers.

4. Give the operator precedence in python.


 Operator precedence determines the order in which operators are evaluated in
expressions.

 Parentheses have the highest precedence, followed by exponentiation (**), then


multiplication, division, and remainder (*, /, %), then addition and subtraction (+, -),
and so on.

5. Define the scope and lifetime of a variable in python.


 Scope refers to the region of code where a variable is accessible.
 Lifetime refers to the duration for which a variable exists in memory during program
execution.
 Python variables have local, global, and built-in scopes.
 Local variables are accessible only within the function where they are defined.
 Global variables are accessible throughout the entire program.
 The lifetime of a local variable is limited to the function call in which it is defined.
 Global variables persist throughout the program's execution.

6. Write the syntax of if and if-else statements.


Syntax of if statement:
if condition:
# code block
Syntax of if-else statement:
if condition:
# code block
else:
# code block

7. Discuss about continue and break statements.


 continue: Skips the rest of the current loop iteration and continues to the next
iteration.
 break:The break statement is used to exit or terminate the loop when a certain
condition is met.

8. Name the type of Boolean operators.


 Membership operator
 Comparison operator
 Logical operator

9. Differentiate for loop and while loop.


For Loop:
 A for loop is used for iterating over a sequence (such as a list, tuple, string, etc.) or an
iterable object.
 It executes a block of code repeatedly for each item in the sequence.
 The loop variable iterates over each item in the sequence automatically, making it
convenient for iterating through elements.
 The loop terminates when all items in the sequence have been processed.
 It is preferred when the number of iterations is known or when iterating over a
collection.

While Loop:
 A while loop is used to repeatedly execute a block of code as long as a specified
condition is true.
 It continues iterating as long as the condition remains true, and terminates when the
condition becomes false.
 The loop condition is checked before each iteration, so it's possible that the loop may
not execute at all if the condition is initially false.
 It is useful when the number of iterations is not known beforehand or when the loop
needs to continue until a certain condition is met.

10. Classify global variable with local variable


Global Variables:
 Global variables are defined outside of any function or class definition.
 They are accessible from anywhere within the program, including inside functions,
classes, or other modules.
Local Variables:
 Local variables are defined within a function or a block of code (such as a loop or an
if statement).
 They are accessible only within the function or block where they are defined.

11. What are the advantages of tuple over list?


 Immutable
 Faster access
 safe for hashing
 sequence packing and unpacking
 useful for fixed collection
 performance in parallel assignments
12. Differentiate between tuples and dictionaries.
Purpose:
 Tuples are used to store a collection of ordered elements, typically of different types,
where the order and values are important. Tuples are immutable, meaning their
elements cannot be changed after creation.
 Dictionaries are used to store key-value pairs, where each value is associated with a
unique key. Dictionaries are mutable, meaning their key-value pairs can be modified
after creation.

Syntax:
 Tuples are enclosed in parentheses () and contain a comma-separated sequence of
elements.
 Dictionaries are enclosed in curly braces {} and consist of key-value pairs separated
by colons :. Each key-value pair is separated by commas.

Accessing Elements:
 Tuples are accessed using indexing or slicing, similar to lists. Elements are accessed
by their position in the tuple.
 Dictionaries are accessed using keys. Values are retrieved by specifying the
corresponding key.

Order:
 Tuples maintain the order of elements as they are inserted. The order of elements in a
tuple is fixed and preserved.
 Dictionaries do not guarantee any specific order for their key-value pairs. The order of
elements in a dictionary may vary and is not guaranteed to be the same as the order in
which they were inserted.

Mutability:
 Tuples are immutable, meaning their elements cannot be changed, added, or removed
after creation. Once a tuple is created, it cannot be modified.
 Dictionaries are mutable, meaning their key-value pairs can be modified after
creation. Key-value pairs can be added, removed, or updated as needed.
Use Cases:
 Tuples are often used for fixed collections of data, such as coordinates, RGB color
values, or as return values from functions that return multiple values.
 Dictionaries are commonly used to represent mappings between keys and values, such
as in databases, configuration settings, or any scenario where data retrieval by a
unique identifier is required.

13. What is type conversion?


TYPE CONVERSION
 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

Implicit Type Conversion


The type conversion that is done automatically done by the compiler is known as implicit
type conversion.

Explicit Conversion
When the user manually changes data from one type to another, this is known as explicit
conversion. This type of conversion is also known as type casting.

14. What is type comparison in python?


Comparing the type of data

Example program
>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

15. What is statements and assignments


Assignment
 Assignment operators are used to assigning values to the operands on the left-hand
side.
 Assignment operators assign the right-hand side values to the operand that is present
on the left-hand side.
 The assignment operator in Python is used as the "=" symbol.

Example,
 X = 5 Y = b-c
Statements
 Any instruction written in the source code and executed by the Python interpreter is
called a statement.
 The Python language has many different types of statements like assignment
statements, conditional statements, looping statements, etc., that help a programmer
get the desired output.

16. What are the different types of assignments in python


 Single assignment
 Augmented assignment
 Multiple assignment
 Chained assignment
 Unpacking assignment
17. “Tuples are immutable”. Explain with Examples.
Immutable means that once a tuple is created, its elements cannot be changed, added, or
removed.

10Marks

1. Explain the control statement or control structures in python?


Control statements in Python are used to manage the flow of execution of a program
based on certain conditions.

Decision making or selection or conditional statement


 Decision-making statements are also known as conditional statements because
they specify conditions with boolean expressions evaluated to a true or false boolean
value.
 If the condition is true, the block will execute; if the condition is false, the block will
not execute.

Looping or iteration statement:


Looping is the process of repeating something until a specific condition is met.
Jump statement
A jump statement is used to break the normal flow of the program and jump onto a specific
line of code in the program if the specific condition is true.

Python if Statement
An if statement executes a block of code only if the specified condition is met.

Syntax
if condition:
# body of if statement

Here, if the condition of the if statement is:


 True - the body of the if statement executes.
 False - the body of the if statement is skipped from execution.
 Flow chart:

Example program
x = int(input('Enter a value for a: '));
y = int(input('Enter a value for b: '));
if(x>y):
print("A is greater than B");
print("if ends...");

Python if...else Statement


 An if statement can have an optional else clause.
 The else statement executes if the condition in the if statement evaluates to False.

Syntax
if condition:
# body of if statement
else:
# body of else statement
Here, if the condition inside the if statement evaluates to
 True - the body of if executes, and the body of else is skipped.
 False - the body of else executes, and the body of if is skipped
Flow chart
Example program
x = int(input('Enter a value for a: '));
y = int(input('Enter a value for b: '));
if(x>y):
print("A is greater than B");
else:
print("B is greater than A");

Python if…elif…else Statement


 The if...else statement is used to execute a block of code among two alternatives.
 However, if we need to make a choice between more than two alternatives, we use the
if...elif...else statement.

Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

Here,
 if condition1 - This checks if condition1 is True. If it is, the program executes code
block 1.
 elif condition2 - If condition1 is not True, the program checks condition2. If
condition2 is True, it executes code block 2.
 else - If neither condition1 nor condition2 is True, the program defaults to executing
code block 3.
Flow chart

Example program
per = float(input('Enter Your Percentage: '));
if((per>=90)and(per<=100)):
print("Grade: S");
elif((per>=80)and(per<=90)):
print("Grade: A");
elif((per>=70)and(per<=80)):
print("Grade: B");
elif((per>=60)and(per<=70)):
print("Grade: C");
elif((per>=50)and(per<=60)):
print("Grade: D");
elif((per>=40)and(per<=50)):
print("Grade: E");
else:
print("Fail");
Python Nested if Statements
It is possible to include an if statement inside another if statement.

Syntax
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Flow chart:

Example program
a = int(input('Enter a value for a: '));
b = int(input('Enter a value for b: '));
c = int(input('Enter a value for c: '));
if (a>b):
if(a>c):
print("A is greater");
else:
print("C is greater");
if(b>a):
if(b>c):
print("B is greater");
else:
print("C is greater");

Iteration statement
Python for Loop
In Python, a for loop is used to iterate over sequences such as lists, strings, tuples, etc.

for loop Syntax


for val in sequence:
# statement(s)

 Here, val accesses each item of the sequence on each iteration.


 The loop continues until we reach the last item in the sequence.

Flow chart

Example program
language = ['A','B','C','D','E'];
for i in language:
print(i);
For Loop with Python range()
 In Python, the range() function returns a sequence of numbers. For example,
 values = range(4)
 Here, range(4) returns a sequence of 0, 1, 2 ,and 3.
 Since the range() function returns a sequence of numbers, we can iterate over it using
a for loop.

Example program
for i in range(10):
print(i);

Python while Loop


In Python, we use the while loop to repeat a block of code until a certain condition is met.

while Loop Syntax


while condition:
# body of while loop

Here,
 The while loop evaluates the condition.
 If the condition is true, body of while loop is executed. The condition is evaluated
again.
 This process continues until the condition is False.
 Once the condition evaluates to False, the loop terminates.
Flow chart
Example program
num = int(input('Enter a value: '));
i=0;
while(i<=num):
print(i);
i=i+1;

Python break and continue

In programming, the break and continue statements are used to alter the flow of loops:
 break exits the loop entirely
 continue skips the current iteration and proceeds to the next one.

Python break Statement

The break statement terminates the loop immediately when it's encountered.
Syntax
Break
Flow chart
Example Program
num = int(input('Enter a value: '));
i=0;
while(i<=num):
print(i);
if(i==4):
break;
i=i+1;

Python continue Statement


The continue statement skips the current iteration of the loop and the control flow of the
program goes to the next iteration.

Syntax
continue

Flow chart
Example program
for i in range(10):
if i == 3:
continue;
print(i);

Python pass Statement

 In Python programming, the pass statement is a null statement which can be used as a
placeholder for future code.
 Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. In such cases, we can use the pass statement.

The syntax of the pass statement is:


Pass

Example program
for i in range(10):
if i == 3:
pass;
print(i);

2. Describe the following


a) Creating the List
b) Accessing values in the Lists
c) Updating the Lists
d) Deleting the list Elements
3. Describe the following
e) Creating the tuple
f) Accessing values in the tuple
g) Updating the tuple
h) Deleting the tuple Elements
4. Describe the following
i) Creating the set
j) Accessing values in the set
k) Updating the set
l) Deleting the set Elements
5. Describe the following
m) Creating the dictionary
n) Accessing values in the dictionary
o) Updating the dictionary
p) Deleting the dictionary Elements

Answer:
6. Explain in detail about the various operators in python with suitable examples.
Operators are special symbols that perform operations on variables and values.

Types of Python Operators


 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators

Python Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2 * 3 = 6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
Example program:(Arithmetic operator)
num1 = int(input('Enter a value for a: '));
num2 = int(input('Enter a value for b: '));
print("Arithmetic Operator");
print("\n The addition of a and b: ",num1+num2);
print("\n The subtraction of a and b: ",num1-num2);
print("\n The multiplication of a and b: ",num1*num2);
print("\n The division of a and b: ",num1/num2);

Python Assignment Operators


Assignment operators are used to assign values to variables.
Operator Name Example
= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10
Example program: (Assignment operator)
num1 = int(input('Enter a value for a: '));
num2 = int(input('Enter a value for b: '));
print("Assignment Operator");
print("\n");
num1+=num2;
print("\n The addition of a and b: ",num1);
num1-=num2
print("\n The subtraction of a and b: ",num1);
num1*=num2
print("\n The multiplication of a and b: ",num1);
num1/=num2; print("\n The division of a and b: ",num1);

Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or
False.

Operator Meaning Example


== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True

Example program(comparison operator)


num1 = int(input('Enter a value for a: '));
num2 = int(input('Enter a value for b: '));
print("relational Operator");
print("\n");
print("\n The greater than (a>b): ",num1>num2);
print("\n The less than (a<b): ",num1<num2);
print("\n The Equal to (a==b): ",(num1==num2));
print("\n The Not Equal to (a!=b): ",(num1!=num2));

Python Logical Operators


 Logical operators are used to check whether an expression is True or False.
 They are used in decision-making.
Operator Example Meaning
and a and b Logical AND:True only if both the operands are True
or a or b Logical OR:True if at least one of the operands is True
not not a Logical NOT:True if the operand is False and viceversa.

Example program(Logical operator)


num1 = int(input('Enter a value for a: '));
num2 = int(input('Enter a value for b: '));
print("Logical Operator");
print("\n");
print("\n The greater than (a>b)&&(a==b): ",((num1>num2)and(num1==num2)));
print("\n The less than (a>b)||(a==b): ",((num1>num2)or(num1==num2)));
print("\n The Equal to !(a>b): ",(not(num1>num2)));

Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by
bit, hence the name.

Operator Meaning Example


& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)

Example program(Bitwise operator)


num1 = int(input('Enter a value for a: '));
num2 = int(input('Enter a value for b: '));
print("Bitwise Operator");
print("\n");
print("\n (num1 & num2: ",(num1&num2));
print("\n num1 | num2: ",(num1|num2));
print("\n (~num1): ",(~num1));
Python Special operators
Python language offers some special types of operators like the identity operator and the
membership operator.

Identity operators

 In Python, is and is not are used to check if two values are located at the same
memory location.
 It's important to note that having two variables with equal values doesn't necessarily
mean they are identical.

Operator Meaning Example


is True if the operands are identical x is True
is not True if the operands are not identical )x is not True

Example program:
x = 10;
a = 10;
y = '10';
b = '20';
z = "JAYAM";
c = "jayam"

print("Identity Operator");
print("\n");
print(x is not a);
print(x is a);
print(y is not b);
print(y is b);
print(z is not c);
print(z is c);
Output:
False
True
True
False
True
False

Membership operators

 In Python, in and not in are the membership operators. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
 In a dictionary, we can only test for the presence of a key, not the value.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example program
print('H' in "Hello");
print('w' in "Welcome");
print('h' not in "hello");

7. Explain the file concepts in python


a. File opening
b. Reading the content
c. Writing the content
d. Closing the file
Python File Operation
 A file is a named location used for storing data.
 For example, main.py is a file that is always used to store Python code.
 Python provides various functions to perform different file operations, a process
known as File Handling.
Opening Files in Python
In Python, we need to open a file first to perform any operations on it—we use the open()
function to do so.

Example
 Suppose we have a file named file1.txt.
 To open this file, we can use the open() function.
file1 = open("file1.txt")

Reading Files in Python


After we open a file, we use the read() method to read its content.

For example,
Suppose we have a file named file1.txt.

# open a file in read mode


file1 = open("file1.txt",’r’)

# read the file content


read_content = file1.read()
print(read_content)

Output
This is a test file.
Hello from the test file.

Writing to Files in write mode Python


 To write to a Python file, we need to open it in write mode using the w parameter.
 Suppose we have a file named file2.txt. Let's write to this file.
Example
# open the file2.txt in write mode
file2 = open('file2.txt', 'w')
# write contents to the file2.txt file
file2.write('Programming is Fun.\n')
file2.write('Programiz for beginners\n')

Writing to file in append mode


# open the file2.txt in append mode
file2 = open('file2.txt', 'a')
# write contents to the file2.txt file
file2.write('Programming is Fun.\n')
file2.write('Programiz for beginners\n')

Closing Files in Python


 When we are done performing operations on the file, we need to close the file
properly.
 We use the close() function to close a file in Python.

For example,
# open a file
file1 = open("file1.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

Output
This is a test file.
Hello from the test file.
8. Compare the python object with other language.
1. Comparison of Python with Other Programming Languages
 Python is an easily adaptable programming language that offers a lot of features.
 Its concise syntax and open-source nature promote readability and implementation of
programs which makes it the fastest-growing programming language in current times.
 Python has various other advantages which give it an edge over other popular
programming languages such as Java and C++.

2. Python vs Java
 In Python there is no need for semicolon and curly braces in the program as compared
to Java which will show syntax error if one forgot to add curly braces or semicolon in
the program.
 Python code requires fewer lines of code as compare to Java to write the same
program.
 For Example, Here is a code in Java

public class PythonandJava {


public static void main(String[] args)
{
System.out.println("Python and Java!");
}
}
Output:
Python and Java!

Same code written in Python


print("Python and Java !")
Output:
Python and Java!
 Python is dynamically typed that means one has to only assign a value to a variable at
runtime, Python interpreter will detect the data type on itself as compare to Java
where one has to explicitly mention the data type.

 Python supports various type of programming models such as imperative, object-


oriented and procedural programming as compare to Java which is completely based
on the object and class-based programming models.

 Python is easy to read and learn which is beneficial for beginners who are looking
forward to understanding the fundamentals of programming quickly as compare to
Java which has a steep learning curve due to its predefined complex syntaxes.

 Python concise syntax makes it a much better option for people of other disciplines
who want to use programming language for data mining, neural processing, Machine
Learning or statistical analysis as compare to Java syntax which is long and hard to
read.

 Python is free and open-source means its code is available to the public on
repositories and it is free for commercial purposes as compare to Java which may
require a paid license to be used for large scale application development.

 Python code requires fewer resources to run since it directly gets compiled into
machine code as compare to Java which first compiles to byte code, then needs to be
compiled to machine code by the Java Virtual Machine(JVM).

3. Python vs C++
 Python is more memory efficient because of its automatic garbage collection as
compared to C++ which does not support garbage collection.

 Python code is easy to learn, use and write as compare to C++ which is hard to
understand and use because of its complex syntax.
 Python uses an interpreter to execute the code which makes it easy to run on almost
every computer or operating system. as compare to C++ code which does not run on
other computers until it is compiled on that computer.

 Python can be easily used for rapid application development because of its smaller
code size as compare to C++ which is impossible to use for rapid application
development because of it large code fragments.

 Readability of Python code is more since it resembles actual English as compared to


C++ code which contains hard to read structures and syntaxes.

 Variables defined in Python are easily accessible outside the loop as compare to C++
in which scope of variables is limited within the loop.

You might also like