Mid Sem Python Answers
Mid Sem Python Answers
Ans:- Free and Open Source, Easy to code, Object-Oriented Language, GUI Programming Support,
High-Level Language, Large Community Support, Python is a Portable language, Python is an
Integrated language.
2. python identifiers?
Ans:- Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that's called identifier.
4.Reseved Keywords?
Ans:- and, else, while ,as, except, with, assert, finally, yield, break, for.
5.Importance of indentation?
Ans:- In computer programming languages, indentation is used to format program source code to
improve readability. Indentation is generally only of use to programmers; compilers and
interpreters rarely care how much whitespace is present in between programming statements.
Ans:- Single-line comments start with two forward slashes ( # ). Any text between # and the end of
the line is ignored by the compiler./ Multiline comments are used for large text descriptions of
code or to comment out chunks of code while debugging applications.
Ans:- Numeric data types: int, float, complex./String data types: str./Sequence types: list, tuple,
range./Binary types: bytes, bytearray, memoryview./Mapping data type: dict./Boolean type: bool.
8.What is list?
Ans:- A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements.
Tuple:-Count(), Index().
14. ?
Ans:- Arithmetic operators take precedence over logical operators. Python will always evaluate the
arithmetic operators first (** is highest, then multiplication/division, then addition/subtraction).
15.Describe bitwise operator?
Ans:- Python bitwise operators are used to perform bitwise calculations on integers. The integers
are converted into binary format and then operations are performed bit by bit, hence the name
bitwise operators.
Ans:- Logical Operators in Python are used to perform logical operations on the values of variables.
The value is either true or false. We can figure out the conditions by the result of the truth values.
There are mainly three types of logical operators in python: logical AND, logical OR and logical
NOT.
Ans:- In Python, you can simply use the bin() function to convert from a decimal value to its
corresponding binary value. And similarly, the int() function to convert a binary to its decimal
value. The int() function takes as second argument the base of the number to be converted, which
is 2 in the case of binary numbers.
Ans:- In case else is not specified, and all the statements are false , none of the blocks would be
executed. Here's an example: if 51<5: print("False, statement skipped") elif 0<5: print("true, block
executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")
Ans:- If the condition is True, the code block indented below the if statement will be executed. If
the condition is False, the code block will be skipped. Here's an example of how to use an if
statement to check if a number is positive: num = 5 if num > 0: print("The number is positive.")
Ans:- Python nested “if else”. consider the following scenario: If num is greater than 0 , check if
num is even by checking if the remainder when num is divided by 2 is 0 . If the remainder is 0 ,
execute the code block that prints the message “The number is positive and even.Ex:- num = 5 if
num > 0: print("The number is positive.")else: if num < 0: print("The number is negative.")
else: print("The number is zero.").
Ans:- A while loop is a control flow statement that allows you to repeatedly execute a block of
code as long as a specific condition is true. It is commonly used when you don't know the exact
number of iterations in advance and need to keep executing the code until the condition becomes
false.ex:- i = 1 while i <= 5: print("KnowledgeHut by upGrad") i = i + 1.
Ans:- We can use the break statement with the for loop to terminate the loop when a certain
condition is met. For example, for i in range(5):if i == 3: break print(i).
We can use the continue statement with the for loop to skip the current iteration of the loop. Then
the control of the program jumps to the next iteration. For example, for i in range(5): if i == 3:
continue print(i).
27.Explain the syntax of for loop and apply it for string with example?
Ans:- The first word of the statement starts with the keyword “for” which signifies the beginning of
the for loop.Then we have the iterator variable which iterates over the sequence and can be used
within the loop to perform various functionsThe next is the “in” keyword in Python which tells the
iterator variable to loop for elements within the sequenceAnd finally, we have the sequence
variable which can either be a list, a tuple, or any other kind of iterator.The statements part of the
loop is where you can play around with the iterator variable and perform various function
Ans:- log10(x) Returns the base-10 logarithm of x, pow(x, y) Returns x raised to the power y, sqrt(x)
Returns the square root of x, acos(x) Returns the arc cosine of x.
Ans:- getrandbits() Return an integer with a specified number of bits, randrange() Returns a
random number within the range, randint() Returns a random integer within the range, choice()
Returns a random item from a list, tuple, or string
Ans:- Strings are immutable data types in Python. We cannot update the string's value. Slicing
strings create a substring from the original string. Slicing means extracting a part from something,
and slicing a string means extracting some part from a string. The slice() method returns an object
containing the range of string slicing. The parameter includes a set of range of values defined as
(start, stop, step). Let's look at the syntax of the slice method().Ex:- string = 'Coding Ninjas'
print(string[slice(6)])
Ans:- When you need to split a string into substrings, you can use the split() method. The split()
method acts on a string and returns a list of substrings. The syntax is:
<string>.split(sep,maxsplit)Ex:- my_string = "Apples,Oranges,Pears,Bananas,Berries"
my_string.split(",")
Ans:- Linear search is a method of finding elements within a list. It is also called a sequential
search. It is the simplest searching algorithm because it searches the desired element in a
sequential manner. It compares each and every element with the value that we are searching for. If
both are matched, the element is found, and the algorithm returns the key's index position.Ex:-
list1 = [1 ,3, 5, 4, 7, 9] key = 7 n = len(list1) res = linear_Search(list1, n, key) if(res == -1):
print("Element not found") else: print("Element found at index: ", res).
Ans:- A binary search is an algorithm to find a particular element in the list. Suppose we have a list
of thousand elements, and we need to get an index position of a particular element. We can find
the element's index position very fast using the binary search algorithm.There are many searching
algorithms but the binary search is most popular among them.The elements in the list must be
sorted to apply the binary search algorithm. If elements are not sorted then sort them first.
Programs:-
if (num % i) == 0: else:
print(num, "is not a prime number") print(num, "is not a prime number")
2.Factorial Program?
Ans:-
for i in s: print(s)
Ans:- c = 'g'
6. split multi line string into list with every element as word or sentence in python?
print(string)
print(new_string)
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
else:
List String
List is a collection of elements, each element
String is a sequence of characters (text).
can be of any data type (int, float, str, etc.).
Lists are mutable, which means you can modify Strings are immutable, meaning you cannot
their elements change their individual characters after
creation.
Lists do not support repetition Strings support repetition
Lists have methods like append(), insert(), Strings have methods like strip(), split(),
remove(), and more for element manipulation. replace(), and more for string manipulation.
You can convert a list to a string using functions You can convert a string to a list using the split()
like join(). method.
Strings are defined using single or double
Lists are defined using square brackets
quotes
Elements or slices can be deleted from a list
Characters or slices cannot be deleted from a
using the del statement or the remove()
string.
method.
Strings are more memory-efficient because
Lists generally consume more memory due to
they store characters as-is without additional
the overhead of storing references to objects.
references.
Strings are used to work with text data,
Lists are typically used to store collections of
manipulate textual information, and represent
items, such as numbers, objects, or other lists.
sequences of characters.
mixed_list = [1, "two", 3.0, "four", True] String1 = "Hello, Python!"
Dictionary Set
Elements are unique; duplicates are automatically
Keys must be unique; values can be duplicated.
removed.
Sets do not support indexing or key-value access.
Dictionaries are accessed by their keys. You can use a You can use sets to check for the presence of
key to look up the associated value elements but cannot directly access elements by
their position.
Dictionaries are defined using curly braces and colon Sets are defined using curly braces without colons to
to separate keys and values denote elements
Set methods involve operations on individual Dictionary methods involve operations on key-value
elements, such as adding, removing, and checking pairs, including adding, modifying, removing, and
for existence. looking up values by keys.
Managing collections of unique elements, set
Key-value storage, mappings, data retrieval.
operations.
my_dict = {'name': 'John', 'age': 30} my_set = {1, 2, 3, 4}
List Tuple
Tuple String
Defined using parentheses (). Defined using single or double quotes '' or "".
Tuples store ordered collections of elements Strings store ordered collections of characters.
Strings store sequences of characters (usually
Tuples can store elements of different data types.
Unicode characters).
Strings can be iterated through character by
Tuples can be iterated through using for loops.
character.
Searching for an element in a tuple can be slower, as Searching for a substring in a string can be more
it involves linear searching. efficient, thanks to built-in string search algorithms.
Tuples have fewer built-in methods compared to Strings have a wide range of built-in methods for
strings. string manipulation, formatting, and more.
Tuples are often used to represent fixed data Strings are used for representing and manipulating
structures like coordinates, records etc. text and formatting messages.
my_tuple = (1, 2, 3) my_string = "Hello, World!"
List Array
List is a built-in data structure in Python defined Arrays are not a built-in data type in Python.
Arrays are often used with external libraries, such as
Lists are part of Python's standard library.
NumPy.
Arrays can store elements of the same data type
Lists can store elements of various data types.
(homogeneous arrays).
Lists can grow or shrink dynamically as elements are Arrays have a fixed size when created; resizing typically
added or removed. requires creating a new array.
Lists may be slower for numerical operations due to their Arrays are optimized for numerical operations and
dynamic nature provide better performance
Lists may consume more memory due to dynamic sizing Arrays can be more memory-efficient due to
and storage of diverse data types. homogeneity
Lists are versatile and suitable for general-purpose data Arrays are used for numerical and scientific computing,
where performance and mathematical operations are
storage and manipulation.
crucial.
import numpy as np
my_list = [1, 2, 3, 4, 5]
my_array = np.array([1, 2, 3, 4, 5])
Array
String
A built-in data type in Python defined using single or
Created using external libraries like NumPy.
double quotes '' or "".
Typically stores elements of the same data type
Stores sequences of characters, often representing text.
(homogeneous).
Strings are immutable; their length doesn't change after Arrays have a fixed size when created, resizing typically
creation. requires creating a new array.
Efficient for string operations, including searching, slicing, Arrays are optimized for numerical operations and
and formatting. provide better performance.
Arrays can be more memory-efficient due to
Efficient in memory consumption for text data.
homogeneity.
Arrays are used for numerical and scientific computing,
Used for representing and manipulating text data,
where performance and mathematical operations are
parsing, formatting, and more.
crucial.
import numpy as np
my_string = "Hello, World!"
my_array = np.array([1, 2, 3, 4, 5])