Programming and Problem Solving through Python

Question & Answer



Question : 1
What is the difference between a keyword and an identifier?


Answer :

Every language has keywords and identifiers, which are only understood by its compiler. Keywords are predefined reserved words, which possess special meaning. An identifier is a unique name given to a particular variable, function or label of class in the program.



Question : 2
What are literals in Python? How many types of Literals allowed in Python?


Answer :

Literals: Python comes with some built-in objects. Some are used so often that Python has a quick way to make these objects, called literals.

The literals include the string, Unicode string, integer, float, long, list, tuple and dictionary types.



Question : 3
How many types of sequences are supported in Python?


Answer :

Three Types of Sequences are supported in python:

(i) String

(ii) List

(iii) Tuple



Question : 4
What factors guide the choice of identifiers in program?


Answer :

(i) An identifier must start with a letter or underscore followed by any number of digits and/or letters.

(ii) No reserved word or standard identifier should be used.

(iii) No special character (Other than underscore) should be included in the identifier.



Question : 5
What is the difference between an expression and a statement in Python?


Answer :

A statement is an instruction that the Python interpreter can execute. We have only seen the assignment statement so far. Some other kinds of statements that we‘ll see shortly are while statements, for statements, if statements, and import statements. (There are other kinds too!)

An expression is a combination of values, variables, operators, and calls to functions. Expressions need to be evaluated. If you ask Python to print an expression, the interpreter evaluates the expression and displays the result.



Question : 6
What are tokens in Python? How many types of tokens allowed in Python?


Answer :

Tokens are the smallest unit of the program. There are following tokens in Python:

  •  Reserved words or Keywords
  •  Identifiers
  •  Literals
  •  Operators
  •  Punctuators


Question : 7
What is the role of indentation in Python?


Answer :

Indentation plays a very important role in Python. Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suit. You cannot unnecessarily indent a statement; python will raise an error for that.



Question : 8
What are data types? What are Python built in core data types?


Answer :

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. There are various data types in Python. Some of the important types are listed below.

(i) Numbers

(ii) String

(iii) List

(iv) Tuple

(v) Dictionary



Question : 9
Which data types of Python handle Numbers?


Answer :

It is cleared by name that Number data types are used to store numeric value in Python. The Numbers in Python have following core data types:

(i) Integers

a. Integers (signed)

b. Booleans

(ii) Floating-Point Numbers

(iii) Complex Numbers



Question : 10
What do you understand by term immutable?


Answer :

Immutable types are those data types that can never change their value in place. In Python the following types are immutable:

(i) integers

(ii) floating-point numbers

(iii) Booleans

(iv) Strings

(v) Tuples



Question : 11
What are mutable and immutable types in Python? List both of them.


Answer :

They are as follows:

  •  Lists
  •  Dictionaries
  •  Sets

Immutable types are those data types that can never change their value in place. In Python the following types are immutable:

  •  integers
  •  floating-point numbers
  •  Booleans
  •  Strings
  •  Tuples


Question : 12
What are augmented assignment operators? How are they useful?


Answer :

An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable. A simple example is x += 1 which is expanded to x = x + (1). Similar constructions are often available for various binary operators. They are helpful in making the source code small.



Question : 13
Why are logical errors harder to locate?


Answer :

in spite of logical errors presence, program executes without any problems but the output produced is not correct. Therefore, each and every statement of the program needs to be scanned and interpreted. Thus the logical errors are harder to locate.



Question : 14
What is an Exception?


Answer :

Exception in general refers to some contradictory or unusual situation which can be encountered unexpectedly while executing the program. Unhandled exceptions will cause Python to halt execution.



Question : 15
Why is Exception Handling is required?


Answer :

Unhandled exceptions will cause Python to halt execution. The exception handling is ideal for processing exceptional situations in a controlled way so that program ends gracefully rather than abrupt crashing of the program.



Question : 16
What is the need for debugger tool?


Answer :

Debugger tools are very useful especially if the code is big or the error is not very clear, it becomes very difficult to manually figure out the origin and cause of the problem. Debugger tools here prove very handy and useful. They show us the line by line execution and its result on variables interactively and help a programmer get to the root of the problem.



Question : 17
What are main error types? Which types are most dangerous and why?


Answer :

Main error types are -

(i)Compile-time errors (ii) Run-time errors (iii) Logical errors

Logical errors are most dangerous errors because these are most difficult to fix. The error is caused by a mistake in the program‘s logic. You won‘t get an error message, because no syntax or runtime error has occurred. You will have to find the problem on your own by reviewing all the relevant parts of your code – although some tools can flag suspicious code which looks like it could cause unexpected behaviour.



Question : 18
What is a difference between an error and exception?


Answer :

Exception and Error: Exceptions are those which can be handled at the run time whereas errors cannot be handled. An exception is an Object of a type deriving from the System. Exception class. System Exception is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user.



Question : 19
What is debugging and code tracing?


Answer :

Debugging involves correction of code so that the cause of errors is removed. I other words we can say that debugging means figure out the origin of error in code, fix the error code and review and rerun your code to ensure that the error is fixed.



Question : 20
What are nested Lists?


Answer :

A list can have an element in it, which itself is a list. Such a list is called nested list. e.g.

L = [1,2,3,4,[5,6,7],8]



Question : 21
Discuss the utility and significance of Lists.


Answer :

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. List is majorly used with dictionaries when there is large number of data.



Question : 22
What is the purpose of the del operator and pop method? Try deleting a slice.


Answer :

del operator is used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below –

>>>del List[index]

>>>del List[start:stop]

pop method is used to remove single element, not list slices. The pop() method removes an individual item and returns it. Its syntax is –

>>>a=List.pop() #this will remove last item and deleted item will be assigned to a.

>>>a=List[10] # this will remove the ite at index 10 and deleted item will be assigned to a.



Question : 23
What are list slices?


Answer :

List slices, like string slices are the sub part of a list extracted out. Indexes can be used to create list slices as per following format:

seq = L[start:stop]



Question : 24
What do you understand by true copy of a list? How is it different from shallow copy?


Answer :

A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won‘t create copies of the child objects themselves.

True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.



Question : 25
What do you understand by immutability?


Answer :

Immutability means not changeable. The immutable types are those that can never change their value in place. In python following types are immutable –

I. Integers

II. Floating point numbers

III. Booleans

IV. Strings

V. Tuples



Question : 26
How are Tuples different from Lists when both are sequences?


Answer :

Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but they are different in the sense that –

Tuples are immutable while lists are mutable.

List can grow or shrink while tuples cannot.



Question : 27
Discuss the utility and significance of Tuples.


Answer :

Tuples are great for holding static data that you don't plan on modifying and changing a lot. Tuples are four to seven times faster than lists. This means for every list item manipulated, four to seven tuples could be manipulated within that time frame. This has huge advantages for scientific work, as this allows for speedy data reading.



Question : 28
How can you say that a tuple is an ordered list of objects?


Answer :

A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index amd for a given index, same element is returned everytime.



Question : 29
How are dictionaries different from Lists?


Answer :

The dictionary is similar to lists in the sense that it is also a collection of data-items but it is different from lists in the sense that lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered).

Elements in lists or tuples can be accessed by using indexes. But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list.



Question : 30
When are dictionaries more useful than lists?


Answer :

Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.



Question : 31
Discuss the utility and significance of Dictionaries.


Answer :

Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.



Question : 32
Why is a dictionary termed as an unordered collection of objects?


Answer :

But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list. In dictionaries there is no index. It uses its keys as index which can be rearranged. That‘s why a dictionary termed as an unordered collection of objects



Question : 33
How is clear() function different from del Statement?


Answer :

clear() removes all the elements of a dictionary and makes it empty dictionary while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no longer exists, not even empty dictionary.



Question : 34
What is the significance of modules?


Answer :

The process of breaking a bigger unit into individual components (modules) is called modularity. Modularity reduces complexity to some degree.



Question : 35
What is dot notation of referring to objects inside a module?


Answer :

After importing a module, to access one of the functions, we have to specify the name of the module and name of the function, separated by a dot. This format is called dot notation.



Question : 36
What is a function? How is it useful?


Answer :

A function is a named block in a program which has some certain working. Whenever you call this it performs all its working. It reduces the complexity and reduces the labour of writing same code again and again.



Question : 37
What is Pandas library of Python? What is its significance?


Answer :

Pandas library of Python is for data analysis. It makes available various tools for data analysis and makes it simple and easy process.



Question : 38
How is Series data structure different from a DataFrame data structure?


Answer :

A Series is a one-dimensional object that can hold any data ype such as integer, float and strings. It has only one axis(0).

A DataFrame is a two dimensional object that can have columns with potential different types. It has two axis(axis 0 and 1).



Question : 39
What is a DataFrame object? How it is created in Python?


Answer :

A DataFrame object is a two-dimensional labeled array which is actually an ordered collection of columns where columns may store different types of data.

A dataFrame object can be created by following ways-

1. From a 2-D Dictionary

2. From a 2-D ndarray

3. From a 2-D Dictionary with values as Series object

4. From an another DataFrame object



Question : 40
What are advantages of CSV file formats?


Answer :

1. A Simple, compact and ubiquitous format for data storage.

2. A common format for data interchange.

3. It can be opened in popular spreadsheet packages like MS-Excel, Cal etc.

4. Nearly all spradsheets and databases support import/export to csv format.



Question : 41
What is sqlite3 library of Python?


Answer :

The sqlite3 library deals with communication with SQLite databases. Sqlite3 is by default bundled with Python.



Question : 42

Can nongraphic characters be used in Python ? How ? Give examples to support your answer.



Answer :

Yes, nongraphic characters can be used in Python with the help of escape sequences. For example, backspace is represented as \b, tab is represented as \t, carriage return is represented as \r.



Question : 43

What is a cross-platform software?



Answer :

A cross-platform software is a software that can run well on a variety of platforms like Windows, Linux/Unix, Macintosh, etc.



Question : 44

What are the advantages of Python programming language?



Answer :

Advantages of Python programming language are:

Easy to Use — Python is compact, programmer-friendly and very easy to use object oriented language with very simple syntax rules.

Expressive Language — Python is an expressive language, it takes fewer lines of codes to represent the same syntax.

Interpreted Language — Python is an interpreted language, not a compiled language. It makes Python an easy-to-debug language and thus suitable for beginners to advanced users.

Completeness — Python has a rich standard library that provides modules for most types of required functionality like emails, web-pages, databases, GUI development, network connections, etc.

Cross-platform Language — Python can run equally well on variety of platforms — Windows, Linux/UNIX, Macintosh, supercomputers, smart phones, etc.

Free and Open Source — Python language is freely available along with its source-code.

Variety of Usage/Applications — Python has evolved into a powerful, complete and useful language over these years. These days Python is being used in many diverse fields/applications, some of which are Scripting, Web Applications, Game development, Database Applications, System Administrations, Rapid Prototyping, GUI Programs.



Question : 45

What are some limitations of Python programming language?



Answer :

Some limitations of Python programming language are:


Not the Fastest Language — As Python is an interpreted language so its execution-times are not that fast compared to some compiled languages.

Lesser Libraries than C, Java, Perl — Library collection of C, Java, Perl is better than Python.

Not easily convertible — Translating Python programs to other languages is difficult due to its lack of syntax.

Not strong on Type-Binding — Python interpreter is not very strong on catching 'Type-Mismatch' issues.



Question : 46

In how many different ways, can you work in Python?



Answer :

We can work in Python in two ways:


Interactive mode (also called Immediate mode)

Script mode



Question : 47

What are advantages/disadvantages of working in Interactive mode in Python?



Answer :

Interactive mode is useful for testing code. We can type the commands one by one and get the result of error immediately for each command. Disadvantages of Interactive mode are that it does not save commands in form of a program and also output is sandwiched between commands.



Question : 48

What are the advantages/disadvantages of working in script mode in Python?



Answer :

Script mode is useful for creating programs and then run the programs later and get the complete output. It is not suitable for testing code.




Question : 49

How are keywords different from identifiers ?



Answer :

Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects, classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with either a letter or underscore. For example, _chk, chess, trail, etc.



Question : 50

How are floating constants represented in Python ? Give examples to support your answer.



Answer :

Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:


Fractional Form — 2.0, 17.5, -13.0, -0.00625

Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3



Question : 51

How are string-literals represented and implemented in Python ?



Answer :

A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-literals in Python are implemented using Unicode.



Question : 52

What are operators ? What is their function ? Give examples of some unary and binary operators.



Answer :

Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).



Question : 53

What is an expression and a statement ?



Answer :

What is an expression and a statemenAn expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.

A statement is a programming instruction that does something i.e. some action takes place. For example:

print("Hello")

a = 15

b = a - 10t ?



Question : 54

What all components can a Python program contain ?



Answer :

A Python program can contain various components like expressions, statements, comments, functions, blocks and indentation.



Question : 55

What do you understand by block/code block/suite in Python ?



Answer :

A block/code block/suite is a group of statements that are part of another statement. For example:

if b > 5:
    print("Value of 'b' is less than 5.")
    print("Thank you.")




Question : 56

What are variables ? How are they important for a program ?



Answer :

Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.



Question : 57

What do you understand by undefined variable in Python ?



Answer :

In Python, a variable is not created until some value is assigned to it. A variable is created when a value is assigned to it for the first time. If we try to use a variable before assigning a value to it then it will result in an undefined variable. For example:


print(x)   #This statement will cause an error for undefined variable x
x = 20
print(x)

The first line of the above code snippet will cause an undefined variable error as we are trying to use x before assigning a value to it.



Question : 58

What is Dynamic Typing feature of Python ?



Answer :

A variable pointing to a value of a certain type can be made to point to a value/object of different type. This is called Dynamic Typing. For example:

x = 10
print(x)
x = "Hello World"
print(x)




Question : 59

What is the common structure of Python compound statements?



Answer :

The common structure of a Python compound statement is as shown below:


<compound statement header>:

    <indented body with multiple simple\

     and/or compound statements>


It has the following components:


A header line which begins with a keyword and ends with a colon.

A body containing a sequence of statements at the same level of indentation.



Question : 60

What is the importance of the three programming constructs?



Answer :

The importance of the three programming constructs is a given below:


Sequence — Statements get executed sequentially.

Selection — Execution of statements depends on a condition test.

Repetition\Iteration — Repetition of a set of statements depends on a condition test.



Question : 61

What is empty statement in Python? What is its need?



Answer :

In Python, an empty statement is pass statement. Its syntax is:


pass

When pass statement is encountered, Python does nothing and moves to next statement in the flow of control.


It is needed in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not.



Question : 62

Which Python statement can be termed as empty statement?



Answer :

In Python, an empty statement is pass statement. Its syntax is:


pass


Question : 63

What is an algorithm?



Answer :

An algorithm is defined as the sequence of instructions written in simple English that are required to get the desired results. It helps to develop the fundamental logic of a problem that leads to a solution.



Question : 64

What is a flowchart? How is it useful?



Answer :

A flowchart is a pictorial representation of an algorithm. It uses boxes of different shapes to represent different types of instructions. These boxes are connected with arrow marks to indicate the flow of operations. It helps in:


Communication — The pictorial representation of the flowchart provides better communication. It is easier for the programmer to explain the logic of a program.

Effective Analysis — It is a very useful technique, as flowchart is a pictorial representation that helps the programmer to analyze the problem in detail.



Question : 65

What is entry-controlled loop?



Answer :

An entry-controlled loop checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop.



Question : 66

What are the four elements of a while loop in Python?



Answer :

The four elements of a while loop in Python are:


Initialization Expressions — It initializes the loop control variable and it is given outside the while loop before the beginning of the loop.

Test Expression — If its truth value is true then the loop-body gets executed otherwise not.

The Body of the Loop — It is the set of statements that are executed repeatedly in loop.

Update Expressions — It updates the value of loop control variable and it is given inside the while loop.



Question : 67

What is the difference between else clause of if-else and else clause of Python loops?



Answer :

The else clause of an if-else statement is executed when the condition of the if statement results into false. The else clause of a loop is executed when the loop is terminating normally i.e., when its test condition has become false for a while loop or when the for loop has executed for the last value in sequence.



Question : 68

In which cases, the else clause of a loop does not get executed?



Answer :

The else clause of a loop does not get executed if the loop is terminated due to the execution of a break statement inside the loop.



Question : 69

What are jump statements? Name them.



Answer :

Jump statements are used to unconditionally transfer program control to other parts within a program. Python provides the below jump statements:


break

continue



Question : 70

How and when are named conditions useful?



Answer :

Sometimes the conditions being used in the code are complex and repetitive. In such cases, to make the program more readable and maintainable, named conditions can be used.



Question : 71

What are endless loops ? Why do such loops occur?



Answer :

A loop which continues iterating indefinitely and never stops is termed as an endless or infinite loop. Such loops can occur primarily due to two reasons:


1. Logical errors when the programmer misses updating the value of loop control variable.

2. Purposefully created endless loops that have a break statement within their body to terminate the loop.



Question : 72

How is break statement different from continue?



Answer :

When the break statement gets executed, it terminates its loop completely and control reaches to the statement immediately following the loop. The continue statement terminates only the current iteration of the loop by skipping rest of the statements in the body of the loop.




Question : 73

Define Operator and Operand.



Answer :

An Operator is a particular symbol which is used on some values and produces an output as a result. An operand is an entity on which an operator acts. For example, in the following expression:
c=a+b
the sign + is an operator on the two operands a and b. 



Question : 74

What is the use of type()?



Answer :

To verify the type of any object in Python, use the type() function.



Question : 75

The modulus operator is used to produce the quotient in division. Is it True or False ? 



Answer :

False, the modulus operator is used to produce the remainder.



Question : 76

Describe the use parentheses in expressions.



Answer :

Parentheses can be used to group terms in an expression so as to provide control over the order in which the operations are performed.



Question : 77

Describe how Python evaluates an expression containing parentheses.



Answer :

A Python expression is evaluated by first evaluating each of the sub-expressions in the parentheses, and then using those values to complete the evaluation. If the expression contains nested parentheses, the evaluation is performed by evaluating the innermost parentheses first and working outwards from there.



Question : 78

Explain the use of the assignment operator.



Answer :

The assignment operator causes the value of its right operand to be stored in the memory location identified by its left operand.



Question : 79

What is the difference between Expressions and Operators?



Answer :

Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2+3. An expression is a combination of operators and operands.
Operators are functionality that do something and can be represented by symbols, such as + or by special keywords. They require some data to operate on and such data is called operands.



Question : 80
Example not (boolean Not) with an example.


Answer :

The not operator is used to reverse the logical state of its expression. Logical not returns True is the expression is false and False if the expressions is true. For example,

If * is ture , it returns False.

if * is false, it returns True

* =   True                                                                                                                                                                                                                                                                                                                                 



Question : 81
Example not (boolean Not) with an example.


Answer :

The not operator is used to reverse the logical state of its expression. Logical not returns True is the expression is false and False if the expressions is true. For example,

If * is ture , it returns False.

if * is false, it returns True

* =   True ;

not * returns False.                                                                                                                                                                                                                                                                                                                              



Question : 82

Example and (boolean AND) with example.



Answer :

The and operator evaluates to True, if both the expressions are true; False if either or both operands evaluate to False. For example,

x and y returns False if x is False, else it returns evaluation of y

x= False;

y=True;

x and y returns False since x is False.

in this case, Python will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values.



Question : 83

Example or (boolean OR) with example.



Answer :

The or operator evaluates to True, if either of operands evaluates to true; False if both operands evaluate to False. For example,

if x is True, it returns True, else it returns evaluation of y

x= True;

y= False;

x or y returns True.



Question : 84

Explain Associativity of operators wit6h example.



Answer :

Associativity means the order in which the two operators with the same precedence should be applied in an expression. It is usually associated from left to right . This means that operators with the same precedence are evaluated from left to right manner. For example, 2+3-4 is evaluated as (2+3)-4.

Some operators like assignment operators have right to left associativity. i.e., a=b=c is treated as a= (b=c).



Question : 85

What is the difference between * and **? Explain with an example.



Answer :

* ( multiply) gives the multiplication of the two numbers or returns the string repeated that many times. For example,

2 * 3 gives 6.

'la' * gives 'lalala'.

** (power) returns x to the power of y. For example,

3 ** 4 gives 81 (i.e., 3 * 3 * 3 * 3 )




Question : 86

What is the difference between << (left shift) and >> (right shift) operators ?



Answer :

<< (left shift) Shift the bits of the number to the left by the number of bits specified. (Each number is represented in memory by bits or binary digits, i.e., 0 and 1)

For example, 2 << 2 gives 8.2 is represented by 10 in bits.

Left shifting by 2 bits gives 1000 which represents the decimal 8.

>> ( right shift) Shift the bits of the number to the right by the number of bits specified.
For example, 11 >> 1 gives 5.
11 is represented in bits by 1011, which when right shifted by 1 bit gives 101 which is the decimal 5.



Question : 87

What is the difference between & (bit-wise AND), and I  (bit-wise OR) operators?



Answer :

Bit-wise AND (&) returns 1 if both the bits are 1, otherwise 0. For example, the numbers 5 & 3 gives 1.

Bit-wise OR (|) returns 1 if any both of the bits is 1. If both the bits are 0, then it returns 0. For example, the numbers 5 | 3 gives 7.




Question : 88

Explain not ( boolean NOT ) with an example



Answer :

The not operator is used to reverse the logical state of its expression. Logical not returns True if the expression is false and False if the expression is true. For example

If x is True, it returns False.

If x is False, it returns True.

x=True;

not x returns False.



Question : 89
What is an expression ?


Answer :

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable. Hence the following are all legal expressions (assuming that the variable x has been assigned a value):
17
x
x + 17



Question : 90

What is a statement ?



Answer :

A statement is a unit of code that the Python interpreter can execute.



Question : 91

What do you mean by floor division ?



Answer :

The operation that divides two numbers and chops off the fractional part. For example, assuming a=15.9, b=3, c=a / / b gives value 5.0, not 5.3.



Question : 92

What is the difference between "=" and "=="  ?



Answer :

"=" is the assignment operator whereas "==" is the equality operator. The assignment operator is used to assign a value to an identifier, whereas the quality operator is used to determine if two expressions have the same value. 



Question : 93

What don you mean by precedence and associativity of operators ?



Answer :

The operators in Python are grouped hierarchically according to their precedence (i.e, order of evaluation ).Operations with a higher precedence are carried out before operations having a lower precedence than any of the other operators.

The order in which consecutive operations within the same precedence group are carried out is know as associativity.



Question : 94

What are Identity and Membership operators ?



Answer :

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
Membership operators are used to if an object is present in a sequence.



Question : 95

Explain different bitwise operators.



Answer :

& (AND) : Sets each bit to 1 if both bits are 1 
| (OR) : Sets each bit to 1 if one of two bits is 1 
^ (XOR) : Sets each bit to 1 if only one of two bits is 1
~ (NOT) : Inverts all the bits
<< (Left Shift) : Zera fill left shift enables to shift left by pushing zeros in from the right and lets the leftmost bits fall off.
>> (Right Shift) : Signed right shift enable to shift right by pushing copies of the leftmost bit in from the left, and lets the rightmost bits fall off.



Question : 96

What will be the result of 5.0/3 and 5.0 / / 3 ?



Answer :

>>> 5.0 / 3
1.6666666666666667
>>> 5.0 / / 3
1.0



Question : 97
What is the difference between + and * operators of List ?


Answer :

The plus (+) sign is the list concatenation operator, while the asterisk ( * ) is the repetition operator.



Question : 98

What is boolean data type ? Explain with an example.



Answer :

Comparisons in Python can only generate one of the two possible responses: True or False.
These data types are called booleans.
To illustrate, you can create several variables to store Boolean values and print the result:

boo1_1=4==2*3
boo1_2=10<2*2**3
boo1_3=8>2*4+1
print (boo1_1)
print (boo1_2)
print (boo1_3)

RUN
False
True
False



Question : 99

What is the difference between pow() and**?



Answer :

Both pow () and the double star (**) operator perform exponentiation. ** is an operator whereas pow () is a built-in function.



Question : 100

What is the deference between expression and statement ?



Answer :

Statement is an instruction or a unit of code that the Python interpreter can execute. For example, print ("Welcome") is a statement. statement may or may not return a value as outcome.



Question : 101

What is the difference between num = 20 and num == 20?



Answer :

In num = 20, variable num is assigned the value 20
In num == 20, variable num is compared with the value 20



Question : 102

What is conditional branching ?



Answer :

In Conditional branching, a program decides whether or not to execute the next statement (s),based on the resultant value of the current expression. For example, go to second year if you pass first year exams, else repeat first year exam, else repeat first year.



Question : 103

What is looping ?



Answer :

In looping, a program performs a set of actions or operations repeatedly till the given condition is true. Looping, for example, adds 1 to number x till current value of x becomes 100. It is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly, until the specified condition is true. 



Question : 104

Explain if statement.



Answer :

The ststement if tests a particular condition. Whenever that condition evaluates to true, an action or a set of actions is executed. Otherwise, the actions are ignored.



Question : 105

Explain range() function ?



Answer :

Python rance() function generates a list of numbers, which is generally used to iterate cover with for loops.



Question : 106

Mention the similarity and difference between break and continue statements.



Answer :

Similarity: Both break and continue are jump statement.
Difference : The break statement terminates the entire loop body whereas continue statement forces the next iteration of the loop to take place, skipping any code following continue statement in the current iteration of the loop.



Question : 107

What is the function of break statement in a while or for loop ?



Answer : If the break statement is included in the while, or for, loop then control will immediately be transferred out of the loop when the break statement is encountered. This provides a convenient way to terminate the loop if an error or other irregular condition is detected.

Question : 108

What is the use of Control structures ?



Answer :

Control structures allow us to change the sequence of instructions for execution. They also implement decisions and repetitions in programs.



Question : 109

How many types of control structures are there ? Explain.



Answer :

There are mainly two types of control structures. These are:

  • Conditional Controls : They allow the computer to take decision as to which statement is to be executed next.
  • Looping : It allows the computer to execute a group of statements repeatedly till the condition is satisfied.


Question : 110

Explain Selection logic.



Answer :

Selection logic, also known as decision logic, is used for making decisions. It is used for selecting the proper path out of the two or more alternative paths in the program logic, It is depicted as either an IF...THEN...ELSE or IF...THEN structure.



Question : 111

What do you mean by flow-of-control ?



Answer :

The flow-of-control of a program is the order in which the statements are executed one after the other sequentially.



Question : 112

What do you mean by selection statements ?



Answer :

In some programs, you may need to change the sequence of execution of instructions according to specified conditions. This is done by selection statements.



Question : 113

What is the minimum number of iteration that while loop could make ?



Answer :

while loop could make 0 iteration.



Question : 114

What is the difference between entry controlled loop and exit-controlled loop?



Answer :

In an entry-controlled loop, the loop control condition is evaluated at the entry point of the loop. However, in an exit-controlled loop, the loop control condition is evaluated at the exit point of the loop.
If the loop control condition is false in the beginning, the entry-controlled loop is never executed. However, the exit-controlled loop would be executed at least once.



Question : 115

What are jump statements ?



Answer :

Jump statements are the statements that allow us to transfer control to another part of our program.



Question : 116

What is Iteration ?



Answer :

It is a process of executing a statement or a set of statements repeatedly, until the specified condition is true.



Question : 117

What are strings ?



Answer :

A string is a sequence of characters. IT is basically just a bunch of words. It is the from of data used in programming for storing and manipulating text, such as words, names and sentences. We can write it in Python using sentences. We can write it in Python using single quotes, double quotes, or triple quotes.



Question : 118

Differentiate between physical line and logical line.



Answer :

A physical line is what we see when we write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.



Question : 119

What is the difference between (+) and (*) operators?



Answer :

The plus (+) sign is the string concatenation operator while the asterisk (*) is the repetition operator, We can concatenate strings with the "+" operator and create multiple concatenated copies of the string with the "*" operator. The use of + and * makes sense by analogy with equivalent to 4+4+4,mnwe expect 'Save' *3 to be the same as 'Save' + 'Save' + 'Save'.



Question : 120

What is the difference between Istrip() and rstrip() ?



Answer :

Istrip() removes characters (including white space characters) from the left, based on the argument passed whereas rstrip() removes characters (including whitespace characters) from the right, based on the argument passed. 



Question : 121

What do you mean by' strings are immutable ?



Answer :

Strings are immutable means that the contents of the string variable cannot be changed after it is created.



Question : 122

What is the function of slicing operation ?



Answer :

We can retrieve a slice (substring) of a string with a slice operation. The slicing operation is used by specifying the name of the sequence, followed by an optional pair of numbers separated by an optional pair of numbers separated by a colon, enclosed within square brackets.



Question : 123

What is the use of Docstrings ?



Answer :

Python has a feature called documentation strings, usually referred to by its short name, docstrings. Docstring is an important tool that we should make use of since it helps document the program better and makes it easier to understand.



Question : 124

How are empty strings represented in Python ?



Answer :

An empty string contains no characters and has length 0, represented by two quotation marks in Python .



Question : 125

"The quotes are not a  part of strings". Comment.



Answer :

The quotes are not a part of string. They only tell the computer where the string constant begins and ends. They can have any character or sign, including space in between them. 



Question : 126

Differentiate between ord() and chr() functions.



Answer :

ord() function returns the ASCII value of a character and requires single character only whereas chr() function takes ASCII value in integer from and returns the character corresponding to the ASCII value.



Question : 127

Write short note on subscript.



Answer :

A string is a sequence of characters. We can access the characters one at a time with the bracket operator. An individual character in a string is accessed using a subscript (index). The subscript should always be an integer (positive or negative)



Question : 128

 What do you mean by positive and negative indices ?



Answer :

In Python, indices that begin from 0 onwards indices, and the indices which begin from -1,-2,-3 in the backward direction are called negative indices. Positive subscript helps in accessing the strings from the beginning. Negative subscript helps in accessing the string from the end.



Question : 129

'String indices must be an integer'. Comment.



Answer :

We can se any expression, including variables and operators, as an integer. Otherwise, we might get an error. We can also use negative indices, which count backward, i.e., from the end of the string to the beginning.



Question : 130

 What do you mean by traversing a string ?



Answer :

Traversing a string means accessing all the elements of the string one after the other by using the subscript or index.



Question : 131

Write short note on membership operators.



Answer :

in and not in are membership operators. in operator returns true if a particular sub-string.
not in operator does the exact reverse of in. It returns true if a particular substring s not present in the specified string.



Question : 132

What is the significance of list ?



Answer :

A list is a collection of a number of values or variables in an ordered sequence. These values are called elements. The element can be any Python objects, including numbers, strings, functions, and other lists.



Question : 133

Lists are mutable. Comments ?



Answer :

Lists are mutable. This means that value of an item in a list can be modified with an assignment statement.



Question : 134

Why are Python Lists called dynamic arrays ?



Answer :

Lists are dynamic arrays. They are arrays in the sense that we can index items in a list (for example, mylist[3]), and we can select subranges (for example, mylist[2:4]).
They are dynamic in the sense that we can add and remove items after the list is created. 



Question : 135

How do list indices work in Python ?



Answer :

List indices work in the same way as string indices:
(a) Any integer expression can be used as an index.
(b) If we try read or write an element that does not exist, we get an IndexError.
(c) If an index has a negative value, it counts backward i.e., from the end of the list. 



Question : 136
Explain count() method with example.


Answer :

The count method counts the occurrences of an elements in a list. Fox example,
>>> [ 'to', 'be', 'or'. 'not','to','be'].count ('to')
2                                                                                                                                                                                                                                                                



Question : 137

What is index() method used for ?



Answer :

The index() method is used for searching lists to find the index of the first occurrence of a value. For example,
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say',' in' ]
>>> knights.index('who')
4



Question : 138

What is aliasing ? Explain with an example.



Answer :

A circumstance where two or more variables refer to the same object is called aliasing. If variable a refers to an object and we assign b to a, then both variables refer to the same object.
For example,
>>> a = [ 1,3,5 ]
>>> b = a
>>> b is a 
true



Question : 139

What do you mean by sequence ?



Answer :

A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and non-mutable data types. There types of sequence data types available in Python are strings, lists, and tuples.



Question : 140

What is indexing ?



Answer :

All elements in a sequence are numbered as from 0, 1, 2, and so on. We can access them individually with their respective number. This is called indexing. We use an index to fetch an elements. All sequences can be indexed in this way. When we use a negative index, Python counts from the right, that is, from the last element. The last element is at position -1. 



Question : 141

What is the default value for the first index if you omit the first index value in a slice ?



Answer :

The default value is zero (0).



Question : 142

What is the default value for the second index if you omit the second index value in a slice?



Answer :

The default value for the second index is the length of the string ( the actual number of characters in the strings ).



Question : 143

What is the purpose of negative slice indices ?



Answer :

Negative indices can be used to count from the right end of the string.



Question : 144

Explain the functions of del statement, pop() and remove().



Answer :

The del statement can be used to remove an individual item, or to remove all items identified by a slice. The pop() method removes an individual item and returns it, while remove() searches for an item and returns it, while remove() searches for an item, and removes the first matching item from the list.



Question : 145

If two list are equivalent, is it necessary that they are identical also. Explain with an example.



Answer :

>>> a = [ 2, 4, 6 ]
>>> b = [2, 4, 6 ]
>>> a is b
False
Above two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necesarily identical.



Question : 146
Name three types of sequence objects.


Answer :

The types of sequence objects are string, tuple, and list.



Question : 147

Which item in the sequence is selected for an index value of - 1?



Answer :

The last item in the sequence is selected for an index value of -1



Question : 148

Just like C, C++, and Java, Python supports character type; True or False ?



Answer :

False. There is no character type in Python. Rather, a string items are characters.



Question : 149

How are lists formed ?



Answer :

Lists are formed by placing a commaseparated sequence of expression in square brackets



Question : 150

What are the characteristics of list ?



Answer :

A list is a sequence of  items stored as a single object. Characteristics of list are as follows:
(a) Items in a list can be accessed by indexing, and sublists can be extracted by slicing.
(b) Lists are mutable; individual items or entire slices can be replace through assignment statements.
(c) Lists can grow and shrink as needed. 



Question : 151

What is tuple ?



Answer :

Tuples are a sequence of values of any type, indexed by integers. They are immutable. They are enclosed in ().



Question : 152

A tuple in Python is immutable. Comment.



Answer :

A tuple in Python is immutable. This means, it cannot be modified as immutable object cannot be changed. Once created, it always has the same values.



Question : 153

What is the difference between objects and methods ?



Answer :

Strings,  lists, and tuples are objects, which means that they not only hold values, but they also have built-in behaviors called methods, that act on the values in the object.



Question : 154

Is an item assignment an a tuple possible ?



Answer :

No, an item assignment statement in tuple is not possible.



Question : 155

What is len() function used for in list and tuple?



Answer :

With lists and tuples, len() function returns the number of elements in the sequence, For example,
>>> len ( [ 'a' , 'b', 'c', 'd', ] )
4
>>> len ( ( 2, 4, 6, 8, 10, 12 ) )
6



Question : 156

What is the use of in operator ?



Answer :

The in operator cheeks whether the given element is contained in the tuple or not. For example,
>>> 4 in ( 2, 4, 6, 8 )
True
>>> 5 in ( 2, 4, 6, 8 )
False



Question : 157

Write short note on tuple assignment.



Answer :

An assignment to all the elements in a tuple is done using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.



Question : 158

How will you create tuple with zero element and 1 element ?



Answer :

Zero element: To create a tuple with zero elements, use only a pair of parentheses  "()". For example,
# Zero element tuple
x = ()

One element: For a tuple with one element, use a trailing comma.
# One-element tuple
y = ( "Sunday" ,)



Question : 159

Compare and contrast tuples and list.



Answer :

Tuples are very similar to lists, but tuples cannot be changed, i.e., no change in the contents of the tuple is allowed. A tuple can be viewed as a 'constant list'. While lists employ square brackets, tuples are written with standard parentheses or no parentheses.  



Question : 160

Can we update tuples?



Answer :

Like numbers and strings, tuples are immutable which means we cannot update them or change values of their elements.



Question : 161

What is the difference between list and tuple ?



Answer :

Lists are enclosed in brackets [ ], and their elements and size can be changed, whereas tuples are enclosed in parentheses ( ) and cannot be updated. Tuples can be thought of as "read only" lists.



Question : 162

Identity the following as mutable or immutable:
lists, numbers, strings, tuples and dictionaries.



Answer :

Mutable : lists, dictionaries
Immutable : numbers, strings, tuples



Question : 163

How will you create an empty tuple ?



Answer :

We can create an empty tuple using built-in function tuple() as follows:
>>> t = tuple ()
>>> print t
()



Question : 164

What is dictionary?



Answer :

A dictionary is another container type that can store any number of Python objects, including other container types. It is mutable. It consists of pairs (called items) of keys and their corresponding values. It is also known as associative array or hash table.



Question : 165

Compare and contrast dictionaries (dicts) with other Python data types.



Answer :

(a) Dictionaries are a container type that store data, like lists and tuples.
(b) Dictionaries are a mapping data type indexed by text (keys). The dictionary's elements (the items it contains) are key:value pairs. In contrast, lists and tuples store data by using numeric indexes (they are sequence data types) and support indexing and slicing.
(c) Dictionaries are mutable. That means, a dictionary can be modified in place; we do not have to create a copy of it to modify it (as we do with strings and tuples ). However, a dict's keys must be immutable.



Question : 166

What are the advantages of hash ?



Answer :

Hashes are used for space-efficient storage, for security and cryptography, and so on. Another benefit of hashing is that after the hash value is computed, keys can be looked directly; there's no need for the computer to search through a whole list of keys. In Python, This feature makes dictionaries very fast.



Question : 167

Does Python store dictionary elements in any particular order?



Answer :

No, python does not store dictionary elements in any particular order. If we enter elements in one order, they may be stored in another (essentially random) order inside Python. For example,
>>> D1 = { ' sleep' : " All night ", 'work' : "All day"}
>>> D1
{ 'work' : 'All day', 'sleep' : 'All night' }



Question : 168

What is a mapping ?



Answer :

A mapping is a structure in which values are stored and retrieved according to a key. This data type is unordered and mutable. However keys of a dictionary must be unique and immutable. This is often called a dictionary, as it behaves similar to a common dictionary.



Question : 169

What is another name for mapping ?



Answer :

A dictionary.



Question : 170

What are the characteristics of a Python dictionary?



Answer :

The characteristics of a Python dictionary are as follows:
(a) A dictionary is an unordered collection of objects.
(b) Values are accessed using a key rather than an ordinal numeric index.
(c) The dictionary can shrink or grow as needed.
(d) It can be nested.
(e) The contents of dictionaries can be modified.



Question : 171

A dictionary is an mutable object. Comment.



Answer :

A dictionary is mutable as its existing items can be modified, new items can be added to it, and existing items can be deleted from it.



Question : 172

A dictionary is an unordered collection of objects. Comment.



Answer :

The items in a dictionary are not maintained in any specific order, and the dictionary can contain references to any type of objects.



Question : 173

Can sequence operations, such as slicing and concatenation, be applied to dictionaries?



Answer :

No, the dictionary is not a sequence. Since it is not maintained in any specific order, operations that depend on the specific order cannot be used. 



Question : 174

Write the syntax of a dictionary.



Answer :

A dictionary consists of one or more key:value pairs, separated by commas, and enclosed in a pair of curly braces. It can be empty also, i.e., having no items.



Question : 175

Can you remove key:value pairs from a dictionary. If so, how ?



Answer :

We can use del statement to remove an existing key:value pair from a dictionary.



Question : 176

What do you mean by traversing a dictionary ?



Answer :

Traversing a dictionary means visiting each element of the dictionary to display its values on the screen.



Question : 177

Can you merge two dictionaries ? If so, how?



Answer :

Two dictionaries can be merged into one by using update() method. It merges the keys and values of one dictionary with that of another and overwrites values of the same key.



Question : 178

Discuss the properties of Dictionary Keys.



Answer :

There are few properties which should be considered while using dictionary keys:
(a) More than one entry per key is not allowed ( no duplicate key is allowed ).
(b) The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples, or strings.
(c) Dictionary keys are case sensitive. Same key name but with the different case are treated as different keys in Python dictionaries. 



Question : 179

What do the keys(), values() and items() functions do ?



Answer :

keys(): Returns a list of the keys.
values(): Returns a list of the values.
items(): Returns a list of tuples (key,value)
representing the key:value pairs.



Question : 180

Write different capabilities of dictionary.



Answer :

A dictionary has the following capabilities:
(a) Ability to iterate over keys or values or key-value pairs.
(b) Ability to add key-value pairs dynamically.
(c) Ability to look for a value by key.



Question : 181

Write difference between lists and dictionaries.



Answer :

The difference between lists and dictionaries are:
(a) In dictionary, index value can be of any data type and is called key, but in list index value is an integer.
(b) No sequence operation such as slicing and concatenation be applied to dictionaries as dictionary is not a sequence. Since it is not maintained in any specific order, operation that depends on a specific order can not be used where as slicing and concatenation are applied on lists.
(c) List are sequential collections (ordered) and dictionaries are non-sequential collections (unordered).



Question : 182

What is the purpose of a header file in a Python program?



Answer :

A header file provides a centralized location for the declaration of all extern variables, function prototypes, etc. Files that must use or define a variable or a function, include header file(s). By using header files, two main safeguards are provided.



Question : 183

What is function ?



Answer :

A named sequence of statements that performs some useful operation. functions may or may not take arguments and may or may not produce a result.



Question : 184

What are the advantages of using functions.



Answer :

Functions let us write code only once.
Functions hide unnecessary complexity from the user.
Functions make our code easier to understand.
Functions help us organize our program logically.



Question : 185

What is function definition ?



Answer :

A statement that creates a new function, specifying its name, parameters, and the statements it executes is called function definition.



Question : 186

Write a short note on built-in function.



Answer :

Built-in functions are then functions that are built into Python and can be accessed by programmer any time without importing any module (file) such functions are input(), int(), float(), type(), help() etc. 



Question : 187

How is built-in function accessed ?



Answer :

Built-in function is accessed simply by writing the function name, followed by an optional list of arguments that represent information being passed to the function.



Question : 188

How will you import all functions in the math module ?



Answer :

from math import *



Question : 189

What is difference between cell() and floor() functions?



Answer :

The function ceil() returns the smallest whole number greater than or equal to x . The floor() function returns the largest whole number less than or equal to x .



Question : 190

What is Python module ?



Answer :

A module is a file that contains a collection of related functions and other definitions. We can make a mudule available to another program by importing it.



Question : 191

How will you import specific names only within a module?



Answer :

We can import specific names only within a module, without importing the whole module, by using the  from  <module>  import  <name>  statement.



Question : 192

Write short note on user defined function.



Answer :

A part from the library functions that are in built in Python, users can also define functions to do a task relevant to their programs. Such functions are called user-defined functions. These functions should be codified by the user, so that any call to the function can refer to it.



Question : 193

What is difference between pow() and **?



Answer :

Both pow() and the double star (** ) operator perform exponentiation. ** is an operator and pow() is a built-in function.



Question : 194

What do you mean by Regular expressions ?



Answer :

Regular expressions called regexes for short, are descriptions for a pattern of text. For example, a\ d in a regex stands for a digit character. They allow us to specify a pattern of text to search for. 



Question : 195

What is a metacharacter?



Answer :

Each character in a Python Regex is either a metacharacter or a regular character. A metacharacters are characters with a special meaning, while a regular character matches itself.



Question : 196

How match() function is different from search() function ?



Answer :

The match() function returns a match object if the text matches the pattern. Otherwise it returns None. The match() functions looks for a pattern at the beginning of a string. The search() function checks for a match anywhere in the string. If there is more than one match, only the first occurrence of the match will be returned.



Question : 197

What do you mean by greedy match and non greedy match ?



Answer :

When a special character matches as much of the search sequence (string) as possible, it is said to be a greedy match. Non greedy matches the smallest number of repetitions.



Question : 198

Differentiate between max() and min() functions ?



Answer :

Python built-in function max() returns the largest of its parameters. Python built-in function min() returns the smallest of its parameters.



Question : 199

Write a short note on random module.



Answer :

The random module contains function related to generating random numbers and producing random results. Random numbers have many applications in science and computer programming, especially when there are significant uncertainties in a phenomenon of interest.



Question : 200

Write a short note on randint().



Answer :

If we wanted a random integer, we can use the randint() function. Randint accepts two parameters: a lowest and a highest number, and returns an integer between lowest and highest (including both).



Question : 201

Observe the following Python function and write the name(s) of the module(s) to which they belong:
a. uniform()  b. findall()



Answer :

a. random b. re



Question : 202

What is file Pointer ?



Answer :

When a file is opened using method, the operating system associates a pointer that points to a character in the file. The file pointer determines from where the read and write operation will take place. Initially, the file pointer points at the start of the file.



Question : 203

Discuss various modes to open a file.



Answer :

'r' : This mode indicates that file will be open for reading only.
'w' : This mode indicates that file will be open for writing only. If file, does not exists, it will create a new one.
'a' : This mode indicates that the output of that program will be append to the previous output of the file.
'r+' : This mode indicates that file will be open for both reading and writing.



Question : 204

Write short note on binary mode of opening a file.



Answer :

Binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.



Question : 205

Differentiate between read() and readline().



Answer :

read() function reads the entire file and returns a string.
readline() function reads lines from that file and returns as a string. It fetches the line n, if it is being called  nth time.

     

                                                                                                                       



Question : 206

Write function of a+ mode.



Answer :

The a+ mode opens a file for both appending and reading. The file pointer is at the end of the file if the exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.



Question : 207

What are different ways to read from a file ?



Answer :

To read a file Python provides different reading methods. There are three ways to read from a file.
read ([n])
readline ([n])
readlines ()
where n is the number of bytes to be read.
The read() method just outputs the entire file if number of bytes are not given in the argument.
The readline(n) outputs at most n bytes of a single line of a file. It does not read more than one line. The readlines() returns a list where each element is single line of that file.



Question : 208

What are command line arguments?



Answer :

Command line arguments are flags given to a program / script at runtime. They contain additional information for our program so that it can execute. 



Question : 209

Why do we use command line arguments ?



Answer :

Command line arguments give additional information to a program at runtime. This allows us to give our program different input without changing the code.



Question : 210

What is the use of getopt method ?



Answer :

This method parses command line options and parameter list.



Question : 211

What are the different file processing modes supported by Python ?



Answer :

Python provides different modes to open files. The read-only, write-only, read-write and append mode. 'r' is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open in reading and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode. 



Question : 212

What is pickling and unpickling in Python ?



Answer :

Pickling is a process in which a pickle module accepts any Python objects, converts it into a string representation and dumps it into a file by using dump() function.
Unpickling is a process of retrieving original Python object from the stored string representation for use.



Question : 213

What is the use of offset ?



Answer :

The offset refers to the byte count which determines the position relative to which the offset will move the file pointer. In other words offset is used to calculate the position of fileobject in the file in bytes. Offset is added to from_what ( reference point) to get the position.



Question : 214

Write a statement in Python to open a text file DATA.TXT so that new contents can be written in it.



Answer :

file=   open("DATA.TXT","w+") OR         file=   open("DATA.TXT","w+")



Question : 215

Differentiate between readlines() and readline() functions.



Answer :

Python's readlines() function reads all the lines in a file, while readline() only reads  one line at a time, which may help save memory.



Question : 216

Name two functions which allow us to access a file in a non-sequential or random mode.



Answer :

seek() and tell()



Question : 217

Name the file which is stored in human readable form and can also be created using any text editor.



Answer :

Text files are stored in human readable form and also be created using any text editor.



Question : 218

What is the use of seek() and tell() methods?



Answer :

To access the contents of the randomly - seek and tell methods are used. tell() method returns an integer giving the current position of object in the file. The integer returned specifies the number of bytes from the beginning of the file till the current position of file object.



Question : 219

What is the use of close() method ?



Answer :

The close() will be used to close the file object, once we have finished working on it. The method will free up all the system resources used by the file, this means that once file is closed, we will not be able to use the file object any more.



Question : 220

What do you understand by module and package ?



Answer :

A module is a file containing Python codes-including statements, variables, functions and classes. It shall be saved with file extension of ".py". On the other hand a Package is simply a directory of Python modules.



Question : 221

What do you mean by LEGB ?



Answer :

The order for name resolution (for names inside a function) is: local, enclosing function for nested def, global, and then the built-in namespaces (i,e., LEGB).
L: Local namespace which is specific to the current function.
E: for nested function, the Enclosing function's namespace.
G: Global namespace for the current module.
b: Built-in namespace for all the modules.                                                                           



Question : 222

What is namespace in Python ?



Answer :

A namespace is a naming system used to make sure that names are unique to avoid naming conflicts



Question : 223

Name any two commonly used build-in modules.



Answer :

math and random



Question : 224

What do you mean by Global variable ?



Answer :

Global variable means that it is accessible from anywhere in our script, including from within a function. It is usually defined at the top of the script or outside of the function.



Question : 225

What do you mean by Built-in ?



Answer :

Built-in means the function and variables that are already defined in Python.



Question : 226

What do you understand by following import statement :
from x import a, b, c



Answer :

It import the module X, and creates references in the current namespace to the given objects.
Or in other words, we can now use a, b and c in our program.



Question : 227

What do you mean by reloading module ?



Answer :

In reloading module, instead of creating a new module object, the existing module is re-used.
By re-using the same object, existing references to the module are preserved even if class or function definitions are modified by the reload.



Question : 228

How will you import all the attributes from a module ?



Answer :

We can also import all the attributes from a module by using *. The syntax is given below:
from  <module>  import *
For example, from math import *



Question : 229

Write short note on from-import statement.



Answer :

Instead of importing the whole module into the namespace, Python provides the flexibility to import only the specific attributes of a module. This can be done by using from import statement.
The syntax to use the from-import statement is given below:
from <  module-name>  import  <name  1>,  <name 2>.., <name n>



Question : 230

What is numpy ?



Answer :

NumPy ("Numerical Python" or "Numeric Python") is an open source module of Python that offers functions and routines for fast mathematical computation on array and matrices.



Question : 231

Name the module you will import to use numpy ?



Answer :

In order to use Numpy, we must import in your module by using a statement like:
import numpy as np



Question : 232

What is slicing ?



Answer :

Slicing in the NumPy array is the way to extract a range of elements from an array, Slicing in the array is performed in the same way as it is performed in the Python list.



Question : 233

What do you mean by Axes in numpy ?



Answer :

Numpy refers to the dimensions of its arrays as axes. Axes are always numbered 0 onwards for ndarrays.



Question : 234

What do you mean by Rank in numpy ?



Answer :

The number of axes in an ndarray is called its rank.



Question : 235

Write short note on slicing.



Answer :

Just like lists in Python, NumPy arrays can be sliced. As rrays can be multidimensional, you need to specify a slice for each dimension of the array. Slicing can be done over multiple dimensions. It cannot be used to expand the size of an array (unlike lists).



Question : 236

What is the purpose of negative index values in NumPy ?



Answer :

NumPy also supports negative index values. Using a negative index allows us to retrieve or reference locations starting from the end of the array.



Question : 237

Define Array and NumPy array.



Answer :

Array : Group or collection of similar type of elements. For example, scores of players in a cricket match, marks of students in a class etc.
NumPy array: A grid contains value of same type (homogeneous elements).



Question : 238

Explain membership operator in with example.



Answer :

Membership operator in returns true if a character exists in the given string, and false other-wise. For example,
>>>  str = "work Hard"
>>> 'w'  in str
True
>>> 'work' in str
True
>>> 'work' in str
False  # because w of work is in small case
>>> 'we' in str
False



Question : 239

What is Numpy?



Answer :

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. … A powerful N-dimensional array object. Sophisticated (broadcasting) functions.



CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online Exam Quiz O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Best Website and Software Company in Allahabad Website development Company in Allahabad