Python for Data Science: Chapter 1: Basics of Python

Basics of Python: Two Marks Important Questions and Answers

Python for Data Science

Python for Data Science: Chapter 1: Basics of Python: Anna University Part A Two Marks Important Questions and Answers

Python for Data Science

Chapter 1: Basics of Python

 

Two Marks Questions with Answers

 

1. What is script mode in python ?

Answer: The script mode in python is a mode in which the python commands are stored in a file and the file is saved using the extension .py.

 

2. What is the use of type commands in python?

Answer: The type command is used to determine the type of the value used. For example type(10) will return 10.

 

3. Explain the precedence rules used in precedence operation.

Answer:

1. P: Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 1 * (10‒5) is 5.

2. E: Exponentiation has the next highest precedence, so 2**3 is 8.

3. MDAS: Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2+3*4 yields 14 rather than 20.

4. Operators with the same precedence are evaluated from left to right. So in the expression

3‒ 2+1 will result 2. As subtraction is performed first and then addition will be performed.

 

4. What is tuple ?

Answer: Tuple is a sequence of items of any type. Syntactically tuple is a comma separated list of values.

For example ‒ The tuple can be created as follows:

>>> student = ('AAA',96,'Std_X')

 

5. What is a comment statement ? How do we use comment statements in python? Explain with examples.

Answer: Comments are non executing statements used for program understanding purposes. In python we use # symbol to write the comment. For example ‒

# This is a comment line

 

6. How to define a function in python?

Answer: The function can be defined using the def. The syntax of function definition is as follows:

def function_name(parameters) :

statements

Example

def my_function(a,b):

print("a=")

print(b= ")

 

7. Name four types of scalar objects python has.

Ans: The commonly used scalar types in python are:

1. int: Any integer.

2. float Floating point number (64 bit precision).

3. complex: Numbers with an optional imaginary component.

4. Bool: True, False.

 

8. What is a python?

Answer: Python is a high‒level, interpreted, interactive and object‒oriented scripting language. Python is designed to be highly readable. It uses english keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages.

 

9. What is pass in python?

Answer: Pass means no operation statement. It can be treated as placeholder in compound statement, where there should be blank left.

 

10. What are various control statements in python?

Ans:. Various control statements in python are ‒ if, if...else, while, for statements.

 

11. What is the use of range in python?

Answer: The range is used to represent the size of the list or a sequence. It is commonly used in a for loop to denote the element from given range.

 

12. What is the use of // operator in python?

Answer: Using // operator is used for performing the division operation. The result will be rounded and only integer value of the result will be displayed.

 

13. What are the rules for global and local variables?

Answer:

Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

 

14. Is python case sensitive language?

Answer: Yes python is a case sensitive language.

 

15. What will be the output of s*3 if s="Ureka".

Answer: The output will be UrekaUrekaUreka.

 

16. What is the purpose of ** operator ?

Answer: The operator ** is an exponent operator. It calculates the power of given number.

For example 2**3 = 8.

 

17. What is purpose of break and continue statement ?

Answer:

• The break statement is for terminating the loop statement and transfers execution to the statement immediately following the loop.

• The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

 

18. How will you check that in a string all the characters are numeric ?

Answer: Using the isnumeric() function we can check that in a string all the characters are numeric.

 

19. If we declare [10,20,30] then what is the output of 30. Justify.VD

Answer: True. It indicates that 30 is a member of the given sequence.

 

20. What is the difference between pop() and remove() function?

Answer: The pop() will return remove last element of the list and remove() will remove any desired element from the list.

 

21. How to represent string in python?

Answer: The string is represented using either double quotes or single quotes.

 

22. What are the operating systems on which the python program runs ?

Answer: The python is platform can run on Windows, Mac, Linux and so on. It is a platform independent language. S

 

23. What is a Boolean value ?

Answer: A Boolean value is either true or false. It is named after the British mathematician, George Boolean, who first formulated Boolean algebra ‒ some rules for reasoning about and combining these values. This is the basis of all modern computer logic.

 

24. What are the python language supports the types of operators?

Answer:

•  Arithmetic operators

• Comparison (Relational) operators

• Assignment operators

• Logical operators

• Bitwise operators

• Membership operators

• Identity operators.

 

25. What is the meaning of iteration?

Answer: Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.

Repeated execution of a set of statements is called iteration.

 

26. What are the python supports the control statements ?

Answer:

Control statement       Description

break statement   ‒   Terminates the loop statement and transfers execution to the statement immediately following the loop.

continue statement   ‒   Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

pass statement     ‒    The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

 

27. State about logical operators available in python language with example.

There are three types of logical operators and or, not.

Operators

and: If both the operands are true then the entire expression is true.  Example: a and b

or: If either the first or second operand is true. Example: a or b

not: If the operand is false then the entire expression is true. Example: not a

For example

In [1]: a=True

b=False

a and b

False

In [2]: a or b

True

In [3]: not a

False

 

28. Define recursive function.

Answer: Recursion is a property in which one function calls itself repeatedly in which the values of function parameters get changed on each call.

 

29. Present the flow of execution for a while statement

The while statement is popularly used for representing iteration.

Syntax

while test_condition:

body of while

Flowchart for while statement is as given below


For example

while i<= 10:

      i=i+1

 

30. What is module ?

Answer: The modules are basically the files having .py extension and containing some special functionalities.

 

31. Write a python script to display current date and time.

Answer:

import datetime

now = datetime.datetime.now()

print ("Current date and time: ")

print (now.strftime("%Y‒%m‒%d %H:%M:%S"))

 

32. Write a note on modular design.

Answer: Modular design approach in python is a design technique which allows to keep the python code in separate files. The executable application will be created by putting all the modules together. It makes the application readable, reliable and maintainable.

 

33 . What are Lists in python ? Give example.

Answer: Lists is a sequence of values enclosed within a square bracket.

For example [10,20,30,40]

 

34. What is the use of* operator in association with list in python?

Answer: The* operator is used to repeat the list number of times. For example :

[1,2,3]*3 will give

[1,2,3,1,2,3,1,2,3]

 

35. What is the purpose of extend method in python?

Answer: The extend method takes new list as argument and append it with old list. Thus using extend two lists can be combined.

 

36. Suppose you have given a list a=[1,2,3,4], how will you iterate through this list and print each element of it?

Answer: Following python code is used for iterating through the list and display of the numbers

>>> a=[10,20,30,40]

>>> for i in range(len(a)):

print(a[i])

 

37. What is mutability property? List is mutable or immutable.

Answer: Mutability is a property indicating whether we can change the element of the sequence or

not. List is mutable. That means we can change the element of list.

 

38. What is aliasing ?

Answer: An object with more than one reference has more than one name, so we say that the object is aliased.

For example ‒

>>> x=[10,20,30]

>>> y=x

>>> y is x

True

 

39. What is tuple? How literals of type tuple are written give example.

Answer: Tuple is a sequence of values. It is similar to list but there lies difference between tuple and

list.

Examples of tuples

T1=(10,20,30,40)

T2=('a','b','c','d')

 

40. Differentiate between tuple and list.

Answer:


Tuple

Tuple use parenthesis

Tuples can not be change

List

List use square brackets

Lists can be changed.

 

41. How can we pass variable number of arguments to tuple?

Answer: In python, it is possible to have variable number of arguments. In that case the parameter name begins with *. Then these variable number of arguments are gathered into a tuple. For example ‒

def student Info(*args):

   print(args)

 

42. What is dictionary?

Answer: In python, dictionary is unordered collection of items. These items are in the form of key‒ value pairs.

•  The dictionary contains the collection of indices called keys and collection of values.

•  Each key is associated with a single value.

•  The association of keys with values is called key‒value pair or item.

• For example

My_dictionary={1:'AAA',2: 'BBB',3:'CCC'}

 

43. What is the difference between list, tuple and dictionary?

Answer: A list can store a sequence of objects in a certain order such that we can iterate over the list.

List is a mutable type meaning that lists can be modified after they have been created.

A tuple is similar to a list except it is immutable. In tuple the elements are enclosed with in parenthesis. Tuples have structure, lists have order.

A dictionary is a key‒value store. It is not ordered.

 

44. Explain what is range() function and how it is used in lists ?

Answer: The range function returns an immutable sequence object of integers between the given start integer to the stop integer.

range(start, stop,[step])

>>>for I in range(1,10,2):

print(i,end=" ")

1 3 5 7 9

 

45. How lists are updated in python?

Answer: The append() method is used to add elements to a list.

Syntax: list.append(obj) List=[123, 'VRB']

List.append(2017)

Print("Updated List:",List)

Output: Updated List: [123,'VRB',2017]

 

46. Write a few methods that are used in python lists.

Answer:

a) append() ‒ Add an element to end of list

b) insert() ‒ Insert an item at the defined index

c) remove() ‒ Removes an item from the list

d) clear() ‒ Removes all items from the list

e) reverse() ‒ Reverse the order of items in the list

 

47. What are the advantages of tuple over list?

Answer:

• Tuple is used for heterogeneous data types and list is used for homogeneous data types.

• Since tuple are immutable, iterating through tuple is faster than with list.

• Tuples that contain immutable elements can be used as key for dictionary.

• Implementing data that doesn't change as a tuple remains write‒protected

 

48. What is indexing and negative indexing in tuple?

Answer: The index operator is used to access an item in a tuple where index starts from 0.

Python also allows negative indexing where the index of‒ 1 refers to the last item, ‒2 to the second last item and so on.

>>>my_tuple=('p','y','t', 'h','o','n')

>>>print(my_tuple[5] ) n

>>>print(my_tuple[‒6]) p

 

49. What is the output of print tuple[1:3] if tuple = ('abcd', 786, 2.23, 'john', 70.2) ?

Answer: In the given command, tuple[1:3] is accessing the items in tuple using indexing.

It will print elements starting from 2nd till 3rd. Output will be (786, 2.23).

 

50. What are the methods that are used in python tuple?

Answer:

Methods that add items or remove items are not available with tuple. Only the following two methods are available:

a) count(x)‒ returns the number of items that is equal to x

b) index(x)‒ returns index of first item that is equal to x

 

51. Is tuple comparison possible? Explain how with example.

Answer:

The standard comparisons ('<','">', '<=','>=','==") work exactly the same among tuple objects. The tuple objects are compared element by element.

>>>a=(1,2,3,4,5)

>>>b=(9,8,7,6,5)

>>>a<

b True

 

52. What are the built‒in functions that are used in tuple?

Answer:

• all() ‒ Returns true if all elements of the tuple are true or if tuple is empty

•  any() ‒ Returns true if any element of tuple is true

• len() ‒ Returns the length in the tuple

•  max() ‒ Returns the largest item in tuple

•  min) ‒ Returns the smallest item in tuple

•  sum() ‒ Returns the sum of all elements in tuple.

 

53. What is the output of print tuple + tinytuple if tuple = ('abcd',786, 2.23, 'john', 70.2) and tinytuple = (123, 'john') ?

Answer: It will print concatenated tuples. Output will be ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john').

 

54. Explain what is dictionary and how it is created in python ?

Answer:                                  

Dictionaries are similar to other compound types except that they can use any immutable type as an index. One way to create a dictionary is to start with the empty dictionary and add elements. The empty dictionary is denoted {}:

>>> eng2sp = {}

>>> eng2sp['one'] = 'uno'

>>> eng2sp['two'] = 'dos'

 

55. What is meant by key‒value pairs in a dictionary?

Answer: The elements of a dictionary appear in a comma‒separated list. Each entry contains an index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key‒value pairs.>>> print eng2sp {'one': 'uno', 'two': 'dos"}

 

56. How to slice list in python?

Answer:

• The : operator used within the square bracket that it is a list slice and not the index of the list

>>> a=[10,20,30,40,50,60]

>>> a[1:4]

[20, 30, 40]

>>> a[:5]

[10, 20, 30, 40, 50]

 

57. How to create a list in python ? Illustrate the use of negative indexing of list with example.

Answer: The list is crated by following methods ‒

1) Mylist = [] #creation of empty list

2) Mylist = [10,20,30,40] #creation of the list of elements of 10,20,30,40

The negative indexing is the act of indexing from the end of the list with indexing starting at ‒1 i.e. ‒ 1 gives the last element of list, ‒2 gives the second last element of list and so on.

For example ‒

>>> mylist = [10,20,30,40,50]

>>> print(mylist[‒1])

50

>>> print(mylist[‒2])

40

>>> print(mylist[‒3])

30

>>> 

 

58. Give the python code to find the minimum among the list of 10 numbers.

Answer:

a=[18, 52, 23, 41, 32, 55, 7, 3, ‒1, 100]

# minimum number

min_num = a[0] if a else None

# find minimum number

for i in a:

if i<min_num:

    min_num=i

print("Minimum element from the list is: ", min_num)

 

59. Demonstrate with simple code to draw the histogram in python.

Answer:

import matplotlib.pyplot as plt

from numpy.random import normal

gaussian_numbers = normal(size=1000)

#plt.hist(gaussian_numbers)

plt.hist(gaussian_numbers)

plt.title("Gaussian Histogram")

plt.xlabel("Value")

plt.ylabel("Frequency")

plt.show()

 

60. Relate strings and lists.

Answer: String is basically a collection of characters. This collection of characters is basically a list of characters. For example ‒

mystring = ['I','n','d','i','a']

 

61. Give a function that can take a value and return the first key mapping to that value in a dictionary.

Answer:

def myfun(d,val):

return [k for k, v in d.items() if v = = val]

d = {

      'AAA': 101,

      'BBB': 102,

      'CCC': 103,

      'DDD': 104,

      'EEE': 105

}

# Get the first key in a dictionary

print('First Key of dictionary:')

print(myfun(d,101))

Output

First Key of dictionary:

['AAA']

>>> 

 

Python for Data Science: Chapter 1: Basics of Python : Tag: Computer Programming, Python, Data Science : Python for Data Science - Basics of Python: Two Marks Important Questions and Answers


Python for Data Science: Chapter 1: Basics of Python



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation