Test your skills through the online practice test: Python Quiz Online Practice Test

Related differences

Python vs JavaPython 2 vs Python 3

Ques 26. How to create a class in Python?

In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:

Example:

class ClassName:

    code statement

Is it helpful? Add Comment View Comments
 

Ques 27. What is the syntax for creating an instance of a class in Python?

The syntax for creating an instance of a class is as follows:

<object-name> = <class-name>(<arguments>)

Is it helpful? Add Comment View Comments
 

Ques 28. Define what is “Method” in Python programming.

The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of object can have methods.

Is it helpful? Add Comment View Comments
 

Ques 29. Why can't I use an assignment in an expression?

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
  ...do something with line...
}

 
where in Python you're forced to write this:

while True:
  line = f.readline() if not line:
  break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

 
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

 
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

 
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

Is it helpful? Add Comment View Comments
 

Ques 30. How do you set a global variable in a function in Python?

x = 1 # make a global
def f():
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.


The solution is to insert an explicit global declaration at the start of the function:

 
def f():
  global x
  print x # try to print the global
  for j in range(100):
    if q>3:
      x=4

 
In this case, all references to x are interpreted as references to the x from the module namespace.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users: