QUESTION BANK OF PYTHON
Write a Python program to declare two complex numbers and perform addition and
multiplication on them. Print the real and imaginary parts of the results separately.
Write a Python program that rounds a given float number to two decimal places and prints
the result.
Write a Python program that takes two float numbers as input and performs basic arithmetic
operations (addition, subtraction, multiplication, and division). Print the results.
Write a Python program to declare an integer variable a, a float variable b, and a complex
variable c. Print their types and values.
Write a Python program that converts a given float number to an integer.
Then, print both the float and the converted integer value.
Write a Python program to swap the values of two variables without using a
temporary variable.
Declare three variables: a, b, and c, and assign them the values 10, 20, and
30, respectively. Print the sum of these variables.
Explain the concept of variables in Python. How are variables created, and
how does Python manage memory for them?
In Python, a variable is a name assigned to a value. Variables are used to
store and manipulate data in a program.
Creating Variables
In Python, variables are created using the assignment operator (=). The
syntax is:
variable_name = value
Example:
x = 5 # creates an integer variable x with value 5
y = "Hello" # creates a string variable y with value "Hello"
Types of Variables
Python has several built-in data types, including:
1. Integers (int)
2. Floats (float)
3. Strings (str)
4. Boolean (bool)
5. List (list)
6. Tuple (tuple)
7. Dictionary (dict)
Memory Management
Python uses a private heap to manage memory for variables. The memory
management process involves:
1. Memory Allocation: When a variable is created, Python allocates
memory for it from the private heap.
2. Reference Counting: Python uses reference counting to track the
number of references to a variable. When the reference count reaches
zero, the memory is deallocated.
3. Garbage Collection: Python's garbage collector periodically scans the
heap for unreachable objects and deallocates their memory.
Key Features
1. Dynamic Typing: Python variables do not have a fixed data type. The
data type is determined at runtime.
2. Mutable and Immutable: Variables can be mutable (e.g., lists,
dictionaries) or immutable (e.g., integers, strings).
3. Scope: Variables have scope, which defines their visibility and
accessibility within the program.
Variable Naming Conventions
1. Use meaningful and descriptive names.
2. Avoid using reserved words and built-in function names.
3. Use underscores instead of spaces.
4. Follow PEP 8 guidelines.
Example Code
What are the rules for naming a variable in Python? Give examples of valid
and invalid variable names.
Rules for Naming Variables in Python:
1. Variable names can contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
2. Variable names must start with a letter or underscore.
3. Variable names cannot start with a digit.
4. Variable names cannot contain special characters (!, @, #, $, etc.).
5. Variable names cannot be reserved words (e.g., if, else, for, while).
6. Variable names are case-sensitive.
7. Variable names should be unique.
Valid Variable Names:
1. x
2. hello_world
3. _var
4. myVariable
5. abc123
Invalid Variable Names:
1. 1variable (starts with digit)
2. hello! (contains special character)
3. if (reserved word)
4. variable@ (contains special character)
5. 123abc (starts with digit)
6. my variable (contains space)
7. __reserved__ (reserved for system use)
Additional Guidelines:
1. Use meaningful and descriptive names.
2. Avoid using single-letter variable names (except for loop counters).
3. Use underscores instead of camelCase.
4. Follow PEP 8 guidelines.
Explain the difference between local and global variables in Python. Provide
examples of how each is used.
Basis Local Variable Global Variable
Accessible only within - Accessible from
Scope the function or block anywhere in the program.
where they're defined.
Defined inside a Defined outside any
Declaration
function or block. function or block.
Created when the Retain their value
function is called, throughout the program's
Lifetime
destroyed when the execution.
function returns.
Can't be accessed from Can be accessed from
Accessibility outside the function or any part of the program.
block.
Can be modified within Can be modified from any
Modification the function or block. part of the program (using
global keyword).
Hide global variables Can be hidden by local
with the same name variables with the same
Name conflict
within the function or name.
block.
Initialized within the Initialized outside any
Initialization
function or block. function or block.
Suitable for function- Data persists throughout
Data persistence
specific data. the program.
Suitable for function- Suitable for shared data
Usage
specific data. across functions.
More secure since Less secure since access
Security
access is restricted. is unrestricted.
How it is used:
Describe the different types of operators in Python. Provide examples of
arithmetic, comparison, logical, and bitwise operators.
Python has various types of operators that perform specific operations on
variables and values. Here are the main categories:
1. Arithmetic Operators
Perform mathematical operations.
Operator Description Example
+ Add a+b
- Subtract a-b
* Multiply a*b
/ Division a/b
// Floor division a//b
% Modulus a%b
** Exponential a**b
Example:
2. Comparison Operators
Compare values and return a boolean result.
Operator Description Example
== Equal a==b
!= Not equal a!=b
> Greater than a>b
< Less than a<b
>= Greater than or equal a>=b
<= Less than or equal a<=b
Example:
3. Logical Operators
Perform logical operations on boolean values.
Operator Description Example
and Logical and a and b
or Logical or a and b
not Logical not not a
Example:
4. Bitwise Operators
Perform bit-level operations.
Operator Description Example
& Bitwise and a&b
|| Bitwise or a|b
^ Bitwise xor a^b
~ Bitwise not ~a
<< Left shift a<<b
>> Right shift a>>b
Example:
5. Assignment Operators
Assign values to variables.
Operator Description Example
= Assignment a=b
+= Add assignment a+=b
-= Subtraction Assignment a-=b
*= Multiplication Assignment a*=b
/= Division Assignment a/=b
Example:
6. Membership Operators
Check membership in sequences.
Operator Description Example
In Membership a in b
not in Non-membership a not in b
Example:
7. Identity Operators
Check object identity.
Operator Description Example
is Identity a is b
is not Non-identity a is not b
Example:
What is the difference between the “==” operator and the “is” operator in
Python? When would you use each?
Basis ==(Equal operator) is(identity operator)
Checks if the values of - Checks if both
Purpose two variables are variables point to the
equal. same object in memory.
Syntax a == b a is b
Compares identities
Comparison Compares values.
(memory locations).
Works with all data
Works with all data
Data type types, but most useful
types.
with mutable objects.
Returns True if both
Returns True if
Mutable concept variables point to the
contents are equal.
same object
May return True or
Returns True if values
Immutable objects False, depending on
are equal.
optimization.
Does not consider Checks memory
Memory allocation
memory allocation. allocation.
Faster for simple data Faster for complex
Performance
types. objects.
Use for value Use for object identity
Usage
comparisons. checks.
Explain the concept of operator precedence and associativity in Python.
How do they affect the evaluation of expressions?
Operator precedence and associativity determine the order in which
operators are evaluated in an expression.
Operator Precedence:
Precedence defines the priority of operators. Higher precedence operators
are evaluated first.
Python Operator Precedence (Highest to Lowest):
1. Parentheses ()
2. Exponentiation **
3. Unary operators +, -, ~, not
4. Multiplication, Division, Modulus *, /, //, %
5. Addition, Subtraction +, -
6. Comparison operators ==, !=, >, <, >= , <=
7. Logical operators and, or, not
8. Assignment operators =, +=, -= , *= , /= , //= , %= , etc.
Operator Associativity:
Associativity defines the direction in which operators with the same
precedence are evaluated.
Python Operator Associativity:
1. Left-to-Right (LTR): +, -, *, /, //, %, ==, !=, >, <, >= , <=
2. Right-to-Left (RTL): **, =, +=, -= , *= , /= , //= , %= , etc.
Example:
2+3*4
1. Multiplication has higher precedence than addition.
2. Evaluate 3 * 4 first: 3 * 4 = 12
3. Then, evaluate 2 + 12: 2 + 12 = 14
Result: 14
Using Parentheses to Override Precedence:
2 + (3 * 4)
1. Evaluate expression inside parentheses first.
2. 3 * 4 = 12
3. Then, evaluate 2 + 12: 2 + 12 = 14
Result: 14
What is type casting in Python? Explain with examples how to convert data
from one type to another (e.g., int to float, str to int).
Type casting, also known as type conversion, is the process of changing the
data type of a variable or expression from one type to another.
Why Type Casting?
1. To ensure compatibility with operators or functions.
2. To change data representation.
3. To avoid type errors.
Built-in Type Casting Functions:
1. int() - converts to integer
2. float() - converts to floating-point number
3. str() - converts to string
4. bool() - converts to boolean
5. complex() - converts to complex number
6. tuple() - converts to tuple
7. list() - converts to list
8. dict() - converts to dictionary
Describe Python's dynamic typing system. How does it differ from statically-
typed languages like C or Java?
Python is dynamically typed, meaning that:
1. Variable types are determined at runtime, not compile time.
2. Variables can change type during execution.
3. No explicit type declarations are required.
Key Features:
1. Type Inference: Python automatically infers the type of a variable
based on its assignment.
2. Type Flexibility: Variables can be reassigned to different types.
3. No Type Errors at Compile Time: Type errors are detected at runtime.
Example:
x = 5 # x is an integer
x = "hello" # x becomes a string
x = 3.14 # x becomes a float
Differences from Statically-Typed Languages (C, Java):
1. Type Declarations: In statically-typed languages, variables must be
explicitly declared with their type.
2. Type Checking: Type checking occurs at compile time, preventing type
errors at runtime.
3. Type Safety: Statically-typed languages ensure type safety by
preventing type mismatches.
Example (Java):
int x = 5; // explicit type declaration
x = "hello"; // compile-time error
Advantages of Dynamic Typing:
1. Flexibility: Easier to write code, fewer type constraints.
2. Rapid Prototyping: Faster development, less boilerplate code.
3. Dynamic Nature: Suitable for dynamic, interactive environments.
Disadvantages of Dynamic Typing:
1. Type Errors: Type errors may occur at runtime.
2. Performance: Dynamic typing can lead to slower performance.
3. Code Complexity: Type-related issues can arise in large codebases.
Python's Type Hinting:
Python 3.5+ introduced type hinting, allowing developers to add type
annotations to variables, function parameters, and return types. These hints
are optional and do not affect runtime behaviour.
What are complex numbers in Python? How are they represented, and what
are some of the operations you can perform on them?
Complex Numbers in Python
Complex numbers are numbers with both real and imaginary components.
Python supports complex numbers through the complex data type.
Representation:
Complex numbers are represented as a + bj, where:
a is the real part
b is the imaginary part
j is the imaginary unit (i.e., sqrt(-1))
Syntax:
complex(real, imaginary)
Operation:
1. Addition: z1 + z2
2. Subtraction: z1 - z2
3. Multiplication: z1 * z2
4. Division: z1 / z2
5. Conjugation: [Link]() (or ~z)
6. Magnitude (absolute value): abs(z)
7. Phase (angle): [Link](z)
Question:- Module
WAP in pyhton to create a module name factorial and create a user
define function fact() in that module and return the factorial of
number by using this module
Basic Programs for Unit 1
1. Write the python program to calculate the simple interest. Data
accept from user like principal amount,rate and time.
2. Write the python program to enter the three integer values
from user and calculate the average.
3. Write the python program to perform the given operations like
(Addition, Subtraction, Multiplication, Division) of two user
inputted numbers.
Basic questions :
1. Who developed the python programming?
2. Write the features of python programming.
3. Explain, Why python is called dynamic language?
4. What is token in python?
5. What is variable and what are the rules to declare the variable
name.
6. What are the operators in Python.
7. What is operator precedence and associativity.
Unit – 2:-
Programs:-
1. Write the python program to accept the age from user and check
he/she is eligible for voting.
2. Write the python program to accept the two integer numbers
from user and check which one is greater.
3. Write the python program to accept three integer numbers from
user and check which is greater.
4. Write the menu driven python program to perform all the
operations of calculator on two intergers. Operation symbol
should be asked at run time.
5. Write the python program to accept list of 10 items from user
and display only integer types of items from the list.
Basic Questions:-
1. What are selection statements in [Link] in detail.
2. What is match statement in python. Why we use it?
3. Is there any alternate of if else statement in python? Explain in
detail.
4. Explain about the datatypes of python.
5. Explain list data structure in detail.
6. Write the difference between list and tuple.
7. Explain the dictionary data structure in detail.
8. Write the difference between set and dictionary.
9. What is the purpose of eval( ) function in python?
Unit-3:-
Basic Programs:-
1. Write the python program to print the only even numbers
from 1 to 20.
2. Write the python program to accept a number from user and
check that number is prime or not?
3. Write the python program to accept a number from user and
check that number is perfect number or not?
4. Write the python program to print the all Armstrong number
fin between 100 and 10,000.
5. Write the python program to print the tables from 2 to 10.
6. Pattern programs.
Basic Questions:-
1. Explain the iterative statements of python.
2. Explain all the jumping statements in python (break, continue,
pass ) in detail.
3. Write down the syntaxes of all iterative statements.
4. Explain else statement with while statements with example.
5. Explain the concept of nested loops in python.
Unit- 4
Basic Programs:-
1.