python tutorial - Python interview questions and answers for experienced - learn python - python programming




python interview questions :121

Print in terminal with colors using Python?

  • This can be achieved to Print a string that starts a color/style, then the string, then end the color/style change with '\x1b[0m':
  • print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
  • Get a table of format options for shell text with following code:
  • def print_format_table():
        """
        prints table of formatted text format options
        """
        for style in range(8):
            for fg in range(30,38):
                s1 = ''
                for bg in range(40,48):
                    format = ';'.join([str(style), str(fg), str(bg)])
                    s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
                print(s1)
            print('\n')
    
    print_format_table()
    
    click below button to copy the code. By Python tutorial team
     one

    Learn python - python tutorial - terminal - python examples - python programs

    python interview questions :122

    How to get line count cheaply in Python?

    def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
    def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
    def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
    def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
    def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
    def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
    def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
    def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))
    
    prGreen("Hello world")
    
    click below button to copy the code. By Python tutorial team

    You need to get a line count of a large file (hundreds of thousands of lines) in python.

    def file_len(fname):
        with open(fname) as f:
            for i, l in enumerate(f):
                pass
        return i + 1
    
    click below button to copy the code. By Python tutorial team

    python interview questions :123

    What's the list comprehension?

  • List comprehensions provide a concise way to create lists
  • It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
  • The expressions can be anything, meaning you can put in all kinds of objects in lists.
  • The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
  • The list comprehension always returns a result list.
  • >>> L2 = [x**3 for x in L]
    >>> L2
    [0, 1, 8, 27, 64, 125]
    
    click below button to copy the code. By Python tutorial team

    Interveiw Questions:124

    Which one has higher precedence in Python? - NOT, AND , OR

    >>> True or False and False
    
    click below button to copy the code. By Python tutorial team
    • AND is higher precedence than OR, AND will be evaluated first, "True" will be printed out.
    • Then, how about this one?
    >>> not True or False or not False and True
    True
    
    click below button to copy the code. By Python tutorial team
    • NOT has first precedence, then AND, then OR.
     two

    Learn python - python tutorial - precedence - python examples - python programs

    One line, probably pretty fast:

    num_lines = sum(1 for line in open('myfile.txt'))
    
    click below button to copy the code. By Python tutorial team

    python interview questions :125

    What is the use of enumerate() in Python?

    • Using enumerate() function you can iterate through the sequence and retrieve the index position and its corresponding value at the same time.
    >>> for i,v in enumerate([‘Python’,’Java’,’C++’]):
    print(i,v)
    
    click below button to copy the code. By Python tutorial team
    0 Python
    1 Java
    2 C++

    python interview questions :126

    How do you perform pattern matching in Python? Explain

    • Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc.
    • The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.

    python interview questions :127

    What is a Class? How do you create it in Python?

    • A class is a blue print/ template of code /collection of objects that has same set of attributes and behaviour.
    • To create a class use the keyword class followed by class name beginning with an uppercase letter. For example, a person belongs to class called Person class and can have the attributes (say first-name and last-name) and behaviours / methods (say showFullName()). A Person class can be defined as:
    class Person():
    #method
    def inputName(self,fname,lname): self.fname=fname self.lastname=lastname
    #method
    def showFullName() (self):
    print(self.fname+" "+self.lname)person1 = Person() #object instantiation person1.inputName("Ratan","Tata") #calling a method inputName person1. showFullName() #calling a method showFullName()
    
    click below button to copy the code. By Python tutorial team

    Note: whenever you define a method inside a class, the first argument to the method must be self (where self - is a pointer to the class instance). self must be passed as an argument to the method, though the method does not take any arguments.

    python interview questions :128

    What are Exception Handling? How do you achieve it in Python?

    • Exception Handling prevents the codes and scripts from breaking on receipt of an error at run -time might be at the time doing I/O, due to syntax errors, data types doesn’t match. Generally it can be used for handling user inputs.
    • The keywords that are used to handle exceptions in Python are:
    • try - it will try to execute the code that belongs to it. May be it used anywhere that keyboard input is required.
    • except - catches all errors or can catch a specific error.
    try block.x = 10 + ‘Python’ #TypeError: unsupported operand type(s) …. try:
    x = 10 + ‘Python’
    except:
    print(“incompatible operand types to perform sum”)
    raise - force an error to occur
    o raise TypeError(“dissimilar data types”)
    finally - it is an optional clause and in this block cleanup code is written here following “try” and “except”.
    
    click below button to copy the code. By Python tutorial team

    python interview questions :129

    What are Accessors, mutators, @property?

    • Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX().
    • Python has an @property “decorator” that allows you to ad getters and setters in order to access the attribute of the class.

    python interview questions :130

    Differentiate between .py and .pyc files?

    • Both .py and .pyc files holds the byte code. “.pyc” is a compiled version of Python file.
    • This file is automatically generated by Python to improve performance.

    Related Searches to Python interview questions and answers for experienced