Skip to main content

Python Sample Questions and Answers for Beginners.

 Phython Sample Questions:

 

1.     In Python, a variable must be declared before it is assigned a value:

a.     True

b.     False

c.     Non Applicable

 

 2.    In Python, a variable may be assigned a value of one type, and then later assigned a value of a different type:

a.True

b.False

3.    Consider the following sequence of statements:

n = 300
m = n

Following execution of these statements, Python has created how many objects and how many references?

a.     Two objects, two references

b.     Two objects, one reference

c.     One object, one reference

d.     One object, two references

4.    What Python built-in function returns the unique number assigned to an object:

a.     ref()

b.     id()

c.     refnum()

d.     identity()

5.    Which of the following are valid Python variable names:

a.     home_address

b.     return

c.     route66

d.     ver1.3

e.     Age

f.       4square

6.    Which of the following is a token in python?

a.     Keyword

b.     Identifiers

c.      Literals

d.     Operators

e.      All of the above

 

7.    Which of the following is not a python literal ?

a.    Boolean

b.     Numeric

c.     String

d.     Special

e.     Identifiers

f.       Literal Collection

 

 

8.    Which of the following is literal collection?

a.      List

b.     Tuple

c.      Dictionary

d.     Set

e.      All of the above

 

 

9.    What is the value of the expression 1 + 2 ** 3 * 4?

a.     31

b.     33

c.     145

d.     4097

 

10.   Bitwise shift operators (<<>>) has higher precedence than Bitwise And(&) operator.

a.     True b. False

11.    4 is 100 in binary and 11 is 1011. What is the output of the following bitwise operators?

a = 4
b = 11
print(a | b)
print(a >> 2)

a.     15

1

b.     14

1

 

 

12.  What is the output of the following assignment operator ?

y = 10

x = y += 2

print(x)

a.     12

b.     10

c.     SyntaxError

d.      

13.  What is the value of the following Python Expression?

print(36 / 4)

a.  9.0

b.  9

c.  0

d.  None of the above

 

 

14.   What is the output of print(2%6)?

a.   ValueError

b.   O.33

c.   2

 

15.  What is the time complexity of linear search and Binary search?

 

16.  a= -5
i. print(type(a))
b=40.5
ii. print(type(b))
c=1+3j
iii. print(type(c))
iv. print(is instance(1+3j,complex))

 

 

17.  What are the data types in python?

 

18.  s='hello students'
s1='how are you'
a. print(s[0:2])
b. print(s1[4])
c. print(s * 2)
d. print(s+s1)
e. print(s[1:10:2])
 

 

19.  Python relies on indentation, using whitespace, to define scope in the code.

True or False

 

20. We can have any number of elif statements in our program depending upon our need.

True or False

 

21.  What is a “not equal to” sign in python operation?

 

 

# A chained conditional is when you use if/elif/else flow controls and they are all indented to the same depth. No nesting.

# A nested conditional is when you use if/elif/else flow controls and the conditionals vary in depth to create a more nuanced sequence of conditionals.

 

# Nesting is the key differentiator between a Chained Conditional and a Nested Conditional.

 

True or False

 

23. for s in range(2,10,2):
    print(s)
output is:
 
24.   for i in "Kathmandu":
    if i=="h":
        break
    print("Got it ")
print("End of it all")
 
Output:
 
25. for i in "Kath":
    if i=="a":
        continue
    print("learn continue in python ")
print("End of it all")
 
output:
 
 
26.  fruits=["apple","banana","cherry"]
for x in fruits:
    print(x)
    if x=='banana':
        break
output:
 
 

27.   while loops only useful when we know how many iterations we need. E.g. going through a sequence.

      for loops can go on forever. There are risks with this but it means they are more powerful.

True or false

28. Nested for loop is more useful in printing pattern in Python and printing data in row and column format (tabular format) True or False

 

29.  What is output of following code

x = 2
y = 10
x * = y * x + 1

A - 42

B - 41

C - 40

D - 39

 
 

30. error_message( )
def error_message( ) :
     print(‘Something went wrong’)

What is the output of this message?
 

31.  __________ are the values we pass to the function in a particular function call.

 

32. _____________ are variable names used in the function definition to refer to the arguments.

 

33. A variable declared inside the function's body is known as a global variable. 

True or False

 

 

34. x='global'

def fun():
    global x
    y='local'
    x= x * 2
    print(x)
    print(y)

fun()
print("x outside", x)

 

output:

 

35. Nonlocal variables are used in nested functions whose local scope is not defined.

True or False

 



36. Is the above image a correct representation of namespace ? True or False

 

37.   

def outerFunction():
    a=20
    def innerFunction():
        a=30
        print("inner:", a)

    innerFunction()
    print('a:',a)

a=10
outerFunction()
print('a:',a)

 

output:

 

 

38.      

def outerFunction():
    global a
    a=10
    def innerFunction():
        global a
        a=5
        print("inner:", a)


    innerFunction()
    print('a:',a)

a=20
outerFunction()
print('a:',a)
 
Output:       

39. What is a Docstring in python and how is it represented?

40. What happens if a local variable exists with the same name as the global variable you want to access?
a) Error
b) The local variable is shadowed
c) Undefined behavior
d) The global variable is shadowed

 

41.  1. Which of the following data structures is returned by the functions globals() and locals()?
a) list
b) set
c) dictionary
d) tuple

 

42.  

x=1
def cg():
         global x
         x=x+1      
cg()
print(x)

a.     2   b. 1  c. 0  d. error

 

43.  ______________ returns a dictionary of the module namespace.
________________ returns a dictionary of the current namespace.

a.local, global  b. local, local  c. global, local d.global,global

 

 

44. Fill in the information for the following built-in Data structure.

 

Ordered

Changeable

Indexed

Allows Duplicate Member

List

 

 

 

 

Set

 

 

 

 

Tuple

 

 

 

 

Dictionary

 

 

 

 

Fill in the right information:

45.  

1

2

3

4

5

a.     List[2:4]

b.     List[:4]

c.     List[:]

d.     List[0:]

 

46. Correct way to append list

list=[1,2,3,4,5,6]

a.   list.append('seventhirty')

b.     append.list(‘seventhirty’)

c.     append list[‘sevetrhirty’]

d.     None of the above

 

47. a=[1,2,3,4,5,6]
print(4 in a )
 
what would be the output and this is the example of what kind of operator?
 
 
48. a=(1,2,3,[4,5])

a[3][1]=9

print(a)
 
49. a={}

print(type(a))
 

 

 

50. a={1}

b={2,3}

print(a|b)

 

 
51.  a = {2,3,4}
b= {2,5,6}

print(a&b)
 
 
52. a = {2,3,4}
b= {2,5,6}

print(a^b)
 
 
53. a = {'name':'jack', 1:'apple', 'ball':5}

print(a['jack'])

 

 

54. square = {}

for x in range (6):
    square[x]=x*x

print(square)

 

 

55. square = {1:1,3:9, 5:25,7:49,9:81}

for i in square:
    print(square[i])

 

 

56. square = {1:1,3:9, 5:25,7:49,9:81}

print(sorted(square))

 

 

57.  Which of these is false about recursion?
a) Recursive function can be replaced by a non-recursive function
b) Recursive functions usually take more memory space than non-recursive function
c) Recursive functions run faster than non-recursive function
d) Recursion makes programs easier to understand

 

 

58. . Fill in the line of the following Python code for calculating the factorial of a number.

def fact(num):
    if num == 0: 
        return 1
    else:
        return _____________________

 

a)     num*fact(num-1)
b) (num-1)*(num-2)
c) num*(num-1)
d) fact(num)*fact(num-1)

 

 

59. What happens if the base condition isn’t defined in recursive programs?
a) Program gets into an infinite loop
b) Program runs once
c) Program runs n number of times where n is the argument given to the function
d) An exception is thrown

 

60. Birthday = 15 + “February” + 1995

Which error would above line of code fall into ?

a.    Syntax Error

b.    Runtime Error

c.    Logic Error

d.    All of the above

 

61.  Which errors are also called exceptions ?

a. Syntax Error

b. Runtime Error

c. Logic Error

d. None of the above

 

62.  Which of the following is the runtime error message?

a.    NameError

b.    NotImplementedError

c.    TypeError

d.    IndexError

e.    All of the above

 

63. Which error is not identified and do not generate any error message?

a.     Syntax Error

b.     Runtime Error

c.     Logic Error

d.     None of the above

 

64. Which of the following is not the mechanism for Exception handling?

a.     try

b.     expect

c.     except

d.     else

e.     finally

 

65. Which block lets you test a block of code for errors?

A. try 
B. except 
C. finally 
D. None of the above

 

 

66.  What will be output for the folllowing code?

try:

  print(x)

except:

  print(""An exception occurred"")

A. x
B. An exception occurred
C. Error
D. None of the above


 

67.  pickle.dump is used to read the preserved data from file one piece at a time and pickle.load is used to write to file preserving types.

True or False

 

68. Given the file dog_breeds.txt, which of the following is the correct way to open the file for reading as a text file? Select all that apply.

Top of Form

a

open('dog_breeds.txt')

b

open('dog_breeds.txt', 'rb')

c

open('dog_breeds.txt', 'w')

d

open('dog_breeds.txt', 'wb')

e

open('dog_breeds.txt', 'r')

69.  Given the file jack_russell.png, which of the following is the correct way to open the file for reading as a buffered binary file? Select all that apply.

Top of Form

a.

open('jack_russell.png', 'wb')

b.

open('jack_russell.png')

c.

open('jack_russell.png', bytes=True)

d.

open('jack_russell.png', 'r')

e.

open('jack_russell.png', 'rb')

 

70.  Name two types of data files available in python ?

 

71.   Write the symbols used in text file mode for the following operations.

  1. Read Only
  2. Write only
  3. Read and Write
  4. Write and Read

 

72.   What is the difference between r+ and w+ mode?

 

73.   What is the difference between write and append mode?

 

74.  Write the symbols used in binary file mode for the following operations.

  1. Read Only
  2. Write only
  3. Read and Write
  4. Write and Read

 

75. What is the Time Complexity of a Bubble sort Algorithm ?


76.  Sorting refers to arranging data in particular format. 

Below we see four such implementation of sorting in Python.

1.       Bubble sort

2.     selection sort

3.     Insertion sort

4.     Merge sort

True or False

 

 

Bottom of Form

 Answers:

1.     Ans: B – False

Variables need not be declared or defined in advance in Python. To create a variable, you just assign it a value.

 

2.     Ans: True

3.     Ans: d – One object, two references

4.     Ans: b – id()

5.     Ans: a, c , e

  • 4square is not valid because it begins with a digit.
  • return is not valid because it is a Python reserved word (keyword).
  • version1.3 is not valid because it contains a character which is not a letter, digit or underscore.

6.     Ans: e – All of the above

7.     Ans: e – Identifiers.

8.     Ans: e – all of the above.

9.     Ans: b – 33

10.  Ans: True

11.  Ans: a: 15 and 1

12.  Ans: c - expression is invalid.

13.  Ans: a - 9.0

14.  Ans: c - 2

The first number is the numerator, and the second is the denominator. For example, 2 divided by 6 is 0 remainder 2. Therefore, the result is 2.

15.  Time complexity of Linear search is O(n) and time complexity of binary search is O(logn)

Linear search is the most basic kind of search method. It is also called as sequential search. It involves checking each element of the list in turn, until the desired element is found.

 

 

16.  <class 'int'>

<class 'float'>

<class 'complex'>

True

 

17.  Numbers – Integer, Complex Number, float

Sequence – String, List, Tuple

Boolean

Set

Dictionary

 

18.  he

a

hello studentshello students

hello studentshow are you

el td

 

19.  Ans: True

20.  Ans: True

21.  Ans: !=

22.  Ans: True

23.  2
4
6
8
24.  Got it 
Got it 
Got it 
End of it all
25.  learn continue in python 
learn continue in python 
learn continue in python 

End of it all

26.  apple
banana

27.  Ans: False

28.  Ans: True

29.  Answer : A

Explanation

x * = y * x + 1 means x = x * (y * x + 1)

 

30.  Ans: NameError –(Error message)
31.  Arguments
32.  Parameter

33.  Ans: False

34.  globalglobal

local

x outside globalglobal

35.  Ans: True

36.  Ans: True

37.  inner: 30

a: 20

a: 10

38.  inner: 5
a: 5
a: 5
Note:  Python looks for variables in namespaces in a strict order. It will look in the local namespace of the function first before looking at the main namespace. 
 

39.  At the top of every user function explaining what the function does – (must be a string literal not any other kind of expression).

""" In Python we enclose docstrings in triple quotes"""

40.  Ans: d

41.  Ans: C

42.  Ans: a. 2

43.  Ans: c global,local

44.   

 

Ordered

Changeable

Indexed

Allows Duplicate Member

List    []

Yes

Yes

Yes

Yes

Set     {}

NO

Yes

NO

NO

Tuple  (),   ,

Yes

No

Yes

Yes

Dictionary – {key:Value}

NO

Yes

Yes

NO

45.  a=[3,4] , b=[1,2,3,4], c=[1,2,3,4,5], d = [1,2,3,4,5]

46.  Ans: a – list.append(‘seventhirty’)   (append method can only add value to the end of the list and using the remove in the same way which is list.remove)

47.  Ans: True , (Membership operator)

 

48.  Output: (1, 2, 3, [4, 9])   
(Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable data type like list, its nested items can be changed – here changing 1st index of the 3rd index of the tuple)

49.  Output - <class ‘dict’>

(To make a set without any elements we use the set ( ) function without any argument like this a=set()  ).

 

50.  output:

 {1,2,3}

51.  Output:{2}
52.  output: {3, 4, 5, 6}
 
This is a symmetric difference 

53.  Output: Keyerror

54.  Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

55.  Output:

1

9

25

49

81

56.  Output : [1, 3, 5, 7, 9]

57.  Ans: C

58.  Answer: A
Explanation: Suppose n=5 then, 5*4*3*2*1 is returned which is the factorial of 5.

59.  Answer: a
Explanation: The program will run until the system gets out of memory.

Note: The countdown program is an example of tail recursion: when the recursive call is the last part of a program

60.   Ans: b – Runtime Error
 Run Time errors will be identified, but not until code is running.

61.  Ans: b – Runtime Error

Runtime errors are called exceptions because they usually mean something exceptional has happened.

62.  Ans: e – All of the above.

63.  Ans: c – Logic Error

64.  Ans: b –expect

Note: try, except, (else) and finally is the correct order for exception handling.

65.  Ans : A
Explanation: The try block lets you test a block of code for errors.

66.  Ans : B

Explanation: An exception occurred be the output for the following code because the try block will generate an error, because x is not defined.

67.  Ans: False

It is vice versa pickle.dump :  write to file preserving types.

                        Pickle.load : read the preserved data from file one piece at a time.

Note: Need to use modes "rb" and "wb" instead of "r" and "w" since pickle codes data in bytes.

68.  Ans: e

69.  Ans: e

70.  Ans: Text file and Binary File

71.  r

w

r+

w+

72.  Ans. r+ mode will return error if file does not exist while w+ mode will create a new file if file does not exist.

73.  Ans. Write mode over writes the existing data while append mode add the new data at the end of the file.

74.  Ans.

rb

wb

rb+

wb

75.  Time Complexity of a Bubble sort Algorithm is:O(n^2).

76.  True

 

 

 
 
 
 
 

 

 

 

 

 

 

 

 

 

 

 

 
 

Comments

Popular posts from this blog

C and Assembly Questions and Answers 101

  Assembly and C Questions 101: 1. How long will it take for a 128kB file to go across at 1Mbps? 2. DMA full form? 3. Register : Register is the fastest memory in a computer which holds information. True or False 4. A 32-bit processor means it can perform operations on 32-bit data; therefore, the size of registers is 32 bits and ALU also performs 32-bit operations. A 64-bit CPU performs the operation in 64-bit data; therefore, it contains 64-bit register and 64-bit ALU.  True or False 5. Which of the following is a control signal? a.       Read Signal b.      Write Signal c.       Interrupt d.      Bus Request e.       Bus Grant f.       I/O Read and Write g.      All of the above 6. There are two types of CPU technology CISC and RISC. What is the full form of CISC and RISC? 7. The characteristics of 8086 are called reduced instruction set computers (RISC)? True or False 8. What are the two types of CPU architecture? 9. Von Neumann uses the data bus

IPV4, Class and Subnetting.

  IPV4, Class and Subnetting.   IPV4 which stands for Internet protocol version 4 consists of 32 bits. It is written in four octets (1 octet consists of eight bits) – xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx -----these digits are in binary either 1 or 0 and if written in decimal looks something like this – 10.25.58.65  The maximum value of 1 octet is 255 that is derived from- lets suppose if an octet is all 1s like 11111111 ---- the decimal value of this equals to 255. Lets get into few important points:   IPV4 class ---- Classes 1 st Octet Range Default Subnet Mask Finding Formula A 0-127 (#127 is a loop IP) 255.0.0.0 00000000(0) -011111111(127) (0 constant in the range) B 128-191 255.255.0.0 10000000(128) – 10111111(191) (10 constant ) C 192 -223 255.255.255.0 11000000(192) – 11011111(223)  (110 constant in the ran