Author Archives: ravitarvan


Panjab University M.A 1st Sem Question Paper

Category : News

Panjab University M.A 1st Sem Question Paper


Panjab University M.A Previous Year Question Papers

Category : News

Panjab University M.A previous Year Question Paper



M.com 3rd sem panjab university question paper

Category : News

PU Panjab University Mcom 3rd sem sem Question paper

Buisness Performance Measurment

Human Resource Development

Human Resource Management industrial Relations

Tax Planing and Management

Accounting Finance International Accounting

2018

marketing
Research

2018

HRM

2018

strategic cost management

2018

Marketing

2018

Bank Management


C ++ Language interview question and Answer

Category : News

Interview Questions
&
Answers

C++language Interview questions and Answers

In simple way Meaning of Analogy is “Similarity ” or compassion between one thing and other thing base d on some similarity 

250 + C++ Question and Answer

1.Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?

A: There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor        is a code which is responsible for creating an instance of a class and it can’t be delegated to        any other object by virtual keyword means. 

2. What is constructor or ctor?

A: Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is        different from other methods in a class. 

3. What about Virtual Destructor?

A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime        depending on the type of object caller is calling to, proper destructor will be called. 

4.What is the difference between a copy constructor and an overloaded assignment operator?

A: A copy constructor constructs a new object by using the content of the argument object. An       overloaded assignment operator assigns the contents of an existing object to another existing       object of the same class. 

5.Can a constructor throws an exception? How to handle the error when the constructor fails?

A:The constructor never throws an error. 

6. What is default constructor?

A: Constructor with no arguments or all the arguments has default values. 

7.What is copy constructor?

A: Constructor which initializes the it’s object member variables ( by shallow copying) with another object of the same class. If you don’t implement one in your class then compiler implements one for you. for example:

 (a) Boo Obj1(10); // calling Boo constructor 

(b) Boo Obj2(Obj1); // calling boo copy constructor 

(c) Boo Obj2 = Obj1;// calling boo copy constructor 

8.When are copy constructors called?

A: Copy constructors are called in following cases:

 (a) when a function returns an object of that      class by value 

(b) when the object of that class is passed by     

  value as an argument to a function

 (c) when you construct an object based on another      

object of the same class

 (d) When compiler generates a temporary object 

9. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?

A: No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference. 

10.What is conversion constructor?

A: constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.

 for example:

 class Boo

 { 

public:

 Boo( int i ); 

}; 

Boo BooObject = 10 ; // assigning int 10 Boo object 

11.What is conversion operator?

A:class can have a public method for specific data type conversions.

 for example: 

class Boo

 { 

double value;

 public: 

Boo(int i ) 

operator double()

 {

 return value;

 }

 }; 

Boo BooObject;

 double i = BooObject; // assigning object to variable i of type double. 

 now conversion operator gets called to assign the value. 

 

12.How can I handle a constructor that fails?

A: throw an exception. Constructors don’t have a return type, so it’s not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

13.How can I handle a destructor that fails?

A: Write a message to a log-_le. But do not throw an exception. The C++ rule is that you must never throw an exception from a destructor that is being called during the “stack unwinding” process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bare) { handler? There is no good answer:either choice loses information. So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you’re dead. 

14.What is Virtual Destructor?

A: Using virtual destructors, you can destroy objects without knowing their type – the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes. if someone will derive from your class, and if someone will say “new Derived”, where “Derived” is derived from your class, and if someone will say delete p, where the actual object’s type is “Derived” but the pointer p’s type is your class. 

15. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?

A: No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference

16. What's the order that local objects are destructed?

A: In reverse order of construction: First constructed, last destructed. 

In the following example, b’s destructor will be executed first, then a’s destructor:  

 

void userCode() 

Fred a;

 Fred b;

 … 

17. What's the order that objects in an array are destructed?

A: In reverse order of construction: First constructed, last destructed.  

 

In the following example, the order for destructors will be a[9], a[8], …, a[1], a[0]:  

 

void userCode() 

{

 Fred a[10]; 

… 

18. Can I overload the destructor for my class?

 No.  

 You can have only one destructor for a class Fred. It’s always called Fred::~Fred(). It never takes any parameters, and it never returns anything.  

 

You can’t pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).  

19. Should I explicitly call a destructor on a local variable?

A: No!  

 The destructor will get called again at the close } of the block in which the local was created. This is a guarantee of the language; it happens automagically; there’s no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! You’re dead! 

20.What if I want a local to "die" before the close } of the scope in which it was created? Can I call a destructor on a local if I really want to?

A: No! [For context, please read the previous FAQ].  

 

Suppose the (desirable) side effect of destructing a local File object is to close the File. Now suppose you have an object f of a class File and you want File f to be closed before the end of the scope (i.e., the }) of the scope of object f:  

 void someCode() { File f; 

 …insert code that should execute when f is still open… 

 We want the side-effect of f’s destructor here! 

 …insert code that should execute after f is closed… }  There is a simple solution to this problem. But in the mean time, remember: Do not explicitly call the destructor! 

21. OK, OK already; I won't explicitly call the destructor of a local; but how do I handle the above situation?

A: Simply wrap the extent of the lifetime of the local in an artificial block {…}:  

 

void someCode() 

{

 { 

File f;

 …insert code that should execute when f is still open… 

} f’s destructor will automagically be called here! 

 

…insert code here that should execute after f is closed…} 

22. What if I can't wrap the local in an artificial block?

A: Most of the time, you can limit the lifetime of a local by wrapping the local in an artificial block ({…}). But if for some reason you can’t do that, add a member function that has a similar effect as the destructor. But do not call the destructor itself!  

 

For example, in the case of class File, you might add a close() method. Typically the destructor will simply call this close() method. Note that the close() method will need to mark the File object so a subsequent call won’t re-close an already-closed File. E.g., it might set the fileHandle_ data member to some nonsensical value such as -1, and it might check at the beginning to see if the fileHandle_ is already equal to -1:  

 

class File {

 public: 

void close(); 

~File(); 

… 

private: 

int fileHandle_; // fileHandle_ >= 0 if/only-if it’s open

 }; 

File::~File()

 { close();

 } 

 

void File::close() 

if (fileHandle_ >= 0) { 

…insert code to call the OS to close the file…

 fileHandle_ = -1; 

 Note that the other File methods may also need to check if the fileHandle_ is -1 (i.e., check if the File is closed).  

 

Note also that any constructors that don’t actually open a file should set fileHandle_ to -1. 

23.But can I explicitly call a destructor if I've allocated my object with new?

A: Probably not. 

Unless you used placement new, you should simply delete the object rather than explicitly calling the destructor. For example, suppose you allocated the object via a typical new expression:  

 Fred* p = new Fred();  Then the destructor Fred::~Fred() will automagically get called when you delete it via:  

 delete p; // Automagically calls p->~Fred()  You should not explicitly call the destructor, since doing so won’t release the memory that was allocated for the Fred object itself. Remember: delete p does two things: it calls the destructor and it deallocates the memory. 

24. What is "placement new" and why would I use it?

A: There are many uses of placement new. The simplest use is to place an object at a particular location in memory. This is done by supplying the place as a pointer parameter to the new part of a new expression:  

#include // Must #include this to use “placement new” 

#include “Fred.h” // Declaration of class Fred 

void someCode()

 { 

char memory[sizeof(Fred)]; // Line #1 

void* place = memory; // Line #2 

 Fred* f = new(place) Fred(); // Line #3 (see “DANGER” below)

 // The pointers f and place will be equal 

… 

Line #1 creates an array of sizeof(Fred) bytes of memory, which is big enough to hold a Fred object. Line #2 creates a pointer place that points to the first byte of this memory (experienced C programmers will note that this step was unnecessary; it’s there only to make the code more obvious). Line #3 essentially just calls the constructor Fred::Fred(). The this pointer in the Fred constructor will be equal to place. The returned pointer f will therefore be equal to place.  

ADVICE: Don’t use this “placement new” syntax unless you have to. Use it only when you really care that an object is placed at a particular location in memory. For example, when your hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that memory location.  

DANGER: You are taking sole responsibility that the pointer you pass to the “placement new” operator points to a region of memory that is big enough and is properly aligned for the object type that you’re creating. Neither the compiler nor the run-time system make any attempt to check whether you did this right. If your Fred class needs to be aligned on a 4 byte boundary but you supplied a location that isn’t properly aligned, you can have a serious disaster on your hands (if you don’t know what “alignment” means, please don’t use the placement new syntax). You have been warned. 

You are also solely responsible for destructing the placed object. This is done by explicitly calling the destructor: 

void someCode()

 { 

char memory[sizeof(Fred)]; 

void* p = memory; 

Fred* f = new(p) Fred(); 

… 

f->~Fred(); // Explicitly call the destructor for the placed object 

}

  This is about the only time you ever explicitly call a destructor.  

 

Note: there is a much cleaner but more sophisticated way of handling the destruction / deletion situation. 

 

25. When I write a destructor, do I need to explicitly call the destructors for my member objects?

A: No. You never need to explicitly call a destructor (except with placement new).  

A class’s destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class. 

class Member

 { public:

 ~Member(); 

… 

}; 

 

class Fred 

{ public: 

~Fred();

 … 

private: 

Member x_; 

Member y_;

 Member z_; 

}; 

 

Fred::~Fred() { 

// Compiler automagically calls z_.~Member() 

// Compiler automagically calls y_.~Member() 

// Compiler automagically calls x_.~Member() 

 

26. When I write a derived class's destructor, do I need to explicitly call the destructor for my base class?

A: No. You never need to explicitly call a destructor (except with placement new).  

 

A derived class’s destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects. In the event of multiple inheritance, direct base classes are destructed in the reverse order of their appearance in the inheritance list.  

 

class Member

 { public:

 ~Member(); … }; 

 

class Base 

{ public: virtual 

~Base(); // A virtual destructor

 … 

}; 

 

class Derived : public Base {

 public:

 ~Derived();

 … private:

 Member

 x_; }; 

 

Derived::~Derived()

 { 

// Compiler automagically calls x_.~Member()

 // Compiler automagically calls Base::~Base()

 }  

Note: Order dependencies with virtual inheritance are trickier. If you are relying on order dependencies in a virtual inheritance hierarchy, you’ll need a lot more information than is in this 

FAQ.


Interview Question For C language

Category : News

Interview Questions
&
Answers

C Language Interview questions and Answers

250 + C Language Question and Answer

1.what are static blocks and static initalizers in Java ?

Static blocks or static initializers are used to initalize static fields in java. we declare static blocks when we want to intialize static fields in our class. Static blocks gets executed exactly once when the class is loaded . Static blocks are executed even before the constructors are executed.

2) How to call one constructor from the other constructor ?

With in the same class if we want to call one constructor from other we use this() method. Based on the number of parameters we pass appropriate this() method is called.

Restrictions for using this method :

1) this must be the first statement in the constructor

2)we cannot use two this() methods in the constructor

3) What is method overriding in java ?

If we have methods with same signature (same name, same signature, same return type) in super class and subclass then we say subclass method is overridden by superclass.

When to use overriding in java If we want same method with different behaviour in superclass and subclass then we go for overriding. When we call overridden method with subclass reference subclass method is called hiding the superclass method.

4) What is super keyword in java ?

Variables and methods of super class can be overridden in subclass . In case of overriding , a subclass object call its own variables and methods. Subclass cannot access the variables and methods of superclass because the overridden variables or methods hides the methods and variables of super class. But still java provides a way to access super class members even if its members are overridden. Super is used to access superclass variables, methods, constructors.

Super can be used in two forms :

1) First form is for calling super class constructor.

2) Second one is to call super class variables,methods.

Super if present must be the first statement.

5) Difference between method overloading and method overriding in java ?

Method Overloading

  •  Method Overloading occurs with in the same class
  • Since it involves with only one class inheritance is not involved.                                        
  • In overloading return type need not be the same
  • Parameters must be different when we do overloading
  • Static polymorphism can be acheived using method overloading
  • In overloading one method can’t hide the another

Method Overriding​

  • Method Overriding occurs between two classes superclass and subclass
  • Since method overriding occurs between superclass and subclass inheritance is involved.
  • In overriding return type must be same.          
  • Parameters must be same.                              
  • Dynamic polymorphism can be acheived using method overriding
  • In overriding subclass method hides that of the superclass method.

6) Difference between abstract class and interface ?

Interface

  • Interface contains only abstract methods       
  • Access Specifiers for methods in interface must be public
  • Variables defined must be public , static final
  • Multiple Inheritance in java is implemented using interface
  • To implement an interface we use implements keyword

Abstract Class

  • Abstract class can contain abstract methods, concrete methods or both
  • Except private we can have any access specifier for methods in abstract class.
  • Except private variables can have any access specifiers
  • We cannot achieve multiple inheritance using abstract class
  • To implement an interface we use implement keyword

7) Why java is platform independent?

The most unique feature of java is platform independent. In any programming language soruce code is compiled in to executable code . This cannot be run across all platforms. When javac compiles a java program it generates an executable file called .class file.

class file contains byte codes. Byte codes are interpreted only by JVM’s . Since these JVM’s are made available across all platforms by Sun Microsystems, we can execute this byte code in any platform. Byte code generated in windows environment can also be executed in linux environment. This makes java platform independent.

8) What is method overloading in java ?

A class having two or more methods with same name but with different arguments then we say that those methods are overloaded. Static polymorphism is achieved in java using method overloading. Method overloading is used when we want the methods to perform similar tasks but with different inputs or values. When an overloaded method is invoked java first checks the method name, and the number of arguments ,type of arguments; based on this compiler executes this method. Compiler decides which method to call at compile time. By using overloading static polymorphism or static

binding can be achieved in java.

Note : Return type is not part of method signature. we may have methods with different return types but return type alone is not sufficient to call a method in java.

9) What is difference between c++ and Java ?

Interface

  •  Java is platform independent
  • There are no pointers in java
  • There is no operator overloading in java
  • There is garbage collection in java
  • Supports multithreading
  • There are no templates in java
  • There are no global variables in java

Abstract Class

  • C++ is platform dependent.
  • There are pointers in C++
  • C ++ has operator overloading.
  • There is no garbage collection
  • Does’nt support multithreading
  • There are templates in java
  • There are global variables in c++

10) What is bytecode in java ?

JIT compiler stands for Just in time compiler. JIT compiler compiles byte code in to executable code . JIT a part of JVM .JIT cannot convert complete java program in to executable code it converts as and when it is needed during execution.

11) What is bytecode in java ?

When a javac compiler compiler compiles a class it generates .class file. This .class file contains set of instructions called byte code. Byte code is a machine independent language and contains set of instructions which are to be executed only by JVM. JVM can understand this byte codes.

12) Difference between this() and super() in java ?

this() is used to access one constructor from another with in the same class while super() is used to access superclass constructor. Either this() or super() exists it must be the first statement in the constructor.

13) What is a class ?

Classes are fundamental or basic unit in Object Oriented Programming .A class is kind of blueprint or template for objects. Class defines variables, methods. A class tells what type of objects we are creating. For example take Department class tells us we can create department type objects. We can create any number of department objects.

All programming constructs in java reside in class. When JVM starts running it first looks for the class when we compile. Every Java application must have atleast one class and one main method. Class starts with class keyword. A class definition must be saved in class file that has same as class name. File name must end with .java extension.

public class FirstClass

{public static void main(String[] args)

{System.out.println(“My First class”);

}

}

If we see the above class when we compile JVM loads the FirstClass and generates a .class file(FirstClass.class). When we run the program we are running the class and then executes the main method.

14) What is an object ?

An Object is instance of class. A class defines type of object. Each object belongs to some class.Every object contains state and behavior. State is determined by value of attributes and behavior is called method. Objects are alos called as an instance.                                 

To instantiate the class we declare with the class type.

public classFirstClass {public static voidmain(String[] args)

{

FirstClass f=new FirstClass();

System.out.println(“My First class”);

}

}

To instantiate the FirstClass we use this statement

FirstClass f=new FirstClass();

f is used to refer FirstClass object              

15) What is an object ?

It contains the executable body that can be applied to the specific object of the class.

Method includes method name, parameters or arguments and return type and a body of executable code.

Syntax : type methodName(Argument List){

}

ex : public float add(int a, int b, int c) methods can have multiple arguments. Separate with commas when we have multiple arguments.

16) What is encapsulation ?

The process of wrapping or putting up of data in to a single unit class and keeps data safe from misuse is called encapsulation .

Through encapsulation we can hide and protect the data stored in java objects.Java supports encapsulation through access control. There are four access control modifiers in java public , private ,protected and default level.

For example take a car class , In car we have many parts which is not required for driver to know what all it consists inside. He is required to know only about how to start and stop the car. So we can expose what all are required and hide the rest by using encapsulation.

17) Why main() method is public, static and void in java ?

public : “public” is an access specifier which can be used outside the class. When main method is declared public it means it can be used outside class.

static : To call a method we require object. Sometimes it may be required to call a method without the help of object. Then we declare that method as static. JVM calls the main() method without creating object by declaring keyword static. 

void : void return type is used when a method does’nt return any value . main() method does’nt return any value, so main() is declared as void.

Signature : public static void main(String[] args) {

18) Explain about main() method in java ?

Main() method is starting point of execution for all java applications.

public static void main(String[] args) {}

String args[] are array of string objects we need to pass from command line arguments.

Every Java application must have atleast one main method.

19)What is constructor in java ?

A constructor is a special method used to initialize objects in java.

we use constructors to initialize all variables in the class when an object is created. As and when an object is created it is initialized automatically with the help of constructor in java. We have two types of constructors
Default Constructor
Parameterized Constructor
Signature : public classname()
{
}
Signature : public classname(parameters list)
{
}

20) What is difference between length and length() method in java ?

length() : In String class we have length() method which is used to return the number of characters in string.
Ex : String str = “Hello World”;
System.out.println(str.length());
Str.length() will return 11 characters including space.
length : we have length instance variable in arrays which will return the number of values or objects in array.
For example :
String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”};
Will return 6 since the number of values in days array is 6.

21) What is ASCII Code?

ASCII stands for American Standard code for Information Interchange. ASCII character range is 0 to 255. We can’t add more characters to the ASCII Character set. ASCII character set supports only English. That is the reason, if we see C language we can write c language only in English we can’t write in other languages because it uses ASCII code.

22) What is Unicode ?

Unicode is a character set developed by Unicode Consortium. To support all languages in the world Java supports Unicode values. Unicode characters were represented by 16 bits and its character range is 0-65,535.

Java uses ASCII code for all input elements except for Strings,identifiers, and comments. If we want to use Punjabi we can use Punjabi characters for identifiers.We can enter comments in Punjabi

23) What is Unicode ?

Character constant is enclosed in single quotes. String constants are enclosed in double quotes. Character constants are single digit or character. String Constants are collection of characters.

Ex :’2’, ‘A’

Ex : “Hello World”

24) What are constants and how to create constants in java?

Constants are fixed values whose values cannot be changed during the execution of program. We create constants in java using final keyword.

Ex : final int number =10;

final String str=”java-interview –questions”

25) Difference between ‘>>’ and ‘>>>’ operators in java?

>> is a right shift operator shifts all of the bits in a value to the right to a specified number of times.

int a =15;

a= a >> 3;

The above line of code moves 15 three characters right.

>>> is an unsigned shift operator used to shift right. The places which were vacated by shift are filled

with zeroes.


Php interview question

Category : News

Interview Questions
&
Answers

PHP Interview questions and Answers

100 + PHP Question and Answer

1. Who is the father of PHP ?

 Rasmus Lerdorf is known as the father of PHP.

2. What is the difference between $name and $$name?

$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh

3) How can we submit a form without a submit button?

Java script submit() function is used for submit form without submit button on click call document.formname.submit() 

4)In how many ways we can retrieve the data in the result set of MySQL using PHP?

We can do it by 4 Ways 1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc 

5.What is the difference between mysql_fetch_object and mysql_fetch_array?

mysql_fetch_object() is similar tomysql_fetch_array(), with one difference – an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names). 

6.What are the differences between Get and post methods.

There are some defference between GET and POST method  1. GET Method have some limit like only 2Kb data able to send for request  But in POST method unlimited data can we send  2. when we use GET method requested data show in url but  Not in POST method so POST method is good for send sensetive request 

7.How can we extract string "pcds.co.in " from a string "http://info@pcds.co.in using regular expression of PHP?

preg_match(“/^http:\/\/.+@(.+)$/”,”http://info@pcds.co.in”,$matc hes); echo $matches[1]; 

8.How can we create a database using PHP and MySQL?

We can create MySQL database with the use of mysql_create_db(“Database Name”) 

9.What are the differences between require and include?

Both include and require used to include a file but when included file not found  Include send Warning where as Require send Fatal Error . 

10. Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?

 Yes we can use include(“xyz.php”) more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob  

11. What are the different tables(Engine) present in MySQL, which one is default?

 Following tables (Storage Engine) we can create 

1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. ) 

2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)

 3. Merge

 4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. ) 

5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMITand ROLLBACK operations on transactions)  

6. EXAMPLE  

7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. ) 

8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. ) 

9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)

 10. BLACKHOLE (The BLACKHOLE storage engine acts as a “black hole” that accepts data but throws it away and does not store it. Retrievals always return an empty result)   

 

12. What is use of header() function in php ?

The header() function sends a raw HTTP header to a client.We can use herder()  function for redirection of pages. It is important to notice that header() must be called before any actual output is seen.. 

13. How can I execute a PHP script using command line?

Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. 

14.Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ?

In php.ini file: set short_open_tag=on to make PHP support 

15.Shopping cart online validation i.e. how can we configure Paypal, etc.?

Nothing more we have to do only redirect to the payPal url after submit all information needed by paypal like amount,adresss etc. 

16. What is meant by nl2br()?

Inserts HTML line breaks (<BR />) before all newlines in a string. 

17.What is htaccess? Why do we use this and Where?

.htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all  subdirectories thereof. 

18.How we get IP address of client, previous reference page etc ?

By using $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_REFERER’] etc

19.What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and operating systems?

All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language. 

20.How can we encrypt the username and password using PHP?

AES_ENCRYPT () and AES_DECRYPT () 

21. What are the features and advantages of object-oriented programming?

One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system 

22.What are the differences between procedure-oriented languages and object-oriented languages?

There are lot of difference between procedure language and object oriented like below 1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model 2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern 3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .

 

23. What is the use of friend function?

Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match. 

24.What are the differences between public, private, protected, static, transient, final and volatile?

Public: Public declared items can be accessed everywhere. 

Protected: Protected limits access to inherited and parent classes (and to the class that defines the item). 

Private: Private limits visibility only to the class that defines the item. 

Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

 Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. 

transient: A transient variable is a variable that may not be serialized.  

volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time

25.What are the different types of errors in PHP?

Three are three types of errors:1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place. 

26.What is the functionality of the function strstr and stristr?

strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.  $email= ‘sonialouder@gmail.com’; $domain = strstr($email, ‘@’); echo $domain; // prints @gmail.com here @ is the needle  stristr is case-insensitive means able not able to diffrenciate between a and A  

 

27.What are the differences between PHP 3 and PHP 4 and PHP 5?

There are lot of difference among these three version of php

 1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come 

 2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C  In PHP5 

1. Implementation of exceptions and exception handling 

2. Type hinting which allows you to force the type of a specific argument 

3. Overloading of methods through the __call function 

4. Full constructors and destructors etc through a __constuctor and __destructor function 

5. __autoload function for dynamically including certain include files depending on the class you are trying to create. 

6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

 7 Interfaces & Abstract Classes

 8 Passed by Reference : 

 9 An __clone method if you really want to duplicate an object 

10 Numbers of Functions Deprecated in php 5.x like ereg,ereg_replace,magic_quotes_runtime, session_register,register_globals, split(), call_user_method() etc 

28.How can we convert asp pages to PHP pages?

there are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available athttp://asp2php.naken.cc./ 

29. What is the functionality of the function htmlentities?

Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. 

30.How can we get second of the current time using date function?

$second = date(“s”);

31.How can we convert the time zones using PHP?

 By using date_default_timezone_get and  date_default_timezone_set function on PHP 5.1.0 

 <?php // Discover what 8am in Tokyo relates to on the East Coast of the US     

 

// Set the default timezone to Tokyo time: date_default_timezone_set(‘Asia/Tokyo’);     

 

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000 $stamp = mktime(8, 0, 0, 1, 1, 2000);     

 

// Now set the timezone back to US/Eastern date_default_timezone_set(‘US/Eastern’);     

 

// Output the date in a standard format (RFC1123), this will print: 

// Fri, 31 Dec 1999 18:00:00 EST

 echo ‘<p>’, date(DATE_RFC1123, $stamp) ,'</p>’;?> 

32.What is meant by urlencode and urldocode?

URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in  application/x-www-form-urlencoded media type.  

urldecode decodes any %## encoding in the given string

33.What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system. unset() makes a variable undefined. 

34.How can we register the variables into a session?

$_SESSION[‘name’] = “sonia”; 

35.How can we get the properties (size, type, width, height) of an image using PHP image functions

To know the Image type use exif_imagetype () function

 To know the Image size use getimagesize () function

 To know the image width use imagesx () function 

To know the image height use imagesy() function t 

36.How can we get the browser properties using PHP?

By using  $_SERVER[‘HTTP_USER_AGENT’] variable. 

37.What is the maximum size of a file that can be uploaded using PHP and how can we change this?

By default the maximum size is 2MB. and we can change the following setup at php.iniupload_max_filesize = 2M 

38. How can we increase the execution time of a PHP script?

by changing the following setup at php.inimax_execution_time = 30 ; Maximum execution time of each script, in seconds 

39.How can we take a backup of a MySQL table and how can we restore it. ?

To backup: BACKUP TABLE tbl_name[,tbl_name…] TO 

‘/path/to/backup/directory’ RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table. -t, –no-create-info Don’t write table creation information (the CREATE TABLE statement). -d, –no-data Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table! 

 

40. How can we optimize or increase the speed of a MySQL select query?

• first of all instead of using select * from table1, use select column1, column2, column3.. from table1

 • Look for the opportunity to introduce index in the table you are querying. 

• use limit keyword if you are looking for any specific number of rows from the result set. 

41.How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

42.How can we destroy the session, how can we unset the variable of a session?

session_unregister — Unregister a global variable from the current session session_unset — Free all session variables

43.How can we set and destroy the cookie n php

By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ; Set the cookies in past for destroy. like  setcookie(“user”, “sonia”, time()+3600); for set the cookie  setcookie(“user”, “”, time()-3600); for destroy or delete the cookies; 

44.How many ways we can pass the variable through the navigation between the pages?

• GET/QueryString 

• POST 

45.What is the difference between ereg_replace() and eregi_replace()?

eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters. 

46. What are the different functions in sorting an array?

Sort(), arsort(), 

asort(), ksort(),

 natsort(), natcasesort(), 

rsort(), usort(),

 array_multisort(), and

 uksort(). 

47. How can we know the count/number of elements of an array?

2 ways 

a) sizeof($urarray) This function is an alias of count()

 b) count($urarray) 

48. what is session_set_save_handler in PHP?

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database. 

49.How can I know that a variable is a number or not using a JavaScript?

bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number. 

  

50.List out some tools through which we can draw E-R diagrams for mysql.

Case Studio

 Smart Draw 

51.How can I retrieve values from one database server and store them in other database server using PHP?

we can always fetch from one database and rewrite to another. here is a nice solution of it.$db1 = mysql_connect(“host”,”user”,”pwd”) 

mysql_select_db(“db1”, $db1); 

$res1 = mysql_query(“query”,$db1);$db2 = 

mysql_connect(“host”,”user”,”pwd”) 

mysql_select_db(“db2”, $db2); 

$res2 = mysql_query(“query”,$db2);At this point you can only fetch 

records from you previous ResultSet,

 i.e $res1 – But you cannot execute new query in $db1, even if you 

supply the link as because the link was overwritten by the new db.so 

at this point the following script will fail 

$res3 = mysql_query(“query”,$db1); //this will failSo how to solve that?  

take a look below. 

$db1 = mysql_connect(“host”,”user”,”pwd”)

 mysql_select_db(“db1”, $db1);

 $res1 = mysql_query(“query”,$db1); 

$db2 = mysql_connect(“host”,”user”,”pwd”, true) 

mysql_select_db(“db2”, $db2); 

$res2 = mysql_query(“query”,$db2); 

So mysql_connect has another optional boolean parameter which indicates whether a link will be created or not. as we connect to the $db2 with this optional parameter set to ‘true’, so both link will remain live. 

now the following query will execute successfully.

 $res3 = mysql_query(“query”,$db1); 

 

52.List out the predefined classes in PHP?

Directory 

stdClass 

__PHP_Incomplete_Class 

exception 

php_user_filter 

53.How can I make a script that can be bi-language (supports English, German)?

You can maintain two separate language file for each of the language. all the labels are putted in both language files as variables and assign those variables in the PHP source. on runtime choose the required language option. 

54.What are the difference between abstract class and interface?

 Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract.

 Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class. 

55.How can we send mail using JavaScript?

JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to approve it. 

56.How can we repair a MySQL table?

The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended] This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is given it will create index row by row 

57.What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs.

 For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.   

58.How many values can the SET function of MySQL take?

MySQL set can take zero or more values but at the maximum it can take 64 values 

59.What are the other commands to know the structure of table using MySQL commands except explain command?

describe Table-Name; 

60. How many tables will create when we create table, what are they?

The ‘.frm’ file stores the table definition. 

The data file has a ‘.MYD’ (MYData) extension. 

The index file has a ‘.MYI’ (MYIndex) extension, 

61.What is the purpose of the following files having extensions 1) .frm 2) .myd 3) .myi? What do these files contain?

In MySql, the default table type is MyISAM. 

Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. 

The ‘.frm’ file stores the table definition. 

The data file has a ‘.MYD’ (MYData) extension. 

The index file has a ‘.MYI’ (MYIndex) extension, 

62. What is maximum size of a database in MySQL?

If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected. 

The amount of available disk space limits the number of tables.

 MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM

 storage engine in MySQL 3.23, the maximum table size was increased 

to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, 

the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL 

internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace

 that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw

 disk 

partitions, which allows extremely large tables. The maximum tablespace size is 64TB.

 The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation

 specific to your operating system.

 Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB) 

Linux 2.4+ (using ext3 filesystem) 4TB 

Solaris 9/10 16TB

 NetWare w/NSS filesystem 8TB 

Win32 w/ FAT/FAT32 2GB/4GB 

Win32 w/ NTFS 2TB (possibly larger)

 MacOS X w/ HFS+ 2TB 

63. Give the syntax of Grant and Revoke commands?

 The generic syntax for grant is as following

 > GRANT [rights] on [database/s] TO [username@hostname] 

IDENTIFIED BY

 [password] 

now rights can be 

a) All privileges 

b) combination of create, drop, select, insert, update and delete 

etc.We can grant rights on all 

databse by using *.* or some specific database by database.* or a specific table by database.table_name

 username@hotsname can be either username@localhost, username@hostname

 and username@% 

where hostname is any valid hostname and % represents any name, the *.* 

any condition password is simply the

 password of userThe generic syntax for 

revoke is as following 

> REVOKE [rights] on [database/s] FROM [username@hostname] 

now rights can be as explained above 

a) All privileges

b) combination of create, drop, select, insert, update and delete etc. username@hotsname can be either username@localhost, username@hostname and username@% 

where hostname is any valid hostname and % represents any name, the *.* any condition 

 

64.Explain Normalization concept?

The normalization process involves getting our data to

 conform to three progressive normal forms, and a higher level of normalization 

cannot be achieved until the previous levels have been achieved

 (there 

are actually five normal forms, but the last two are mainly academic 

and

 will not be discussed).First Normal FormThe First Normal Form (or

1NF) involves removal of redundant data 

from horizontal rows. We want to ensure that there is no duplication

 of

 data in a given row, and that every column stores the least amount 

of

 information possible (making the field atomic).Second Normal 

FormWhere the First Normal Form deals with redundancy of data

 across a 

horizontal row, Second Normal Form (or 2NF) deals with redundancy 

of

 data in vertical columns. As stated earlier, the normal forms are

 progressive, so to achieve Second Normal Form, your tables must

 already 

be in First Normal Form.Third Normal Form  

I have a confession

 to make; I do not often use Third Normal Form.

 In

 Third Normal Form we are looking for data in our tables that is not 

fully dependant on the primary key, but dependant on another value

 in

 the table 

65.How can we find the number of rows in a table using MySQL?

Use this for mysql

 >SELECT COUNT(*) FROM table_name;

66.How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link);

 $num_rows = mysql_num_rows($result); 

echo “$num_rows rows found”; 

67.How many ways we can we find the current date using MySQL?

SELECT CURDATE();

 CURRENT_DATE() = CURDATE() 

for time use

 SELECT CURTIME(); 

CURRENT_TIME() = CURTIME() 

68. What are the advantages and disadvantages of Cascading Style Sheets?

External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be created for use on multiple HTML element types in many documents.Selector and grouping methods can be used to apply styles under complex contextsDisadvantagesAn extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitionsEmbedded Style Sheets  

Advantages 

Classes can be created for use on multiple tag types in the document. Selector and grouping methods can be used to apply styles under complex contexts. No additional downloads necessary to receive style information 

Disadvantages 

This method can not control styles for multiple documents at once 

Inline Styles 

Advantages 

Useful for small quantities of style definitions. Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods 

Disadvantages 

Does not distance style information from content (a main goal of 

SGML/HTML). Can not control styles for multiple documents at once. 

Author can not create or control classes of elements to control 

multiple

 element types within the document. Selector grouping methods can 

not be

 used to create complex element addressing scenarios  

69. What type of inheritance that PHP supports?

In PHP an extended class is always dependent on a single base 

class,

 that is, multiple inheritance is not supported. Classes are extended 

using the keyword ‘extends’. 

70. What is the difference between Primary Key and Unique key?

 Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.  

Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table. 

71.what is garbage collection? default time ? refresh time?

Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. Garbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory. There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100  

 

72. What are the advantages/disadvantages of MySQL and PHP?

Both of them are open source software (so free of cost), support cross platform. php is faster then ASP and JSP. 

73.What is the difference between GROUP BY and ORDER BY in Sql?

ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what 

columns

 it should sort the result. If two rows will hawe the same value in col1

 it will try to sort them according to col2 and so on.GROUP BY

 [col1],[col2],…,[coln]; Tels DBMS to group results with same value 

of 

column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with 

it, if 

you want to count all items in group, sum all values or view average 

74. What is the difference between char and varchar data types?

Set char to occupy n bytes and it will take n bytes even if u r 

storing a value of n-m bytes 

Set varchar to occupy n bytes and it will take only the required

 space 

and will not use the n bytes

 eg. name char(15) will waste 10 bytes if we store ‘romharshan’,

 if each char 

takes a byte 

eg. name varchar(15) will just use 5 bytes if we store ‘romharshan’,

 if each 

char takes a byte. rest 10 bytes will be free. 

75. What is the functionality of md5 function in PHP?

Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using. 

76.How can I load data from a text file into a table?

you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly 

77. How can we know the number of days between two given dates using MySQL?

SELECT DATEDIFF(“2007-03-07″,”2005-01-01”); 

78. How can we know the number of days between two given dates using PHP?

$date1 = date(“Y-m-d”); 

$date2 = “2006-08-15”;

 $days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24); 

79. How we load all classes that placed in different directory in one PHP File , means how to do auto load classes

by using spl_autoload_register(‘autoloader::funtion’); 

Like below  

 

class autoloader 

 

 

public static function moduleautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/modules/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

public static function daoautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/dataobjects/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

public static function includesautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/includes/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

 

spl_autoload_register(‘autoloader::includesautoloader’); 

 

spl_autoload_register(‘autoloader::daoautoloader’); 

 

spl_autoload_register(‘autoloader::moduleautoloader’); Like below  

 

class autoloader 

 

 

public static function moduleautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/modules/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

public static function daoautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/dataobjects/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

public static function includesautoloader($class) 

 

 

$path = $_SERVER[‘DOCUMENT_ROOT’] . “/includes/{$class}.php”; 

 

if (is_readable($path)) require $path; 

 

 

 

spl_autoload_register(‘autoloader::includesautoloader’); 

 

spl_autoload_register(‘autoloader::daoautoloader’); 

 

spl_autoload_register(‘autoloader::moduleautoloader’); 

 

80. How many types of Inheritances used in PHP and how we achieve it

As far PHP concern it only support single Inheritance in scripting. we can also use interface to achieve multiple inheritance. 

81.PHP how to know user has read the email?

Using Disposition-Notification-To: in mailheader we can get read

 receipt. 

Add the possibility to define a read receipt when sending an email.

 It’s quite straightforward, just edit email.php, and add this at 

vars definitions:

 var $readReceipt = null;

 And then, at ‘createHeader’ function add: 

if (!empty($this->readReceipt)) {  

$this->__header .= ‘Disposition-Notification-To: ‘ . $this

>__formatAddress($this->readReceipt) . $this->_newLine; 

 } 

82. What are default session time and path?

default session time in PHP is 1440 seconds or 24 minutes Default session save path id temporary folder /tmp   

83.how to track user logged out or not? when user is idle ?

By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server. 

84.how to track no of user logged in ?

whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors. 

85. in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5. 

86.for image work which library?

we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with. 

87.what is design pattern? singleton pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design. The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.  

 

88.what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()  

 

89.what is magic quotes?

Magic Quotes is a process that automagically escapes ncoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.  

 

90.what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed 

91.what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.  

 

92. what is the major php security hole? how to avoid?

1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 

 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 

3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes  

4. Never run unescaped queries

  5. For protected areas, use sessions or validate the login every time. 

 6. If you don’t want the file contents to be seen, give the file a .php extension.  

 

93. whether PHP supports Microsoft SQL server ?

The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server. 

94. what is MVC? why its been used?

Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITSNEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means: A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code    

95 .what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance 

96.what is CURL?

CURL means Client URL Library curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks. CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.  

 

97.what is PDO ?

The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code.  

WhilePDO has its advantages, such as a clean, simple, portable API but its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements. 

Just need to use below code for connect mysql using PDO

 try { 

$dbh = new 

PDO(“mysql:host=$hostname;dbname=databasename”, $username,

 $password); 

$sql = “SELECT * FROM employee”; 

foreach ($dbh->query($sql) as $row) {

 print $row[’employee_name’] .’ – ‘. $row[’employee_age’] ; 

catch(PDOException $e)

 { 

echo $e->getMessage();

 }  

98. What is PHP's mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.  

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:  

=>Object-oriented interface 

 =>Support for Prepared Statements  

=>Support for Multiple Statements  

=>Support for Transactions  

=>Enhanced debugging capabilities  

=>Embedded server support  

 

99. How can we encrypt the username and password using PHP?

encryption

AES_ENCRYT()  

ENCODE() 

DES_ENCRYPT() 

ENCRYPT()

MD5() 

OLD_PASSWORD()

PASSWORD() 

SHA() or SHA1()

Not available 

decryption

 AES_DECRYPT() 

DECODE() 

DES_DECRYPT() 

 Not available 

Not available 

Not available 

 Not available 

Not available 

UNCOMPRESSED_LENGTH() 


The top accounting interview

Category : News

Interview Questions
&
Answers

Top accounting Interview Questions

In simple way Meaning of Analogy is “Similarity ” or compassion between one thing and other thing base d on some similarity 

250 + Accounting Question and Answer

Q1. How many types of business transactions are there in accounting?

Ans.There are two types of business transactions in accounting – revenue and capital.

Q2. Explain real and nominal accounts with examples.

Ans. A real account is an account of assets and liabilities. E.g. land account, building account, etc.

A nominal account is an account of income and expenses. E.g. salary account, wages account, etc.

Q3. Which accounting platforms have you worked on? Which one do you prefer the most?

Ans. Describe the accounting platforms (QuickBooks, Microsoft Dynamic GP, etc.) that you have worked with and which one you liked the most.

Q4. What is double entry bookkeeping? What are the rules associated with it?

Ans.Double entry bookkeeping is an accounting principle where every debit has a corresponding credit. Thus, the total debit is always equal to the total credit. In this system, when one account is debited then another account gets credited at the same time.

Q5. What is working capital?

Ans. Working capital is calculated as current assets minus current liabilities, which is used in day-to-day trading.

Q6. How do you maintain accounting accuracy?

Ans. Maintaining the accuracy of an organisation’s accounting is an important activity as it can result in a huge loss. There are various tools and resources which can be used to limit the potential for errors to creep in and address quickly if any errors do arise.

Q7. What is TDS? Where do you show TDS on a balance sheet?

Ans. TDS (Tax Deducted at Source) is a concept aimed at collecting tax at every source of income. In a balance sheet, it is shown in the assets section, right after the head current asset.

Q8. What is the difference between ‘accounts payable (AP)’ and ‘accounts receivable (AR)’?

Accounts Payable

  • The amount a company owes because it purchased goods or services on credit from a vendor or supplier.
  • Accounts payable are liabilities                                      

Accounts Receivable

  • The amount a company has right to collect because it sold goods or services on credit to a customer
  • Accounts receivable are assets.

Q9. What is the difference between a trial balance and a balance sheet?

Ans. A trial balance is the list of all balances in a ledger account and is used to check the arithmetical accuracy in recording and posting.  A balance sheet, on the other hand, is a statement which shows the assets, liabilities and equity of a company and is used to ascertain its financial position on a particular date.

 

Q10. Is it possible for a company to show positive cash flows and still be in grave trouble?

Ans. Yes, if it shows an unsustainable improvement in working capital and involves lack of revenue going forward in the pipeline.

Q11. What are the common errors in accounting?

Ans.The common errors in accounting are – errors of omission, errors of commission, errors of principle and compensating error.

Q12. What is the difference between inactive and dormant accounts?

Ans. Inactive accounts are which that are closed and will not be used in the future. Dormant accounts are not currently functional but may be used in the future.

Q13. Are you familiar with the Accounting Standards? How many accounting standards are there in India?

Ans.There are currently 41 Accounting Standards which are usually issued by the Accounting Standards Board (ASB)

Q14. Why do you think Accounting Standards are mandatory?

Ans. Accounting Standards play an important role in preparing a good and accurate financial report. It ensures reliability and relevance in financial reports.

Q15. Have you ever helped your company to save money or use their available financial resources effectively?

Ans.Explain if you have proposed an idea which has affected the company’s finances positively. Tell how you have optimised the process and how you came to such a decision through historical data reviewing.

Q16. If our organisation has three bank accounts for processing payments, what is the minimum number of ledgers it needs?

Ans.Three ledgers for each account for proper accounting and reconciliation processes.

Q17. What are some of the ways to estimate bad debts?

Ans.Some of the popular ways of estimating bad debts are – percentage of outstanding accounts, aging analysis and percentage of credit sales.

Q18. What is a deferred tax liability?

Ans.Deferred tax liability signifies that a company may pay more tax in the future due to current transactions.

Q19. What is a deferred tax asset and how is the value created?

Ans. A deferred tax asset is when the tax amount has been paid or has been carried forward but has still not been recognized in the income statement. The value is created by taking the difference between the book income and the taxable income

Q20. What is the equation for Acid-Test Ratio in accounting?

Ans.The equation for Acid-Test Ratio in accounting

Acid-Test Ratio = (Current assets – Inventory) / Current Liabilities

Q21. What are the popular accounting applications?

Ans.. I am familiar with accounting apps like CGram Software, Financial Force, Microsoft Accounting Professional, Microsoft Dynamics AX and Microsoft Small Business Financials.

Q22. Which accounting application you like the most and why?

Ans.. I find Microsoft Accounting Professional the best as it offers reliable and fast processing of accounting transactions, thereby saving time and increasing proficiency.

Q23. Tell me something about GST.

Ans.GST is the acronym for Goods and Service Tax and it is an indirect tax other than the income tax. The seller charges it to the customer on the value of the service or product sold. The seller then deposits the GST to the government.

Q24. What is bank reconciliation statement?

Ans.A bank reconciliation statement or BRS is a form that allows individuals to compare their personal bank account records to that of the bank. BRS is prepared when the passbook balance differs from the cashbook balance.

Q25. What is tally accounting?

Ans.It is an accounting software used by small business and shops to manage routine accounting transactions.

Q26. What are fictitious assets?

Ans. Fictitious assets are intangible assets and their benefit is derived over a longer period, for example good will, rights, deferred revenue expenditure, miscellaneous expenses, preliminary expenses, and accumulated loss, among others.

Q27. Can you explain the basic accounting equation?

Ans.Yes, since we know that accounting is all about assets, liabilities and capital. Hence, its equation can be summarized as:

Assets = Liabilities + Owners Equity.

Q28. What are the different branches of accounting?

Ans.There are three branches of accounting –

  • Financial Accounting
  • Management Accounting
  • Cost Accounting

Q29. What is the meaning of purchase return in accounting?

Ans.As the name suggests, purchase return is a transaction where the buyer of merchandise, inventory or fixed assets returns these defective or unsatisfactory products back to the seller.

Q30. What is retail banking?

Ans.Retail banking or consumer banking involves a retail client, where individual customers use local branches of larger commercial banks.

 

Q31. What is offset accounting?

Ans.Offset accounting is a process of canceling an accounting entry with an equal but opposite entry. It decreases the net amount of another account to create a net balance.

Q32. What are trade bills?

Ans.These are the bills generated against each transaction. It is a part of documentation procedure for all types of transactions.

Q33. What is fair value accounting?

Ans. As per fair value accounting, a company has to show the value of all of its assets in terms of price on balance sheet on which that asset can be sold.

Q34. What happens to the cash, which is collected from the customers but not recorded as revenue?

Ans.It goes into “Deferred Revenue” on the balance sheet as a liability if no revenue has been earned yet.

Q35. Why did you choose accounting as your profession?

Ans.. I was good at numbers and accounting since my school days, but it was during my 10+2; I decided to adopt this field as a profession and did Bachelor’s and then Master’s in Accounting

Q36. What is a MIS report, have you prepared any?

Ans.Yes, I have prepared MIS reports. It is an acronym for Management Information System, and this report is generated to identify the efficiency of any department of a company.

Q37. What is a company’s payable cycle?

Ans.. It is the time required by the company to pay all its account payables.

Q38. What is Scrap Value in accounting?

Ans.. Scrap Value is the residual value of an asset that any asset holds after its estimated lifetime

Q39. Which account is responsible for interest payable?

Ans. Current liability account is responsible for interest payable.

Q40. What is departmental accounting system?

Ans.It is a type of accounting information system that records all the financial information and activities of the department. This financial information can be used to check profitability and efficiency of every department.

Q41. What is a perpetual inventory system?

Ans.Perpetual inventory is a methodology that involves recording the sale or purchase of inventory immediately using enterprise asset management software and computerized point-of-sale systems.

Q42. What do you mean when you say that you have negative working capital?

Ans.When a company’s current liabilities exceed its current assets, it is named as negative working capital. It is a common terminology in certain industries like retail and restaurant businesses.

Q43. What are the major constraints that can hamper relevant and reliable financial statements?

Ans.

  1. Delay, which leads to irrelevant information
  2. No balance between costs and benefits
  3. No balance between the qualitative characteristics
  4. No clarity in true and fair view presentation

Q44. Tell me the golden rules of accounting, just mention the statements.

Ans.There are three golden rules of accounting –

  • Debit the receiver, credit the giver
  • Debit what comes in, credit what goes out
  • Debit all expenses and losses, credit all incomes and gains

Q45. Please elaborate, what this statement means – “Debit the Receiver, Credit the Giver”.

Ans.So, this is among the most frequently asked accounting interview questions. Your reply should be –

This principle is used in the case of personal accounts. If a person is giving any amount either in cash or by cheque to an organization, it becomes an inflow and thus that person must be credited in the books of accounts. Therefore, when an organization received the money or cheque, it needs to credit the person who is paying and debit the organization.

Q46. Any idea what is ICAI?

Ans.Of course, it is the abbreviation of Institute of Chartered Accountants in India

Q47. What do you mean by premises?

Ans.Premises refer to fixed assets presented on a balance sheet.

Q48. What is Executive Accounting?

Ans.Executive Accounting is specifically designed for the service-based businesses. This term is popular in finance, advertising and public relations businesses.

Q49. What are bills receivable?

Ans.Bills receivable are the proceeds or payments, which a merchant or a company will be receiving from its customers.

When replying to accounting interview questions, be very specific and don’t speak up generic stuff.

Q50. Define Balancing.

Ans.Balancing means equating or balancing both debit and credit sides of a T-account.

Q51. What is Marginal Cost?

Ans.If there is any increase in the number of units produced, the total cost of output is changed. Marginal cost is that change in the cost of an additional unit of output.

Q52. What are Trade Bills?

Ans.Every transaction is documented and the trade bills are those documents, generated against each transaction.

Q53. Can you define the term Material Facts?

Ans.Yes, these are the documents such as vouchers, bills, debit and credit notes, or receipts, etc. They serve as the base of every account book.

Q54. What are the different stages of Double Entry System?

Ans.There are three different stages of double entry system, which are –

  • Recording transactions in the accounting systems
  • Preparing a trial balance in respective ledger accounts
  • Preparing final documents and closing the books of accounts

Q55. What are the disadvantages of a Double Entry System?

Ans.

  • Difficult to find the errors, especially when transactions are recorded in the books
  • In case of any error, extensive clerical labor is required
  • You can’t disclose all the information of a transaction, which is not properly recorded in the journal

Q56. What is Assets Minus Liabilities?

Ans.It stands for an owner’s or a stockholder’s equity.

Q57. What is GAAP?

AnsGAAP is the abbreviation for Generally Accepted Accounting Principles (GAAP) issued by the Institute of Chartered Accountants of India (ICAI) and the provisions of the Companies Act, 1956.  It is a cluster of accounting standards and common industry usage, and it is used by organizations to:

  • Record their financial information properly
  • Summarize accounting records into financial statements
  • Disclose information whenever required

Q58. Can you tell me some examples for liability accounts?

Ans.Some popular examples of liability accounts are –

  • Accounts Payable
  • Accrued Expenses
  • Bonds Payable
  • Customer Deposits
  • Income Taxes Payable
  • Installment Loans Payable
  • Interest Payable
  • Lawsuits Payable
  • Mortgage Loans Payable
  • Notes Payable
  • Salaries Payable
  • Warranty Liability

Q59. What is the difference between accounts receivable and deferred revenue?

Ans.Accounts receivable is yet-to be received cash from products or services that are already sold/delivered to customers, whereas, deferred revenue is the cash received from customers for services or goods not yet delivered.

Q60. Where should you record a cash discount in journal entry?

Ans.A cash discount should be recorded as a reduction of expense in cash account.

Q61. Explain ‘financial modelling’.

Ans. . Financial modelling is a quantitative analysis commonly used for either asset pricing or general corporate finance.

 

Q62. Walk me through a ‘cash flow statement.’

Ans.You’ll have to be well-prepared for this question. Start with the net income and go line by line explaining all major adjustments to arrive at cash flow from operating activities. Mention all the necessary parts that are associated with it.

Q63. Is it possible for a company to have positive cash flow but still be in serious financial trouble?

Ans.

Q64. What do you think is the best evaluation metric for analysing a company’s stock?

Ans.  Yes. There are two examples –

(i) a company that is selling off inventory but delaying payables will show positive cash flow for a while even though it is in trouble.
(ii) A company has strong revenues for the period but future forecasts show that revenues will decline.

Q65. What is ‘working capital’?

Ans. Working capital is the best defined as current assets minus current liabilities.

Q66. Explain quarterly forecasting and expense models?

Ans.The analysis of expenses and revenue which is predicted to be produced or incurred in future is called quarterly forecasting.

An expense model tells what expense categories are allowed on a particular type of work order.

Q67. What is the difference between a journal and a ledger?

Ans.The journal is a book where all the financial transactions are recorded for the first time. The ledger is one which has particular accounts taken from the original journal.

Q68. Mention one difference between a P&L statement and a balance sheet?

AnsThe balance sheet summarises the financial position of a company for a specific point in time. The P&L (profit and loss) statement shows revenues and expenses during a set period of time.

 

Q69. What is ‘cost accountancy’?

Ans.Cost accountancy is the application of costing and cost accounting principles, methods and techniques to the science, art and practice of cost control and the ascertainment of profitability as well as the presentation of information for the purpose of managerial decision making.

Q70. What is NPV? Where is it used?

AnsNet Present Value (NPV) is the difference between the present value of cash inflows and the present value of cash outflows. NPV is used in capital budgeting to analyse the profitability of a projected investment or project.

Q71. How many financial statements are there? Name them

Ans.There are four main financial statements – 1) balance sheets, 2) income statements, 3) cash flow statements, and 4) statements of shareholders’ equity.

Q72. What are ‘adjustment entries’?

Ans. Adjustment entries are accounting journal entries that convert a company’s accounting records to the accrual basis of accounting.

Q73. Do you follow the stock market? Which stocks in particular?

Ans. You need to be very careful in answering this question. As a financial analyst, following the stock market proves to be beneficial. Also, always be up-to-date with the stocks.

Q74. What is a ‘composite cost of capital’?

Ans. Also known as the weighted average cost of capital (WACC), a composite cost of capital is a company’s cost to borrow money given the proportional amounts of each type of debt and equity a company has taken on.

WACC= Wd (cost of debt) + Ws (cost of stock/RE) + Wp (cost of pf. Stock

Q75. What is ‘capital structure’?

Ans.The capital structure is how a firm finances its overall operations and growth by using different sources of funds.

Q76. What is a ‘goodwill’?

Ans.Goodwill is an asset that captures excess of the purchase price over fair market value of an acquired business.

Q77. Why did you select accounting as your profession?

Ans.Well, I was quite good at accounting throughout, but in my masters, when I got a distinction, I decided to adopt this field as a profession.

Q78. Do you have any professional experience in this field?

Ans.Yes, I have worked as an accountant at two different places.

Q79. Did you use accounting applications at your previous companies or prefer working manually??

Ans. Yes, I have used Advanced Business Solutions and AME Accounting Software in my previous jobs.

Q80 Can you name any other accounting application?

Ans.Yes, I am familiar with CGram Software, Financial Force, Microsoft Accounting Professional, Microsoft Dynamics AX and Microsoft Small Business Financials.

Q81 Which accounting application you prefer most and why?

Ans.I think all are good though, but Microsoft Accounting Professional is best because it offers reliable and fast processing of accounting transactions that saves time and increases proficiency. It helps with financial analysis as well.

Q82 What is the abbreviation for the accounting terms debit and credit?

Ans.The debit abbreviation is “dr” and credit abbreviation is “cr”.

Q83 How many types of business transactions are there in accounting?

Ans.There are two types of transactions in accounting, i.e. revenue and capital.

Q84 What is the balance sheet?

Ans.It is a statement that states all the liabilities and assets of the company at a certain point.

Q85 Have you ever heard about TDS, what it is?

Ans.Yes, TDS abbreviates Tax Deduction at Source.

Q86.Do you think there is any difference between inactive and dormant accounts?

Ans.Yes, both are different terms in accounting. Inactive accounts mean that accounts have been closed and will not be used in the future as well. While dormant accounts are those that are not functional today but may be used in the future.

Q87.What is tally accounting?

Ans.It is the software used for accounting in small business and shops for managing routine accounting transactions.

Q88. By saying, perpetual or periodic inventory system; what do we mean?

Ans.In the first one, i.e. the perpetual inventory system, the accounts are adjusted on a continual basis. In the periodic inventory system, the accounts are adjusted periodically.

Q89. In accounting, how do you define the premises?

Ans.Premises refer to fixed assets that are shown in the balance sheet.

Q90. What is a CPA?

Ans.CPA stands for Certified Public Accountant. To become a CPA, one should have to do many other qualifications as well. It is a qualification with a 150-hour requirement. It means that one should complete 150 credit hours at an accredited university.

Q91 Define Public accounting?

Ans. Public accounting offers audits and CPAs to review company financial records to ensure accountability. It is for the general public.

Q92.Define Executive accounting?

Ans.It is a type of accounting that is specifically designed for the business that offers services to users.

Q93. Differentiate Accounting and Auditing?

Ans.Accounting is all about recording daily business activities while auditing is the checking that whether all these events have been noted down correctly or not.

Q94 What do we mean by purchase return in accounting?

Ans.It is the term introduced in the records for every defective or unsatisfactory good returned back to its supplier.

Q95. Define the term material facts in accounting?

Ans.Material facts are the bills or any document that becomes the base of every account book. It means that all those documents, on which account book is prepared, are called material facts.

Q96.Have you ever made MIS reports and what are they?

Ans.Yes, I have prepared a few MIS reports during my previous jobs. MIS reports are created to identify the efficiency of any department of a company.

Q97. Define a company's payable cycle?

Ans.It is the time required by the company to pay all its account payables.

Q98. How much mathematics knowledge is necessary or required in accounting?

Ans.Not much knowledge but basic mathematical background is required in accounting for operations like addition, subtraction, multiplication, and division.

Q99. Differentiate between consignor and consignee?

Ans.Consigner is the owner of the goods, or you can say he is the person who delivers the goods to the consignee. The consignee is the person who receives the goods.

Q100. Define Partitioning in accounting?

Ans.It is a kind of groups made on the basis of the same responses by a system.

Q101. Differentiate Accounting and Auditing?

Ans.Accounting is all about recording daily business activities while auditing is the checking that whether all these events have been noted down correctly or not.

Q102. Define Offset accounting?

Ans.Offset accounting is one that decreases the net amount of another account to create a net balance.

Q103.Define trade bills?

Ans.We know that all types of transactions need to be documented. The trade bills are the documents, generated against each transaction.

Q104.Under the accrual basis of accounting, when revenues are reported in the accounting period?

Ans.When service or goods have been delivered, then revenues are reported in the accounting period.

Q105. Explain what a deferred asset is and give an example?

Ans.A deferred asset refers to a deferred debit or a deferred charge. An example of a deferred charge is bond issue costs. These costs involve all of the fees or charges that an organization incurs in order to register and issue bonds. These fees are paid in a near time when the bonds are issued but it will not be expensed at that time.

Q106.What is "deposit in transit"?

Ans.A deposit in transit is a check or cash that have been received and recorded by an entity, but which have not yet been entered in the records of the bank where the funds are deposited.

Q107. What is an over accrual?

Ans.An over accrual is a condition where the estimate for an accrual journal entry is too high. This estimate may apply to the accrual of expense or revenue.

Q108.) What happens to the company's "Cash Account" if it borrows money from the bank by signing a note payable?

Ans.Due to double entry, the “cash account” will increase as such the liability account increases.

Q109. What is reversing journal entries?

Ans.Reversing journal entries are entries made at the beginning of an accounting period to cancel out the adjusting journal entries made at the end of the previous accounting period.

Q110.Deferred taxation is a part of which equity?

Ans.Deferred taxation is a part of the owner’s equity

Q111.What is the equation for Acid-Test Ratio in accounting?

Ans.The equation for Acid-Test Ratio in accounting

Acid-Test Ratio = (Current assets – Inventory) / Current Liabilities

Q112.Mention why some asset accounts have a credit balance?

Ans.Some asset accounts have a credit balance due to the following reasons,

  • Receiving and posting an amount that was higher than the recorded receivable
  • Expenses occurred faster than the agreed upon prepayments
  • An error caused by posting an amount to a wrong account
  • The amount of checks written exceeded the positive amount in the Cash account
  • Continuing to amortize or depreciate an asset after its balance has reached zero

Q113. What is the Master Account?

Ans.A Master Account has subsidiary accounts. A master account receivable could be anything, it could be account receivable for various individual receivable accounts.

Q114. What is Bad debt expense?

Ans.A Bad debt expense is the amount of an account receivable that is considered to NOT be collectible.

Q115.In which account does the unpresented cheque will get recorded?

Ans.The unpresented cheque will get recorded as a credit to the cash account in the company’s General ledger.

Q116.What knowledge should financial accountant have?

Ans.A certified financial accountant should have knowledge about

  • Accounting/Bookkeeping principles and practices
  • Reporting and analysis of financial data
  • Auditing practices and principles
  • Account management
  • Budgets
  • Software knowledge dealing with Accounting
  • Knowledge of relevant laws, codes, and regulations
  • Good soft skills
  • Being a team player
  • Ability to learn quickly and up skill
  • Basic Technical skills

Q117.What are the three factors that can affect your cash flow and business profitability?

Ans.The three factors that can affect your cash flow and business profit includes

  • Cash flows from investing activities: It includes shares, bonds, physical property, machinery, etc.
  • Cash flows from operating activities: It does not include cash received from other sources like investments
  • Cash flow from financing activities: It includes any activities that involve dividend payments that the company made to its shareholders, any money that includes stock to the public, any money borrowed from the lender, etc. in other words, it is a report that tells the firm about the money borrowed and paid out in order to finance its activities.

Q118.Explain what is accrual accounting?

Ans.Accrual Accounting is a method for measuring the performance and position of the company by identifying economic events regardless of when the cash transaction happened. In this method, revenue is compared with the expenditures, at the time in which the transaction happens rather than when the payment is made.

Q119. Explain the term account payable?

Ans.Account payable is referred to as the amount the company owes to its suppliers, its employees, and its partners. In other words, it is the basic cost levied on the company to run a business process that is outstanding. Account payable for one company may be account receivable for another firm or company.

Q120.) Explain the meaning of long-term notes payable is or long term liabilities?

Ans.Long-term notes payable or liabilities are referred for that loan that is not supposed to due for more than a year. These are the loans from banks or financial institution that are secured against various assets on the balance sheet, such as inventories.

Q121.What does the financial statement of the company include?

Ans.Financial statement of the company includes various information like

  • Balance Sheet ( Assets, liabilities, and equity)
  • Income statement ( Profit or Loss statement)
  • Equity statement
  • Cash flow statement

Q122. Explain what is GAAP?

AnsGAAP means Generally Accepted Accounting Principle; it is a framework of accounting, standards, procedures & rules determined by the professional accounting industry and practiced by publicly traded U.S companies all over the U.S.A.

Q123. Mention the types of ledgers?

Ans.There are three types of ledger

  • General ledger
  • Debtors ledger
  • Creditors ledger

Q124.Explain what is double-entry accounting? Explain with an example?

Ans.Double entry accounting is an accounting system that requires recording business transaction or event in at least two accounts. It is the same concept of accounting, where every debit account should be matched with a credit account.

For example, if a company takes a loan from a bank, it receives cash as an asset but at the same time, it creates a liability on a company. This single entry will affect both accounts, the asset accounts, and the liabilities accounts, such entry is referred to as double entry accounting.

Q125.. Explain What Is Cash Flow And Fund Flow?

Ans.Cash flow and funds flow: cash flow means direct entry of cash in your business and exit of the same funds flow means entry of funds (cash funds or non cash funds) and their exit non cash funds may mean rise in current assets or fall in current liabilities which was not due to any cash movement.

Q126. Is There A Difference Between Accounting For Conversion Of Bonds And Accounting For The Conversion Of Preferred Stock?

Ans.Bonds have discounts and premiums and accrued interest. Preferred Stock does not.

Q127.How Many Invoices On Average Do You Handle On A Weekly/monthly Basis?

Ans.Show your understanding of the invoice verification process. Go through each step in detail such as checking that goods have been received in proper condition or services rendered in a satisfactory manner. Explain the importance of each step.

Q128.Explain What Is Customer Account?

Ans.Debtors account and bills receivable account are theoretically same. Both are called as receivables. When we sold goods to debtors account is debited. If we receive a bill from that debtor, we open bills receivable account by closing that debtor account. Thus, bills receivable account is nothing but debtor account.

If the bill is dishonored on the due date, we again debit the debtor account in our books. For information and accounting purpose, we use both debtor account and bills receivable account.

Q129.Were You Happy With The Grades You Achieved At A-level?

Ans.Chartered Accountancy firms put a lot of weight on A-level grades as these have been found to be the best predictors of success in professional examinations.

If your A levels were not outstanding, this may sometimes depend more on the quality of the school you attended than your ability. In some inner-city schools it may be that a mediocre A-level performance that you achieved might have been the best in your school – if this is so, then make it clear. An average performance at a weak school academically may be the equivalent of a much better performance at some prestigious establishments.

Similarly, if there were any other external factors, such as illness, that may have affected your grades, tell the interviewers – but don’t sound as though you are making excuses.

Q130. What is the difference between depreciation and amortization?

Method Overloading

Depreciation

  • Depreciate means to lose the value of an asset due to their usage, wear and tear, outdated, etc.
  • The depreciation cost is calculated in terms of tangible assets like furniture, plant & machinery, building, etc.
  • The purpose of calculating depreciation costs recovery
  • The easiest way to calculate depreciation is to know the loss of value of an asset over its life.
  • For example, a car worth $30,000 has estimated the lifetime of 10 years after that it will have no value in the market. The cost or loss in value throughout these 10 years is known as depreciation
  • Various method for depreciation includes straight-line depreciation, declining balance method, group depreciation method, unit of     time/production depreciation method, etc.           

Method Overriding​

Amortization

  • Amortize means to write off or pay the debt over a period of time. Amortization can be for loans, or it can be for Intangible assets
  • Amortization cost is calculated in terms of intangible assets like goodwill, trademark, loans, patents, etc.
  • The purpose of calculating amortization is also for cost recovery
  • Amortization calculates the amount spent after the intangible assets throughout the life for that asset
  • For example, Pharmaceutical Company spent $20 million dollars on a drug patent with a useful life of 20 years. The amortization value for that company will be $1 million each year
  • Various method for amortization is negative amortization, zoning amortization, business amortization, etc.

Q131.Define the term material facts in accounting?

Ans.Material facts are the bills or any document that becomes the base of every account book. It means that all those documents, on which account book is prepared, are called material facts.

Q132. Define Offset accounting?

Ans.Offset accounting is one that decreases the net amount of another account to create a net balance.

Q133.What is the difference between accumulated depreciation and depreciation expense?

Ans.The difference between accumulated depreciation and depreciation expense is that

  • Accumulated depreciation: It is the total amount of depreciation that has been taken on a company’s assets up to the date of the balance sheet
  • Depreciation expense: It is the amount of depreciation that is reported on the income statement. Basically, it is the amount that corresponds only to the period of time indicated in the heading of the income statement.

Q134. Explain what a deferred asset is and give an example?

Ans.A deferred asset refers to a deferred debit or a deferred charge. An example of a deferred charge is bond issue costs. These costs involve all of the fees or charges that an organization incurs in order to register and issue bonds. These fees are paid in a near time when the bonds are issued but it will not be expensed at that time.

Q135.What is the Master Account?

Ans.A Master Account has subsidiary accounts. A master account receivable could be anything, it could be account receivable for various individual receivable accounts.

Q136.Tell Me What Is Accounting Normalization?

Ans.It is removing items from the income statement or balance sheet that do not normally occur during the course of business to better estimate the value of a company.

Q137.. Explain What Is Service Tax?

Ans.When any employer provides any service to his customer, which income is excess under the tax then company liable for the pay tax.In addition, service tax deposited of in under 5 days who you charged service tax to his customers.In the payment of Service tax amount you can Credit availed during of the month.

Q138. What is Wacc?

Ans.It denotes weighted average cost of capital. It is defined as the overall cost of capital computed by reference to the proportion of each component of capital as weights.

Q139. What is financial . Financial break-even point?

Ans.It denotes the level at which a firm’s EBIT is just sufficient to cover interest and preference dividend.

Q140.What i s Treasury management?

Ans.It means it is defined as the efficient management of liquidity and financial risk in business.

Q141. What is . Maximum permissible bank finance (MPBF)?

Ans.It is the maximum amount that banks can lend a borrower towards his working capital requirements.

Q142. What are Commercial paper?

Ans.A cp is a short term promissory note issued by a company, negotiable by endorsement and delivery, issued at a discount on face value as may be determined by the issuing company.

Q143. What is Bridge finance?

Ans.It refers to the loans taken by the company normally from commercial banks for a short period pending disbursement of loans sanctioned by the financial institutions.

Q144. What is ICD (Inter corporate deposits)?

Ans.Companies can borrow funds for a short period. For example 6 months or less from another company which have surplus liquidity? Such deposits made by one company in another company are called ICD.

Q145. What do you mean by certificate of deposits?

Ans. The CD is a document of title similar to a fixed deposit receipt issued by banks there is no prescribed interest rate on such CDs it is based on the prevailing market conditions.

Q146.What is Euro issues?

Ans.The euro issues means that the issue is listed on a European stock Exchange. The subscription can come from any part of the world except India.

Q147. What is Zero- base- budgeting?

Ans.It is a management tool which provides a systematic method for evaluating all operations and programmes, current of new allows for budget reductions and expansions in a rational inner and allows reallocation of source from low to high priority programs.

Q148. What is Hedging?

Ans.Hedging means minimize the risk.

Q149.What is Contingent liability?

Ans.An obligation to an existing condition or situation which may arise in future depending on the occurrence of one or more uncertain future events.

Q150. What is Contingency?

Ans.A condition (or) situation the ultimate out comes of which gain or loss will be known as determined only as the occurrence or non occurrence of one or more uncertain future events.

Q130. What is the difference between depreciation and amortization?

Method Overloading

Method Overriding​


Python Interview Questions and Answers

Category : News

Interview Questions
&
Answers

Python Interview questions and Answers

In simple way Meaning of Analogy is “Similarity ” or compassion between one thing and other thing base d on some similarity 

100 Python interview Question and Answer

1. What type of a language is python? Interpreted or Compiled?

Beginner’s Answer:
Python is an interpreted, interactive, object­oriented programming language.
Expert Answer:
Python is an interpreted language, as opposed to a compiled one, though the
distinction can be blurry because of the presence of the bytecode compiler. This means
that source files can be run directly without explicitly creating an executable which is
then run.

2.What do you mean by python being an “interpreted language”? (Continues from previous question)

An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine­ language instructions. In context of Python, it means that Python program runs directly from the source code.

3. What is python’s standard way of identifying a block of code?  

Indentation.   

4.Please provide an example implementation of a function called “my_func”  that returns the square of a given variable “x”. (Continues from previous  question) 

def my_func ( x ):  

 return x **2 

5. Is python statically typed or dynamically typed? 

  Dynamic.  

 In a statically typed language, the type of variables must be known (and usually  declared) at the point at which it is used. Attempting to use it will be an error. In a  dynamically typed language, objects still have a type, but it is determined at runtime.  You are free to bind names (variables) to different objects with a different type. So long  as you only perform operations valid for the type the interpreter doesn’t care what type  they actually are.   

6. Is python strongly typed or weakly typed language? 

 Strong. 

 In a weakly typed language a compiler / interpreter will sometimes change the  type of a variable. For example, in some languages (like  JavaScript ) you can add  strings to numbers ‘x’ + 3 becomes ‘x3’. This can be a problem because if you have  made a mistake in your program, instead of raising an exception execution will continue  but your variables now have wrong and unexpected values. In a strongly typed  language (like Python) you can’t perform operations inappropriate to the type of the  object ­ attempting to add numbers to strings will fail. Problems like these are easier to  diagnose because the exception is raised at the point where the error occurs rather than  at some other, potentially far removed, place.   

7.Create a unicode string in python with the string “This is a test string”? 

some_variable = u ‘ This is a test string ‘  

Or

  some_variable = u ” This is a test string

8. What is the python syntax for switch case statements? 

Python doesn’t support switch­case statements. You can use if­else statements  for this purpose.  

9. What is a lambda statement? Provide an example. 

A lambda statement is used to create new function objects and then return them at  runtime. 

Example:  my_func = lambda x : x **2  

 creates a function called my_func that returns the square of the argument  passed.

10..What are the rules for local and global variables in Python? 

If a variable is defined outside function then it is  implicitly global . If variable is  assigned new value inside the function means it is local . If we want to make it global we need to explicitly define it as global. Variable referenced inside the function are implicit  global 

 

11..What is the output of the following program? 
#!/usr/bin/python   
  def fun1 ( a ): 
 print 'a:' , a 
 a = 33; 
  print 'local a: ' , a  
 a = 100  
 fun1 ( a)
 print 'a outside fun1:' , a      

#!/usr/bin/python    

 def fun1 ( a ): 

 print ‘a:’ , a   a = 33; 

  print ‘local a: ‘ , a 

   a = 100 

  fun1 ( a)  

 print ‘a outside fun1:’ , a    

 Ans. 

 Output:  a : 100

 local a : 33  

 a outside fun1 : 100

12..What is the output of the following program? 

#!/usr/bin/python

def fun2():

        global b

         print ‘b: ‘ , b 

         b   =  33

         print ‘global b:’ , b

b = 100

fun2()

print ‘b outside fun2’ , b

Output: 

 b : 100   global 

b : 33

b outside fun2 : 33 

13.What is the output of the following program? 
#!/usr/bin/python
  def foo ( x , y )
global a  
a = 42
  x , y = y ,x
  b = 33
  b = 17  
c = 100
  print ( a , b , x , y)
a , b , x , y = 1 , 15 , 3 ,4  
foo ( 17 , 4)  
print ( a , b , x , y)

. Output:   42 17 4 17   

                   42 15 3 4 

14.What is the output of the following program? 
#!/usr/bin/pytho
def foo ( x =[]):   x . append ( 1)  
return x
foo ()
  foo ()

. Output:  [ 1]   

                  [ 1 , 1] 

15. What is the purpose of  #!/usr/bin/python  on the first line in the above  code? Is there any advantage? 

Ans. By specifying #!/usr/bin/python  you specify exactly which interpreter will be  used to run the script on a particular system . This is the hardcoded path to the python  interpreter for that particular system. The advantage of this line is that you can use a  specific python version to run your code. 

16.What is the output of the following program?
  list = [ 'a' , 'b' , 'c' , 'd' , 'e' ]
print list [ 10

 Output: 

 IndexError. Or Error.   

17.What is the output of the following program? 
list = [ 'a' , 'b' , 'c' , 'd' , 'e' ]
print list [ 10 :]

Ans . Output:  

[ ]   

The above code will output [], and will not result in an IndexError.   As one would expect, attempting to access a member of a list using an index that  exceeds the number of members results in an    IndexError 

18. What does this list comprehension do: 
[ x ** 2 for x in range ( 10 ) if x % 2 ==0]

. Creates the following list: 

        [ 0 , 4 , 16 , 36 , 64] 

19. Do sets, dictionaries and tuples also support comprehensions? 

Ans . Sets and dictionaries support it. However tuples are immutable and have  generators but not comprehensions.  

Set Comprehension: 

 r = { x for x in range ( 2 , 101 )  

 if not any ( x % y == 0 for y in range ( 2 , x ))}    

 Dictionary Comprehension:

  { i : j for i , j in { 1 : ‘a’ , 2 : ‘b’ }. items ()}  

  since 

 { 1 : ‘a’ , 2 : ‘b’ }. items () returns a list of 2 – Tuple . i is the first element of tuple j is the second. 

20.What are generators in Python? 

Ans . A generator is simply a function which returns an object on which you can call  next, such that for every call it returns some value, until it raises a StopIteration  exception, signaling that all values have been generated. Such an object is called an  iterator.  Normal functions return a single value using return, just like in Java. In Python,  however, there is an alternative, called yield. Using yield anywhere in a function makes  it a generator.    

21.What can you use Python generator functions for? 

Ans . One of the reasons to use generator is to make the solution clearer for some kind  of solutions.  The other is to treat results one at a time, avoiding building huge lists of results that you  would process separated anyway.  

22.When is not a good time to use python generators? 

Ans . Use list instead of generator when:    

1­ You need to access the data multiple times (i.e. cache the results instead of  recomputing them)  

  2­ You need random access (or any access other than forward sequential order):   

 3­ You need to join strings (which requires two passes over the data) 

   4­  You are using PyPy which sometimes can’t optimize generator code as much    as it can with normal function calls and list manipulations.  

23..What's your preferred text editor? 

Ans . Emacs. Any alternate answer leads to instant disqualification of the applicant 😛  

24..When should you use generator expressions vs. list comprehensions in  Python and vice­versa? 

Ans . Iterating over the generator expression or the list comprehension will do the same  thing. However, the list comp will create the entire list in memory first while the  generator expression will create the items on the fly, so you are able to use it for very  large (and also infinite!) sequences.  

25. What is a negative index in Python? 

Ans . Python arrays and list items can be accessed with positive or negative numbers. A  negative Index accesses the elements from the end of the list counting backwards.   

Example:  

a = [ 1 2 3]  

 print a [- 3] 

  print a [- 2]  

 Outputs:  

 2 

26. What is the difference between range and xrange functions? 

Ans . Range returns a list while xrange returns an xrange object which take the  same memory no matter of the range size. In the first case you have all items already  generated (this can take a lot of time and memory). In Python 3 however, range is  implemented with xrange and you have to explicitly call the list function if you want to  convert it to a list.

27. What is PEP8? 

Ans. 

PEP8 is a coding convention (a set of recommendations) how to write your  Python code in order to make it more readable and useful for those after you.

28.How can I find methods or attributes of an object in Python? 

 Ans. Built­in dir() function of Python ,on an instance shows the instance variables as  well as the methods and class attributes defined by the instance’s class and all its base  classes alphabetically. So by any object as argument to dir() we can find all the  methods & attributes of the object’s class  Built­in dir() function of Python ,on an instance shows the instance variables as  well as the methods and class attributes defined by the instance’s class and all its base  classes alphabetically. So by any object as argument to dir() we can find all the  methods & attributes of the object’s class  

29.. What is the statement that can be used in Python if a statement is required  syntactically but the program requires no action? 

Ans. 

         pass

30.Do you know what is the difference between lists and tuples? Can you give  me an example for their usage? 

Ans. 

First list are mutable while tuples are not, and second tuples can be hashed e.g.  to be used as keys for dictionaries. As an example of their usage, tuples are used when  the order of the elements in the sequence matters e.g. a geographic coordinates, “list”  of points in a path or route, or set of actions that should be executed in specific order.  Don’t forget that you can use them a dictionary keys. For everything else use lists  

31. What is the function of “self”? 

Ans. 

“Self” is a variable that represents the instance of the object to itself. In most of  the object oriented programming languages, this is passed to the methods as a hidden  parameter that is defined by an object. But, in python it is passed explicitly. It refers to  separate instance of the variable for individual objects. The variables are referred as  “self.xxx”.

32. How is memory managed in Python?  

Ans.  

Memory management in Python involves a private heap containing all  Python objects and data structures. Interpreter takes care of Python heap and  the programmer has no access to it. The allocation of heap space for Python  objects is done by Python memory manager. The core API of Python provides  some tools for the programmer to code reliable and more robust program. Python  also has a built­in garbage collector which recycles all the unused memory.    

 The gc module defines functions to enable /disable garbage collector: 

 gc . enable ()   ­Enables automatic garbage collection. 

 gc . disable () –  Disables automatic garbage collection  

33.. What is __init__.py?  

Ans.   It is used to import a module in a directory, which is called package import. 

34 .Print contents of a file ensuring proper error handling? 

Ans. 

try :    

  with open ( ‘filename’ , ‘r’ ) as f :  

    print f . read ()  

 except IOError:    

  print “No such file exists” 

35. How do we share global variables across modules in Python? 

Ans.  

We can create a config file and store the entire global variable to be  shared across modules in it. By simply importing config, the entire global variable  defined will be available for use in other modules.  

For example I want a, b & c to share between modules.  

config.py : 

 a=0 

 b=0

  c=0   

 module1.py:  

 import config   

config . a = 1 

  config . b =2  

 config . c =3  

 print ” a , b & resp . are : ” , config . a , config . b , config .c   ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

  output of module1 . py will be   

1 2 3 

36. Does Python support Multithreading? 

Ans . Yes  

37. How do I get a list of all files (and directories) in a given directory in Python? 

Ans . Following is one possible solution there can be other similar ones:­   

 import os    

 for dirname , dirnames , filenames in os . walk ( ‘.’ ):    

  # print path to all subdirectories first.     

 for subdirname in dirnames:    

      print os . path . join ( dirname , subdirname)     

   # print path to all filenames.    

  for filename in filenames:         

 print os . path . join ( dirname , filename)     

   # Advanced usage:    

  # editing the ‘dirnames’ list will stop os.walk() from recursing into there.    

  if ‘.git’ in dirnames:        

  # don’t go into any .git directories.       

   dirnames . remove ( ‘.git’) 

38. How to append to a string in Python? 

Ans . The easiest way is to use the += operator. If the string is a list of character, join()  function can also be used.  

39. How to convert a string to lowercase in Python?

Ans . use lower() function.  

   Example: 

 s = ‘ MYSTRING’  

 print s . lower ()

40. How to convert a string to lowercase in Python?  

Ans . Similar to the above question. use upper() function instead.   

41. How to check if string A is substring of string B? 

Ans . The easiest way is to use the in operator.   

  >>> ‘abc’ in ‘abcdefg’ 

 True

42. Find all occurrences of a substring in Python 

Ans .  There is no simple built­in string function that does what you’re looking for, but  you could use the more powerful regular expressions:   

 >>> [ m . start () for m in re . finditer ( ‘test’ , ‘test test test test’ )] 

  [ 0 , 5 , 10 , 15] // these are starting indices for the string 

43. What is GIL? What does it do?Talk to me about the GIL. How does it impact  concurrency in Python? What kinds of applications does it impact more than  others? 

Ans .  Python’s GIL is intended to serialize access to interpreter internals from different  threads. On multi­core systems, it means that multiple threads can’t effectively make  use of multiple cores. (If the GIL didn’t lead to this problem, most people wouldn’t care  about the GIL ­ it’s only being raised as an issue because of the increasing prevalence  of multi­core systems.)

  Note that Python’s GIL is only really an issue for CPython, the reference  implementation. Jython and IronPython don’t have a GIL. As a Python developer, you  don’t generally come across the GIL unless you’re writing a C extension. C extension  writers need to release the GIL when their extensions do blocking I/O, so that other  threads in the Python process get a chance to run. 

44. Print the index of a specific item in a list? 

Ans . use the index() function 

 >>> [ “foo” , “bar” , “baz” ]. index ( ‘bar’)

   1 

45.How do you iterate over a list and pull element indices at the same time? 

Ans . You are looking for the enumerate function. It takes each element in a sequence  (like a list) and sticks it’s location right before it. For example:  

>>> my_list = [ ‘a’ , ‘b’ , ‘c’] 

  >>> list ( enumerate ( my_list )) 

  [( 0 , ‘a’ ), ( 1 , ‘b’ ), ( 2 , ‘c’ )]     

Note that enumerate() returns an object to be iterated over, so wrapping it in list() just  helps us see what enumerate() produces.   

 An example that directly answers the question is given below   

 my_list = [ ‘a’ , ‘b’ , ‘c’]   

  for i , char in enumerate ( my_list ):     

 print i , char   

  The output is:   

 0 a  

 1 b 

  2 c

46. How does Python's list.sort work at a high level? Is it stable? What's the  runtime? 

Ans . In early python­versions, the sort function implemented a modified version of  quicksort. However, it was deemed unstable and as of 2.3 they switched to using an  adaptive mergesort algorithm. 

47. What does the list comprehension do: 

Ans.  my_list =[( x , y , z ) for x in range ( 1 , 30 ) for y in range ( x , 30 ) for z in 

range ( y , 30 ) if x ** 2 + y ** 2 == z ** 2]   

  Ans. It creates a list of tuples called my_list, where the first 2 elements are the  perpendicular sides of right angle triangle and the third value ‘z’ is the hypotenuse.  

 [( 3 , 4 , 5 ), ( 5 , 12 , 13 ), ( 6 , 8 , 10 ), ( 7 , 24 , 25 ), ( 8 , 15 , 17 ), ( 9 , 12 , 15 ), 

( 10 , 24 , 26 ), ( 12 , 16 , 20 ), ( 15 , 20 , 25 ), ( 20 , 21 , 29 )] 

48. How can we pass optional or keyword parameters from one function to  another in Python? 

Ans.    Gather the arguments using the * and ** specifiers in the function’s parameter list. This  gives us positional arguments as a tuple and the keyword arguments as a dictionary.  

Then we can pass these arguments while calling another function by using * and **:    

def fun1 ( a , * tup , ** keywordArg ):   … 

 keywordArg [ ‘width’ ]= ‘23.3c’  

 … 

  Fun2 ( a , * tup , ** keywordArg)

49. Explain the role of repr function. 

Ans.  

  Python can convert any value to a string by making use of two functions repr() or  str(). The str() function returns representations of values which are human­readable,  while repr() generates representations which can be read by the interpreter.  repr() returns a machine­readable representation of values, suitable for an exec  command.  

50. Python ­ How do you make a higher order function in Python? 

Ans. 

A higher­order function accepts one or more functions as input and returns a new  function. Sometimes it is required to use function as data To make high order function ,  we need to import functools module The functools.partial() function is used often for  high order function

51. What is map? 

Ans. 

The syntax of map is:   map ( aFunction , aSequence)   The first argument is a function to be executed for all the elements of the iterable given  as the second argument. If the function given takes in more than 1 arguments, then  many iterables are given. 

52.Tell me a very simple solution to print every other element of this list? 
L = [ 0 , 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90]

Ans. L [:: 2] 

53. Are Tuples immutable?  

Ans . Yes.     

54. Why is not all memory freed when python exits?  

Ans. Objects referenced from the global namespaces of Python modules are not  always de­allocated when Python exits. This may happen if there are circular  references. There are also certain bits of memory that are allocated by the C library that  are impossible to free (e.g. a tool like the one Purify will complain about these). Python  is, however, aggressive about cleaning up memory on exit and does try to destroy every  single object. If you want to force Python to delete certain things on de­allocation, you  can use the at exit module to register one or more exit functions to handle those  deletions.  

55.What is Java implementation of Python popularly know? 

Ans.  Jython.   

56. What is used to create unicode strings in Python?  

Ans.  

Add u before the string.  

 u ‘mystring’ 

57. What is a docstring? 

Ans. 

docstring is the documentation string for a function. It can be accessed by  function_name.__doc__  

58.Given the list below remove the repetition of an element. 

Ans.    words = [‘ one ‘, ‘ one ‘, ‘ two ‘, ‘ three ‘, ‘ three ‘, ‘ two ‘]   A bad solution would be to iterate over the list and checking for copies somehow and  then remove them!

A very good solution would be to use the set type. In a Python set, duplicates are not  allowed.   

So, list(set(words)) would remove the duplicates.   

 

59. Print the length of each line in the file ‘file.txt’ not including any  whitespaces at the end of the lines?  

Ans.   with open ( “filename.txt” , “r” ) as f1:  

  print len ( f1 . readline (). rstrip ())   rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs  (whitespace characters).  

60. What is wrong with the code?
func ([ 1 , 2 , 3 ]) # explicitly passing in a list  
func () # using a default empty list    
def func ( n = []):  
#do something with n    
print n

Ans. 

This would result in a NameError. The variable n is local to function func and  can’t be accessesd outside. So, printing it won’t be possible.    

61. What does the below mean? 
  s = a + ‘[‘ + b + ‘:’ + c + ‘]’ 

Ans.  

seems like a string is being concatenated. Nothing much can be said without  knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string,  TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used in the  statement.  

62. What are Python decorators? 

Ans.  

A Python decorator is a specific change that we make in Python syntax to alter  functions easily.  

63. What is namespace in Python? 

Ans.  

In Python, every name introduced has a place where it lives and can be hooked  for. This is known as namespace. It is like a box where a variable name is mapped to  the object placed.  Whenever the variable is searched out, this box will be searched, to  get corresponding object.  

64. Explain the role of repr function. 

Ans.  

Python can convert any value to a string by making use of two functions repr() or  str(). The str() function returns representations of values which are human­readable,  while repr() generates representations which can be read by the interpreter. repr()  returns a machine­readable representation of values, suitable for an exec command. 

 Following code sniipets shows working of repr() & str() : 

   def fun ():  

 y = 2333.3 

  x = str ( y)  

 z = repr ( y)  

 print ” y :” ,y 

  print “str(y) :” ,x  

 print “repr(y):” ,z  

 fun () 

  ———— 

 output  

 y : 2333.3  

 str ( y ) : 2333.3 

  repr ( y ) : 2333.3000000000002

65.  What is LIST comprehensions features of Python used for? 

Ans.  

LIST comprehensions features were introduced in Python version 2.0, it creates  a new list based on existing list. It maps a list into another list by applying a function to each of the elements of the existing list. List comprehensions creates lists without using  map() , filter() or lambda form.   

 

66. Explain how to copy an object in Python.?  

Ans.  

There are two ways in which objects can be copied in python. Shallow copy &  Deep copy. Shallow copies duplicate as minute as possible whereas Deep copies  duplicate everything. If a is object to be copied then …   ­copy.copy(a) returns a shallow copy of a.  ­copy.deepcopy(a) returns a deep copy of a.  

67. Describe how to send mail from a Python script?   

Ans.  

The smtplib module defines an SMTP client session object that can be used to  send mail to any Internet machine. 

 A sample email is demonstrated below.  import smtplib 

 SERVER = smtplib.SMTP(‘smtp.server.domain’) 

 FROM = sender@mail.com 

 TO = [“user@mail.com”] # must be a list 

 SUBJECT = “Hello!” 

 TEXT = “This message was sent with Python’s smtplib.” 

 # Main message  

message = “”” 

 From: Lincoln < sender@mail.com > 

 To: CarreerRide user@mail.com  

Subject: SMTP email msg  

This is a test email. Acknowledge the email by responding. 

 “”” % (FROM, “, “.join(TO), SUBJECT, TEXT)

  server = smtplib.SMTP(SERVER) 

 server.sendmail(FROM, TO, message)  

server.quit()

68. Which of the languages does Python resemble in its class syntax?

Ans . c++.  

69. Python ­ How to create a multidimensional list? 

Ans. There are two ways in which Multidimensional list can be created: 

 By direct initializing the list as shown below to create myList below.  

>>> myList = [ [ 227 , 122 , 223 ],[ 222 , 321 , 192 ],[ 21 , 122 , 444 ]]  

 >>> print myList [ 0]  

 >>> print myList [ 1 ][ 2]  

 ____________________  

Output   [227, 122, 223]  

192   

 The second approach is to create a list of the desired length first and then fill in each  element with a newly created lists demonstrated below :  

  >>> list =[ 0 ]*3  

 >>> for i in range ( 3 ):   

>>> list [ i ]=[ 0 ]*2  

 >>> for i in range ( 3 ):  

 >>> for j in range ( 2 ):   

>>> list [ i ][ j ] = i +j  

 >>> print list 

  __________________________   

Output   [[ 0 , 1 ], [ 1 , 2 ], [ 2 , 3 ]] 

70. Explain the disadvantages of python

Ans. Disadvantages of Python are: Python isn’t the best for memory intensive tasks.  Python is interpreted language & is slow compared to C/C++ or Java.  

71. Explain how to make Forms in python. 

Ans.  As python is scripting language forms processing is done by Python. We need to  import cgi module to access form fields using FieldStorage class.  

  Every instance of class FieldStorage (for ‘form’) has the following attributes:    

form.name: The name of the field, if specified.   

form.filename: If an FTP transaction, the client­side filename.  

 form.value: The value of the field as a string.  

 form.file: file object from which data can be read.  

 form.type: The content type, if applicable.   

form.type_options: The options of the ‘content­type’ line of the HTTP request, returned  as a dictionary. 

  form.disposition: The field ‘content­disposition’; None if unspecified. 

  form.disposition_options: The options for ‘content­disposition’. 

  form.headers: All of the HTTP headers returned as a dictionary.   

 A code snippet of form handling in python:  

  import cgi   

  form = cgi . FieldStorage ()  

 if not ( form . has_key ( “name” ) and form . has_key ( “age” )): 

  print “<H1>Name & Age not Entered</H1>”  

 print “Fill the Name & Age accurately.”  

 return  

 print “<p>name:” , form [ “name” ]. value   

print “<p>Age:” , form [ “age” ]. valu

72.Explain how python is interpreted. 

Ans.  Python program runs directly from the source code. Each type Python programs  are executed code is required. Python converts source code written by the programmer  into intermediate language which is again translated it into the native language  machine language that is executed. So Python is an Interpreted language.  

73. Explain how to overload constructors (or methods) in Python.? 

Ans.  _init__ () is a first method defined in a class. when an instance of a class is  created, python calls __init__() to initialize the attribute of the object.  Following example demonstrates further:  

class Employee: 

    def __init__ ( self , name , empCode , pay ):  

 self . name = name

self . empCode = empCode   

self . pay = pay   

  e1 = Employee ( “Obama” , 99 , 30000.00)  

   e2 = Employee ( “Clinton” , 100 , 60000.00) 

  print ( “Employee Details:”)    

 print ( ” Name:” , e1 . name , “Code:” , e1 . empCode , “Pay:” , e1 . pay)   

print ( ” Name:” , e2 . name , “Code:” , e2 . empCode , “Pay:” , e2 . pay)

Output  

   Employee Details: 

  ( ‘ Name:’ , ‘Obama’ , ‘Code:’ , 99 , ‘Pay:’ , 30000.0) 

  ( ‘ Name:’ , ‘Clinton’ , ‘Code:’ , 100 , ‘Pay:’ , 60000.0) 

 

74. How do we make python scripts executable? 

Ans. Python scripts can be executed in two ways:  Suppose we want to execute script1.py  We can open the script1.py in IDE editor & run the script in the frontmost window of the  python IDE by hitting the run all button.  Second way is using command prompt by making sure PATH is set appropriately  directly type script name else type    >>>python script1.py      

75. We have the following code with unknown function f()
  for x in f ( 5 ):  
print x,
Output looks like this  
0 1 8 27 64  
Write the function f() ? 

Ans .  

Following is a possible implementation of f()  

  def f ( n ): 

  for x in range ( n ): 

  yield x ** 3  

 

76. What is Pickling and unpickling?  

Ans.  

Pickle is a standard module which serializes & de­serializes a python  object structure. pickle module accepts any python object converts it into a string  representation & dumps it into a file(by using dump() function) which can be used  later, process is called pickling. Whereas unpickling is process of retrieving  original python object from the stored string representation for use. 

77.What are some common uses of Pickling in Python? 

Ans.  (Open Ended Question, a possible answer is given below)    These are some of the use cases, there can be many other:­   

 1) saving a program’s state data to disk so that it can carry on where it left off when  restarted (persistence)  

  2) sending python data over a TCP connection in a multi­core or distributed system  (marshalling)   

 3) storing python objects in a database   

 4) converting an arbitrary python object to a string so that it can be used as a dictionary  key (e.g. for caching & memoization). 

There are some issues with the last one ­ two identical objects can be pickled and result  in different strings ­ or even the same object pickled twice can have different  representations. This is because the pickle can include reference count information.  

78. Why do list comprehensions write to the loop variable, but generators don't? 

Ans. 

This was a bug in Python 2.x and is fixed in Python 3.x. 

79. What is the length of your largest python code? Can you please describe the  project? 

Ans.     It’s a very open ended question. The answer is difficult to predict. Python beginners will  have written small codes (basic scripts). More advanced users would have used OOP in  python and their codes will range from a 200 to 800 lines of code. Advanced users will  have written larger codes upto 2000 or 3000 lines of codes.   Beyond this point, codes are generally written in groups to meet a deadline.  

80. In the above project, were you alone or were you in group of developers? If  so, how many? 

Ans.  (Open Ended Question) Depends on the personal experience of the person. A  good successful project being part of the team indicates that the person is a good team  player. 

81. What was your contribution to the above project? 

Ans. (Open ended Question). Interviewee’s answer depends on the personal  experience which could involve writing a module for the project, testing or  documentation etc.   

82. How often do you comment your code? Can you write anyone who reads your  code recognise and understand your variable names? 

Ans.  (Open Ended Question) A good programmer would do medium amount of  commenting frequently making use of python doc strings. 

83. Why does Python have a maximum recursion depth?  

Ans . Recursion requires space on the call stack, which is limited in size. Code which  used too many levels of recursion will give an error called a stack overflow. Python  stack frames are also quite big in size which further makes the issue more crucial.  

84. Can you modify the maximum depth for a recursive function in Python? If  yes how?  

Ans . Yes 

   sys . setrecursionlimit ( 1500) // Generally the length is 1000 stack frame 

85.What is tail recursion?  

Ans .  In traditional recursion, the typical model is that you perform your recursive calls  first, and then you take the return value of the recursive call and calculate the result. In  this manner, you don’t get the result of your calculation until you have returned from  every recursive call.   

 In tail recursion, you perform your calculations first, and then you execute the recursive  call, passing the results of your current step to the next recursive step. This results in  the last statement being in the form of “(return (recursive­function params))” . Basically,  the return value of any given recursive step is the same as the return value of the next  recursive call.    

The consequence of this is that once you are ready to perform your next recursive step,  you don’t need the current stack frame any more. This allows for some optimization. In  fact, with an appropriately written compiler, you should never have a stack overflow  snicker with a tail recursive call. Simply reuse the current stack frame for the next  recursive step.  

86. Does python perform tail recursion optimization?  

Ans . No it doesn’t. Python founder Guido van Rossum wrote in his blog:    

“I recently posted an entry in my Python History blog on the origins of Python’s  functional features. A side remark about not supporting tail recursion elimination (TRE)  immediately sparked several comments about what a pity it is that Python doesn’t do  this, including links to recent blog entries by others trying to “prove” that TRE can be  added to Python easily. So let me defend my position (which is that I don’t want TRE in  the language). If you want a short answer, it’s simply unpythonic”.

87. What is a metaclass in Python?  

Ans.  A metaclass is the class of a class. Like a class defines how an instance of the  class behaves, a metaclass defines how a class behaves. A class is an instance of a  metaclass.  

88. How to get class name of an instance in Python? 

Ans.   instance . __class__ . __name__ 

89. Describe how to use Sessions for Web python?  

Ans.   Sessions are the server side version of cookies. While a cookie preserves state at the  client side, sessions preserves state at server side. 

   The session state is kept in a file or in a database at the server side. Each session is  identified by a unique session id (SID). To make it possible to the client to identify  himself to the server the SID must be created by the server and sent to the client  whenever the client makes a request.  

90. Multiply all elements of a list without writing a loop.

Ans.   from operator import mul  

 reduce ( mul , range ( 1 , 10 ))

91. What is a singleton design pattern?  

Ans.   In the singleton design pattern that limits the number of instances of a class (normally to  1).   

92. Write a program to show the usage of singleton pattern in Python?  

Ans. Some code along the following lines would do.   

  Singleton & Singleton :: Handle () { 

  if ( ! psingle ) { 

psingle = new Singleton; 

  }  

 return * psingle; 

  }     

93. Can we use singleton functionality without making a singleton class in  Python?  

Ans.   A module with functions (and not a class) would serve well as a singleton. All its  variables would be bound to the module, which could not be instantiated repeatedly  anyways.  

94. Does python support database programming?  

Ans. Yes.  

95. What is MySQLdb? 

Ans. MySQLdb is an interface for connecting to a MySQL database server from Python.  It implements the Python Database API v2.0 and is built on top of the MySQL C API.  

96. How would you check if MySQLdb is installed? 

Ans. Try importing it with import MySQLdb. An error would indicate that it’s not  installed.   

97. How do you disconnect from the database?  

Ans. Use the close() method. db.close() closes the connection from the database like in  the script above

98. Does Python support enums? 

Ans. Python 3.4 does. Earlier versions of Python dont. 

99. How do you use enums in Python? 

Ans. The following code would do.    

 from enum import Enum  

 Game = Enum ( ‘Game’ , ‘hockey football rugby’) 

100. Booleans have 2 possible values. Are there types in python that have 3  possible values? 

Ans. Yes. This functionality can be achieved by enums. refer to the example in previous  enum question.