Python questions

Happy reading...😊

1) What are the Data Structures of Python and How to initialize them?
List: In list, the more than one data type can be added using append method. In list we can delete or edit the elements which are added to the list(Mutable)
List can be declare mainly in two ways
 I) variable_name=list(1,2,3) 
 II) variable_name=[1,2,3]
To add variable at end variable_name.append(data)
Tuples: These are similar to list but once variables are added it cannot be modified, so this is immutable 
I) variable_name=tuple(2,5,7)
II) variable_name=(2,5,7)
Dictionary: Dictionary have Key value pair where Key can be int or float or strings
These are also mutable
 I) variable_name=dict(2,4,6)
 II) variable_name={2,4,6}

2) What is negative Indices?

It is used to Slicing the from the end of the lists
Eg:- list=[0,1,2,3,4,5]
print(list[-0])
5

3) What will be returned when dict.items() is called?

List of Tuple of key and items is returned

4) Does Python don't have any Limitations?

No, Even python have limitations some are 

  I)Speed :- While comparing to C,C++,Java python is slow because python uses interpreter which means line by line compared to C,C++,Java because they uses compiler 
 II)Mobile Development :- As there are less development in python for mobile therefore only few ways we can implement in Mobile one of them is kivy
III) Runtime Errors:- As Python is a dynamically typed language runtime errors are often so show more testing is required
IV) Database :- Python database access layer is quite undeveloped compared to jdbc and odbc therefore one should use this on their own risk

5) What is // and ** do in python?


// =>Performs floor division operation whereas 

/ =>performs normal division
Eg:- 10//6  gives 1 and 10/6 gives 1.66666
** Performs exponential operation whereas * performs multiplication operation
Eg:- 3**2 gives 9 and 3*2 gives 6

6)What are the benefits of python?


It is easy,simple,portable,extensible,have built-in data structures,and it is an open source.



7)How python is interpreted?

Python language runs directly from the source code.It converts the source code into the immediate language,which is then converted into machine level code and executed.


8)How memory is managed in python?


--Memory is managed in python private heap space.All python objects and data structures are in the heap space. The interpreter takes care of this heap space,and programmer cant access this.

--The allocation for heap memory is done by python memory manager. The code API gives access to some of the tools for the programmer.
--Python memory manager also has garbage collector, which collects the unused memory and recycles when needed.Useless objects or data are thrown out of the heap.

9)Can we alter the python syntax ?

Yes, it is called python decorator,where me make specific change to alter the functions easily.

10)What is the use of  split in python?

This is used to break a string into smaller string when it gets defined separator.
ex: line.split(':') 

11)What is flask, pyramids,Django?

Flask is a micro framework primarily built for small applications with simpler requirements.Here you don't have to use external libraries.

Pyramids are built for larger applications.It provides flexibility and allows to use right tool for their project.
Django is also used for larger applications. It uses ORM (object relational mapping)

12)Why tuples are better than list?


Tuples are stored in a single block of memory.

Tuples are immutable so, It doesn't require extra space to store new objects.

Lists are allocated in two blocks.

The fixed one with all the Python object information and a variable sized block for the data.

It is the reason creating a tuple is faster than List.

It also explains the slight difference in indexing speed is faster than lists, because in tuples for indexing it follows fewer pointers


13)How to swap two numbers in python using tuple?


//by default the values are taken as tuples

x,y=2,3

print("{},{} before swap".format(x,y))

x,y=y,x 

print("{},{} after swap".format(x,y))


14)Which method works both for list and tuple in python?


Since tuple is immutable many of the methods of list don't work for tuple.Only two common method ie., index() and count() works for both. 


15)Which of the following tuples is greater than x in the following Python sequence

x = (5, 1, 3)

if ??? > x :

a) (5,0,200)

b) (6,20,0)

c) None


 (6,20,0) tuple compare element by element with (5,1,3) .If the first element is greater it doesn't check the rest of the elements. 


16) What is the difference between list and tuple?



LISTTUPLES
Lists are mutable i.e they can be edited.Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples.Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20]Syntax: tup_1 = (10, ‘Chelsea’ , 20)

17)What is PYTHONPATH ?

Whenever a module is imported, PYTHONPATH (an environment variable) will looked up to check for the presence of the imported modules in various directories. 

18)What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code of built-in functions.
Some of the commonly used built-in modules are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON
19) When do you use pass?

When you want a code syntactically to run without error even though it is incomplete. Used in conditional statements or loops.It does nothing.
ex: if flag:
            pass

20) What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Somewhat similar Boxing and unboxing in java.
21)How to handle files in python? Demonstrate using code.
We use open () function in Python to open a file in read or write mode.This function returns file object.
Syntax being: open(filename, mode)
  •  r “, for reading.
  •  w “, for writing.
  •  a “, for appending.
  •  r+ “, for both reading and writing
# a file named "geek", will be opened with the reading mode. 
file = open('geek.txt', 'r') 
# This will print every line one by one in the file 
for each_line in file: 
print (each_line) 

22)Which module in Python supports regular expressions?

 re is a part of the standard library and can be imported using: import re

23)What will be the output of the following Python code?
sentence = 'we are humans'
matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.groups())

(‘we’, ‘are’, ‘humans’)

This function returns all the subgroups that have been matched.


24)What will be the output of the following Python code?
sentence = 'we are humans'
matched = re.match(r'(.*) (.*?) (.*)', sentence)
print(matched.group())

'we are humans' This function returns the entire match.

25)What will be the output of the following Python code?
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())


{‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}
Function re.compile returns dictionary

26)What will be the output of the following Python code?
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.group(2))

‘are’ This function returns the particular subgroup

27)Write the code to retrieve web data without using urlib module.

#1.import socket module 
import socket

#2.create a socket name mysocket
mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#3.connect that socket to the web page
mysocket.connect(('data.pr4e.org',80))

#4.get the web page, encode it and store it in cmnd. This will be in bytes
cmnd='GET https://data.pr4e.org/romeo.txt HTTP/1.1\n\n'.encode()

#5.send the cmnd through mysocket and request the web page
mysocket.send(cmnd)

#6.Retrieve all data 
while(True):
         data=mysocket.recv(500)#receive 500 charecter
         if len(data)<1:#End of file
                  break
   print(data.decode())#Byte is decoded to unicode string
mysocket.close()#close socket connection

      





Comments

Popular posts from this blog

JAVA QUESTIONS