SCRIPTING LANGUAGE SUGGESTION(previous year)
1. WHAT IS LAMBDA FUNCTION?
Ans: A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one
expression.
[Link] is an interpreted language?
Ans: An interpreted language is a programming language that executes
instructions directly, without the need for a separate compilation step:
How it works
An interpreter translates and executes the instructions in a program line by
line. This makes it easier and quicker to develop and test code.
When to use
Interpreted languages are often used for web development, scripting,
automation tasks, network programming and communication, and game
development.
3. what is python iterator?
Ans: In Python, an iterator is an object that allows you to traverse through a
sequence of values, one at a time. It provides a way to access elements of a
collection without needing to know the underlying implementation details.
4. what is python scope?
Ans: In Python, scope defines the region of the code where a variable is
accessible or visible. It determines where you can access and modify a variable.
Python follows the LEGB rule for scope resolution:
L: Local Scope:
The innermost scope, typically within a function or method. Variables defined
here are only accessible inside the function.
G: Global Scope:
The top-level scope of a module. Variables defined here are accessible from
anywhere within the module.
[Link] to comment multiple line in python?
Ans: Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
[Link] find() function.
Ans: he find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference
is that the index() method raises an exception if the value is not found.
[Link] is dictionaries?
Ans: Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
8. what is flush() function?
Ans: The flush() method in Python file handling clears the internal buffer of the
file. In Python, files are automatically flushed while closing them.
9. What is list and tuple?
Ans: List is Mutable and Tuple is not (Cannot update an element, insert and
delete elements)
Tuples are faster because of read only nature. Memory can be efficiently
allocated and used for tuples.
[Link] is PEP 8?
Ans: PEP8 provides an extensive set of guidelines for Python code styling,
promoting readability and a uniform coding standard. By aligning with PEP8,
we ensure our codebase remains clean, maintainable, and easily understandable
for Python developers at any level.
11. IS PYTHON CASE SENSITIVE LANGUAGE?
Ans:
Yes, Python is a case-sensitive programming language. This means that Python
distinguishes between uppercase and lowercase characters.
12. What is string slicing?
Ans: you can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
b = "Hello, World!"
print(b[2:5])
output:llo
13. what is membership operator?
Ans: Membership operators are used to test if a sequence is presented in an
object:
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in
specified value is not present in the object y
14. Difference between break and continue.
Ans:
Break statement
Ends the entire loop process and terminates the remaining iterations. For
example, a break statement can be used to return to the beginning of a menu.
Continue statement
Skips the rest of the loop's statements and begins the next iteration. Continue
statements are useful when there is also a test that includes a break.
15. what is local and global variable?
Ans:
Local variables
Can only be accessed within the function or block where they are
declared. They are only present in RAM while the sub-program they are in is
executing.
Global variables
Can be accessed by any function or sub-program in the program, and are
always present in RAM while the program is executing.
16. Difference between list and array?
Ans:
Difference Between List and Array in Python
The following table shows the differences between List and Array in Python:
List Array
Can consist of elements belonging Only consists of elements belonging to
to different data types the same data type
No need to explicitly import a Need to explicitly import
module for the declaration the array module for declaration
Cannot directly handle arithmetic Can directly handle arithmetic
operations operations
Preferred for a shorter sequence of Preferred for a longer sequence of data
data items items
17. Name two built in function in python with syntax.
Ans: 1. len(): Returns the length of an object (like a string, list, or dictionary).
Python
my_list = [1, 2, 3, 4]
length = len(my_list) # length will be 4
2. print(): Outputs the specified message to the console.
Python
print("Hello, World!")
[Link] is ternary operator in python?
Ans: n Python, the ternary operator is a concise way to write a conditional
expression in a single line.
x = 10
y=5
z = x if x > y else y
print(z)
19. Explain basic data types of python? With example.
Ans:
Python Data Types
Every value has a datatype, and variables can hold values. Python is a
powerfully composed language; consequently, we don't have to characterize the
sort of variable while announcing it. The interpreter binds the value implicitly to
its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an
integer. The Python interpreter will automatically interpret the variable as an
integer.
We can verify the type of the program-used variable thanks to Python. The
type() function in Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of
various data types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must
be stored as an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is
specified by Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk
about every single one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex
qualities have a place with a Python Numbers datatype. Python offers the type()
function to determine a variable's data type. The instance () capability is utilized
to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For
instance,
1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20,
- 150, and so on. An integer can be any length you want in Python. Its
worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can
be accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy,
where x and y signify the genuine and non-existent parts separately. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the
string. A string can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in
capabilities and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello
python," and the operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred
to as a repetition operator.
The Python string is demonstrated in the following example.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string
Look at the following illustration of string handling.
Example - 2
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types.
The things put away in the rundown are isolated with a comma (,) and encased
inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they
worked with strings, the list is handled by the concatenation operator (+) and the
repetition operator (*).
Look at the following example.
Example:
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11.# List slicing
[Link] (list1[0:2])
13.
14.# List Concatenation using + operator
[Link] (list1 + list1)
16.
17.# List repetation using * operator
[Link] (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of
items from various data types. A parenthetical space () separates the tuple's
components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only
data structure.
Let's look at a straightforward tuple in action.
Example:
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
[Link] (tup[0:1])
11.
12.# Tuple concatenation using + operator
[Link] (tup + tup)
14.
15.# Tuple repatation using * operator
[Link] (tup * 3)
17.
18.# Adding value to tup. It will throw an error.
19.t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last):
File "[Link]", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific
value for each key, like an associative array or a hash table. Value is any Python
object, while the key can hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the
dictionary.
Look at the following example.
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
[Link] ([Link]())
[Link] ([Link]())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
True and False are the two default values for the Boolean type. These qualities
are utilized to decide the given assertion valid or misleading. The class book
indicates this. False can be represented by the 0 or the letter "F," while true can
be represented by any value that is not zero.
Look at the following example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can
change after creation), and has remarkable components. The elements of a set
have no set order; It might return the element's altered sequence. Either a
sequence of elements is passed through the curly braces and separated by a
comma to create the set or the built-in function set() is used to create the set. It
can contain different kinds of values.
Look at the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
[Link](10)
[Link](set2)
13.
14.#Removing element from the set
[Link](2)
[Link](set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
20. Write difference between list and tuple.
Ans:
Sno LIST TUPLE
Sno LIST TUPLE
1 Lists are mutable Tuples are immutable
The implication of iterations is Time- The implication of iterations is
2
consuming comparatively Faster
The list is better for performing A Tuple data type is
3 operations, such as insertion and appropriate for accessing the
deletion. elements
Tuple consumes less memory
4 Lists consume more memory
as compared to the list
Tuple does not have many
5 Lists have several built-in methods
built-in methods.
[Link] is difference between module and package?
Ans: this article, we will see the difference between Python’s Module,
Package, and Library. We will also see some examples of each to things more
clear.
What is Module in Python?
The module is a simple Python file that contains collections of functions
and global variables and with having a .py extension file. It is an executable
file and to organize all the modules we have the concept called Package in
Python.
Examples of modules:
1. Datetime
2. Regex
3. Random etc.
Example: Save the code in a file called demo_module.py
Python3
def myModule(name):
print("This is My Module : "+ name)
Import module named demo_module and call the myModule function inside
it.
Python3
import demo_module
demo_module.myModule("Math")
Output:
This is My Module : Math
What is Package in Python?
The package is a simple directory having collections of modules. This
directory contains Python modules and also having __init__.py file by which
the interpreter interprets it as a Package. The package is simply a namespace.
The package also contains sub-packages inside it.
Examples of Packages:
1. Numpy
2. Pandas
Example:
Student(Package)
| __init__.py (Constructor)
| [Link] (Module)
| [Link] (Module)
| [Link] (Module)
22. Explain different type of loops in python.
Ans:
Repeats a statement or
group of statements
while a given condition
1 While loop
is TRUE. It tests the
condition before
executing the loop body.
This type of loop
executes a code block
multiple times and
2 For loop
abbreviates the code that
manages the loop
variable.
We can iterate a loop
3 Nested loops
inside another loop.
23. What is purpose of return statement in python?
Ans: In Python, the return statement serves two primary purposes:
1. Ending Function Execution:
It marks the end of a function's execution.
Any code written after the return statement within the function will not be
executed.
2. Sending Values Back to the Caller:
It allows a function to send a value (or multiple values) back to the code that
called the function.
This value can then be used by the caller for further processing or calculations.
[Link] do you mean by default argument and how is it required?
Ans:
A "default argument" in programming refers to a value assigned to a function
parameter when the function is defined, which is automatically used if the caller
of the function does not explicitly provide a value for that argument during the
function call; essentially, it acts as a fallback value when an argument is
omitted.
Why default arguments are useful:
Flexibility:
They allow you to create functions that can be called with varying levels of
specificity, depending on the situation.
Reduced code duplication:
By setting default values for commonly used options, you can avoid writing
multiple similar functions with slightly different parameters.
Improved readability:
When a function has default values for certain parameters, it becomes clearer
what the expected behavior is if the caller doesn't specify those values.
25. What is python? Explain the key features of python.
Ans: Python is a dynamic, high-level, free open source, and interpreted
programming language. It supports object-oriented programming as well
as procedural-oriented programming. In Python, we don’t need to declare the
type of variable because it is a dynamically typed language. For example, x =
10 Here, x can be anything such as String, int, etc. In this article we will see
what characteristics describe the python programming language
Features in Python
In this section we will see what are the features of Python programming
language:
1. Free and Open Source
Python language is freely available at the official website and you can
download it from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that
source code is also available to the public. So you can download it, use it as
well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in the Python language and anybody can learn Python basics
in a few hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the
indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, object
encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in Python. PyQt5 is the most popular option for creating
graphical apps with Python.
26. write the difference between local and global variable.
Ans:
Aspect Local Variables Global Variables
Accessible throughout the
Limited to the block of code
Scope program
Typically within functions or Outside of any function or
Declaration specific blocks block
Accessible only within the Accessible from any part of
Access block where they are declared the program
Created when the block is
Retain their value throughout
entered and destroyed when it
the lifetime of the program
Lifetime exits
Name Can have the same name as Should be used carefully to
conflicts variables in other blocks avoid unintended side effects
27. What is join() and split() function in python?
Ans:
In Python, join() and split() are string methods used for manipulating strings:
split():
Purpose: Splits a string into a list of substrings based on a specified delimiter.
Syntax: [Link](separator, maxsplit)
o separator: The delimiter used to split the string (default is whitespace).
o maxsplit: The maximum number of splits to perform (optional).
Example:
Python
Execution output
text = "Hello, world! How are you?"
words = [Link]() # Split using whitespace as delimiter
print(words)
['Hello,', 'world!', 'How', 'are', 'you?']
join():
Purpose: Joins a list of strings into a single string, using a specified separator.
Syntax: [Link](iterable)
o separator: The string used to join the elements of the iterable.
o iterable: An iterable (e.g., list, tuple) containing the strings to be joined.
Example:
Python
Execution output
words = ['Hello', 'world', 'how', 'are', 'you']
sentence = ' '.join(words)
print(sentence)
Hello world how are you
In simpler terms:
split() breaks a string into pieces, like splitting a sentence into words.
join() glues pieces back together, like joining words to form a sentence.
[Link] string is called immutable? What is mutable and immutable data
types?
Ans: A string is called "immutable" because once created, its value cannot be
changed directly; any attempt to modify a string results in a new string object
being created with the updated value, leaving the original string unchanged.
Explanation of Mutable and Immutable Data Types:
Mutable Data Types:
These are data types that can be modified after they are created. When you
change a value in a mutable data type, the existing object is directly updated.
Example: Lists, dictionaries, sets in most programming languages.
Immutable Data Types:
These are data types that cannot be changed once created. If you need to
"modify" an immutable data type, a new object with the desired changes must
be created.
Example: Strings, integers, floats, and tuples in most programming languages.
29. Write the types of operators in python.
1. Ans: Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Arithmetic Operators in Python
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x
division of 2 integers was an integer. To obtain an integer result in Python 3.x
floored (// integer) is used.
Operator Description Syntax
Addition: adds
+ x+y
two operands
Subtraction:
– subtracts two x–y
operands
Operator Description Syntax
Multiplication:
* multiplies two x*y
operands
Division (float):
divides the first
/ x/y
operand by the
second
Division (floor):
divides the first
// x // y
operand by the
second
Modulus: returns
the remainder
when the first
% x%y
operand is
divided by the
second
Power: Returns
** first raised to x ** y
power second
Example of Arithmetic Operators in Python
Division Operators
In Python programming language Division Operators allow you to divide
two numbers and return a quotient, i.e., the first number or number at the left
is divided by the second number or number at the right and returns the
quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if
two numbers are integers. For example:
Example: The code performs division operations and prints the results. It
demonstrates that both integer and floating-point divisions return accurate
results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’.
[GFGTABS] Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
[/GFGTABS]
Output:
1.0
5.0
-5.0
10.0
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being
passed. If any of the numbers is float, it returns output in float. It is also known
as Floor division because, if any number is negative, then the output will be
floored. For example:
Example: The code demonstrates integer (floor) division operations using
the // in Python operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-
5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer
division returns the largest integer less than or equal to the division result.
[GFGTABS] Pythons
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
[/GFGTABS]
Output:
3
-3
2.0
-3.0
Precedence of Arithmetic Operators in Python
The precedence of Arithmetic Operators in Python is as follows:
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the same precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same precedence)
6. S – Subtraction
The modulus of Python operators helps us extract the last digit/s of a number.
For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits
Arithmetic Operators With Addition, Subtraction, Multiplication,
Modulo and Power
Here is an example showing how different Arithmetic Operators in Python
work:
Example: The code performs basic arithmetic operations with the values
of ‘a’ and ‘b’. It adds (‘+’), subtracts (‘-‘), multiplies (‘*’), computes the
remainder (‘%’), and raises a to the power of ‘b (**)’. The results of these
operations are printed.
[GFGTABS] Python
a=9
b=4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
[/GFGTABS]
Output:
13
5
36
1
6561
Note: Refer to Differences between / and // for some interesting facts about
these two Python operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
Greater than: True if the
> left operand is greater x>y
than the right
Less than: True if the
< left operand is less than x<y
the right
Equal to: True if both
== x == y
operands are equal
Not equal to – True if
!= x != y
operands are not equal
Greater than or equal to
True if the left operand
>= x >= y
is greater than or equal
to the right
Less than or equal to
True if the left operand
<= x <= y
is less than or equal to
the right
= is an assignment operator and == comparison operator.
Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than the arithmetic
operators. All the operators within comparison operators have the same
precedence order.
Example of Comparison Operators in Python
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using various
comparison Python operators and prints the results. It checks if ‘a’ is greater
than, less than, equal to, not equal to, greater than, or equal to, and less than or
equal to ‘b’.
[GFGTABS] Python
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
[/GFGTABS]
Output
False
True
False
True
False
True
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
Operator Description Syntax
Operator Description Syntax
Logical AND: True if
and both the operands are x and y
true
Logical OR: True if
or either of the operands is x or y
true
Logical NOT: True if
not not x
the operand is false
Precedence of Logical Operators in Python
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python
The following code shows how to implement Logical Operators in Python:
Example: The code performs logical operations with Boolean values. It
checks if both ‘a’ and ‘b’ are true (‘and’), if at least one of them is true (‘or’),
and negates the value of ‘a’ using ‘not’. The results are printed accordingly.
[GFGTABS] Python
a = True
b = False
print(a and b)
print(a or b)
print(not a)
[/GFGTABS]
Output
False
True
False
Bitwise Operators in Python
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in Python is as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Bitwise Operators in Python
Here is an example showing how Bitwise Operators in Python work:
Example: The code demonstrates various bitwise operations with the values
of ‘a’ and ‘b’. It performs bitwise AND (&), OR (|), NOT (~), XOR
(^), right shift (>>), and left shift (<<) operations and prints the results.
These operations manipulate the binary representations of the numbers.
[GFGTABS] Python
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
[/GFGTABS]
Output
0
14
-11
14
2
40
Assignment Operators in Python
Python Assignment operators are used to assign values to the variables.
Operator Description Syntax
Assign the value of the
right side of the
= x=y+z
expression to the left
side operand
Add AND: Add right-
side operand with left-
+= a+=b a=a+b
side operand and then
assign to left operand
Operator Description Syntax
Subtract AND: Subtract
right operand from left
-= a-=b a=a-b
operand and then assign
to left operand
Multiply AND:
Multiply right operand
*= with left operand and a*=b a=a*b
then assign to left
operand
Divide AND: Divide
left operand with right
/= a/=b a=a/b
operand and then assign
to left operand
Modulus AND: Takes
modulus using left and
%= right operands and a%=b a=a%b
assign the result to left
operand
Divide(floor) AND:
Divide left operand with
//= right operand and then a//=b a=a//b
assign the value(floor)
to left operand
**= Exponent AND: a**=b a=a**b
Calculate
Operator Description Syntax
exponent(raise power)
value using operands
and assign value to left
operand
Performs Bitwise AND
&= on operands and assign a&=b a=a&b
value to left operand
Performs Bitwise OR on
|= operands and assign a|=b a=a|b
value to left operand
Performs Bitwise xOR
^= on operands and assign a^=b a=a^b
value to left operand
Performs Bitwise right
shift on operands and
>>= a>>=b a=a>>b
assign value to left
operand
Performs Bitwise left
shift on operands and
<<= a <<= b a= a << b
assign value to left
operand
Assignment Operators in Python
Let’s see an example of Assignment Operators in Python.
Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then
performs a series of operations: addition, subtraction, multiplication, and a left
shift operation on ‘b’. The results of each operation are printed, showing the
impact of these operations on the value of ‘b’.
[GFGTABS] Python
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
[/GFGTABS]
Output
10
20
10
100
102400
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are
equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example Identity Operators in Python
Let’s see an example of Identity Operators in Python.
Example: The code uses identity operators to compare variables in Python. It
checks if ‘a’ is not the same object as ‘b’ (which is true because they have
different values) and if ‘a’ is the same object as ‘c’ (which is true
because ‘c’ was assigned the value of ‘a’).
[GFGTABS] Python
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
[/GFGTABS]
Output
True
True
Membership Operators in Python
In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Examples of Membership Operators in Python
The following code shows how to implement Membership Operators in
Python:
Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It
prints whether or not each value is present in the list. ‘x’ is not in the list,
and ‘y’ is present, as indicated by the printed messages. The code uses
the ‘in’ and ‘not in’ Python operators to perform these checks.
[GFGTABS] Python
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
[/GFGTABS]
Output
x is NOT present in given list
y is present in given list
30. How to import module in python?
Ans: import a module in Python, you can use the import statement.
Here's how it works:
Importing the entire module.
Python
import math
This imports the entire math module, allowing you to access its functions and
variables using the module name as a prefix:
Python
import math
print([Link](25))
Importing specific attributes from a module.
Python
from math import sqrt
[Link] is arbitrary argument?
Ans: An "arbitrary argument" in programming, often referred to as "*args" in
Python, is a function parameter that allows a variable number of arguments to
be passed to a function when the exact number of arguments needed is unknown
beforehand; essentially, it lets a function accept any number of values at the
time of calling it, providing flexibility in code design.
Key points about arbitrary arguments:
Syntax:
To define an arbitrary argument in Python, use an asterisk (*) before the
parameter name in the function definition.
Data structure:
When passed to a function, arbitrary arguments are automatically collected
into a tuple.
Example:
Code
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3)) # Output: 6
print(sum_numbers(10, 20, 30, 40)) # Output: 100
32. What is MVC framework? Explain it.
Ans: MVC framework stands for "Model-View-Controller" framework, which
is a software design pattern that separates an application's logic into three
distinct parts: the Model (data management), the View (user interface
presentation), and the Controller (handling user input and coordinating between
the Model and View), allowing for better organization, maintainability, and
easier development by dividing responsibilities within the application.
Key components of MVC:
Model:
Represents the application's data and business logic.
Retrieves, stores, and manipulates data from a database.
Does not directly interact with the user interface.
View:
Responsible for displaying data to the user.
Generates the visual representation of the data received from the controller.
Does not contain any business logic.
Controller:
Acts as the intermediary between the Model and View.
Receives user input, retrieves data from the Model, and decides which View to
render based on the data.
Handles user interactions and updates the model when necessary.
[Link] down the steps of creating django project and run it.
Ans:
To create a Django project and run it, follow these steps:
1. Set up your environment:
Create a virtual environment:
o Open your terminal and navigate to the directory where you want to create your
project.
o Run python -m venv <your_env_name> (e.g., python -m venv my_project_env)
o Activate the environment:
On most systems: source my_project_env/bin/activate
On Windows: my_project_env\Scripts\activate
Install Django:
o Once your virtual environment is activated, run pip install django
2. Create a Django project:
Navigate to the project directory:
o In your terminal, navigate to the desired location for your project.
Create the project:
o Run django-admin startproject <project_name> (e.g., django-admin startproject
my_project)
3. Understand the project structure:
[Link]:
This file is the primary entry point for interacting with your Django project
(like running the development server).
[Link]:
Contains configuration details for your project (database settings, installed
apps, etc.).
[Link]:
Defines the URL patterns for your project.
[Link]:
Used for ASGI (Asynchronous Server Gateway Interface) compatible web
servers.
4. Create an app (optional):
Navigate to the project directory:
o cd my_project
Create an app:
o Run python [Link] startapp <app_name> (e.g., python [Link] startapp
my_app)
5. Run the development server:
Activate the virtual environment (if not already active)
Run the server:
o python [Link] runserver
Access your project:
Open your web browser and go to [Link] to see the default
Django welcome page.
34. Write a program to print to find factorial of a number.
Ans: def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
number = int(input("Enter a number: "))
print("The factorial of", number, "is", factorial(number))
35. Write a program to check a number is palindrome or not.
1. Ans: Num = int(input("Enter a value:"))
2. Temp = num
3. Rev = 0
4. while(num > 0):
5. dig = num % 10
6. revrev = rev * 10 + dig
7. numnum = num // 10
8. if(temp == rev):
9. print("This value is a palindrome number!")
10. else:
11. print("This value is not a palindrome number!")
36. Write a program to check a number is prime or not.
num = 29
#num = int(input("Enter a number: "))
flag = False
if num == 0 or num == 1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
37. Write a program to check a string is palindrome or not.
1. Ans: string=input(("Enter a letter:"))
2. if(string==string[::-1]):
3. print("The letter is a palindrome")
4. else:
5. print("The letter is not a palindrome")