Python Interview Questions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Single post underscore_

Used for naming variables as Python keywords while avoiding clashes.

Relational Operators

Used to compare operands, they include =,<,>,<=,>=,<>

Comparison Operators

Used to compare values, returning either True or False. >, <, ==, !=, >=, <=

Mutable object

Value can be modified in place after object creation. Examples: list, dict, set, byte array, user-defined class

Truthy and Falsy

Values that evaluate to boolean true or false but that aren't actually boolean values of true or false. Truthy values: non-empty sequences or collections (sets, dictionaries, lists, tuples, strings), True, numeric values which are not zero. Falsy: zero of any numeric type, integer 0, float 0.0, complex 0j, constants None, False.

Ternary Operator

an operator that takes three arguments. [on_true] if [expression] else [on_false], EXAMPLE: condition = True x = 4 if condition else 5 >>> x 4

garbage collection

automatic reclamation of memory occupied by objects that are no longer referenced

Check if string 'string' is contained within larger_string 'This is my sentence, look at it go."

if 'string' in larger_string: # do something

Check if 9 is contained within a list called "nums"

if 9 in nums: # some code here

Membership operator

in, not in

Expression to accept user input

input()

Dunder method

"Double underscore" or "magic methods"

Magic Method

"Dunder Method." A special function which is invoked internally by the class on a certain action. Denoted by a set of double underscores before and after the function name. Example: __init__, __str__, __repr__

Insert string value using format()

"{}, a website for geeks.".format("GeeksforGeeks")

str = 'anaconda' str[0:2]

'an' Remember that Python is upper-bound exclusive with regards to ranges and list slicing.

'anaconda'[:3]

'ana'

'anaconda'[3:]

'conda'

Logical operators in python

(1) AND, (2) OR, (3) NOT

Non-Primitive Types in Python

(1) Array, (2) List, (3) Tuple, (4) Dictionary, (5) Set, (6) File

List

(1) Non-primitive data type (2) Mutable (3) Ordered, indexable container of arbitrary length (4) Can hold a heterogenous collection of items, including integers, strings, and objects (5) The equivalent of an array in many other languages.

Built-in function

(1) Reliably included with different implementations of a language (2) can be utilized immediately (3) don't require add-on packages.

Primitive Data Types in Python

(1) integer, (2) float, (3) string, (4) boolean

Python data types

(1) numbers, including int and float (2) string, (3) boolean, (4) list, (5) tuple, (6) set, (7) dictionary

5 - 2 - 1

(5 - 2) - 1 = 2

a + b + c

(a + b) + c

a < b < c

(a < b) and (b < c). If a < b evaluates to false

Numbers

A basic data type Immutable Three types: float, int, and complex

String

A basic data type Immutable An ordered sequence of characters

Docstring

A special comment located at the beginning of a function or program which is intended for the end-user; no implementation details; may be turned into actual documentation and may be viewed when function is running with help(function_name). Comments denote the function of sections or lines to developers, and may include #TODOs, workarounds, or complex items. Comments are non-executable statements and are thus ignored; cannot be viewed while program is running.

*args, **kwargs

A special syntax in function definitions used to pass a variable number of arguments to a function args = non-keyworded, kwargs = keyworded can use any word with * and **.

*args

A special way of denoting a non-keyworded, variable-length list of arguments. def myfun(*args): total = 0 for i in args: total += i return total

PEP 8

A style guide which dictates formatting for maximum readability and long-term maintainability. "Python Enhancement Proposal"

Operator

A symbol that performs an operation on operands. In python, these include Basic (arithmetic, relational, logical, bitwise, assignment, special)

str[::-1]

All items in the array, reversed The first colon omits the optional start operator, so the start is assumed to be 0. The second : omits the stop operator, so the stop point is set to the end of the sequence. The -1 sets the step size to one in the backwards direction.

PYTHONPATH

An environment variable which sets additional directories in which Python will search for modules and packages. An easy way to make modules available for import.

Iterator

An object containing data and methods to iterate through a collection of data

Positional argument

An unnamed argument that is assigned to a parameter based on its position in the function call

Logical Operators

And, or, or not. Return True or False. Example: True and True returns True

//

Floor division resulting in a whole number adjusted to the left on the number line. While 3/2 = 1.5, 3//2 = 1. While -3/2 = -1.5, -3//2 = -2.

Wildcard import

From from [module] import *. Should be avoided due to the possibility of namespace pollution. For example, from foo import bar from spam import * If there is a spam.bar, you have replaced the foo.bar in the line above.

**kwargs

A dictionary of keyword arguments. def fun2(**kwargs): dic = {} for key, val in kwargs.items(): dic[key] = val return dic

Anaconda

A distribution containing cPython, scientific computing packages, and Conda (package and environment manager).

Decorator

A function which accepts another function as input and extends its behavior, without explicitly modifying it - a wrapper.

Literal

A notation for representing a fixed value in source code.

Python interpreter

A program that accepts and then executes Python source code.

Set vs. Tuple

A set is unordered, un-indexable, and cannot contain duplicates, while a tuple is ordered, may be indexed, and duplicate elements are OK. Sets are useful for set mathematical operations like unions and intersections. Sets are mutable while tuples are immutable.

Function keywords (named parameters)

Arguments which can be specified by name as they are passed into a function. myFunction(a = 100, b=10)

Assignment operator

Assign values to variables. =, +=, -=, *=, /=, etc

Mangling

Avoid clashes between names defined by superclasses and those defined by subclasses. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

Tuple (A) vs. List (B)

Both are heterogenous, indexable, sliceable collections of objects A is immutable, while B is mutable.

(A) Set (B) List

Both are mutable data types in Python which contain heterogenous data. (A) is unordered and un-indexable while (B) is ordered and indexable. (A) has only unique elements; (B) can contain duplicates.

Symbolic Computation

Computation utilizing symbolic expressions, which is exact and more precise than the other type, which can only use real numbers.

print()

Compute the "informal" or nicely printable string representation of an object; always returns a string object. Invokes __str__.

__repr__

Computes the "formal" or "official" representation of an object. Used mainly for debugging and development. Focus: unambiguity

__str__

Computes the informal string representation of an object. Focused on creating readable output for end user. Invoked by print() or str()

__init__

Constructor method Initializes 'default' attributes and methods automatically when an object is instantiated from a class.

Boolean

Immutable A single value of either TRUE or FALSE One of the four primitive data types in Python

How is 'print' treated differently in Python 2 vs. 3?

In Python 2, print is a special statement, while in Python 3, it is treated as a function, requiring parentheses.

Maximum value for an integer in Python

In Python 3, the only limit to the size of an integer is its available memory. Conversely, there was an explicit limit defined in Python 2.

_Single underscore prefix

Indicates "weak internal use - hints method or attribute is intended to be private. Won't be imported by from module import *. The method or attribute can still be accessed normally, however, such as with print(obj._attribute)

Numeric (type)

Int, float, complex. Explicit long type no longer exists

Numerical Computation

Involves only real floating point numbers. Less precise than the other type, which emphasizes exact computation with symbolic expressions.

identity operator

Is, is not Used to determine whether data is of a certain type ("x is int"). Also, check if two values are located in the same location in memory. Is returns True if operands are identical, and refer to the same object. Is not returns True if operands are not identical. Example. x = 5, y = 5, x==y returns True, x is y returns True. However, a = [1,2,3] and b = [1,2,3]. a == b returns True but a is b returns False since lists are allocated separate areas in memory

What is a .pyc file?

Created by the Python interpreter when a .py file is imported, it contains the compiled bytecode of that file or module. Speeds up subsequent imports since the compiling step only needs to be performed once.

Singleton

Creational design pattern which allows for the creation of only one instance of data. Controls concurrent access to a shared resource and good for read-only global states such as time, app path, and user language.

Environment Variables

Define the way processes behave on a computer.

None

Defines a null value, or no value at all. Falsy. A data type of the class NoneType. Not the same as 0, False, or an empty string A singleton; all variables assigned None point to same object

Non-Primitive Data Type

Derived from the primitive data types, these offer increased functionality.​​

Mapping (type)

Dictionaries are what general class of data type

Null

Doesn't exist in Python. See 'None.'

Short circuit evaluation

Evaluation of a boolean expression from left to right such that, under certain conditions, the righthand portion can be ignored. An or statement stops as soon as if encounters the first True case. An and statement stops as soon as if encounters the first False case

Lazy Evaluation

Evaluation strategy which delays the evaluation of an expression until its value is needed.

Float (Floating Point)

Express real and rational (able to be written as a fraction) numbers Usually written with a decimal point Can be negative One of four primitive data types in Python

Is Python compiled or interpreted?

It is not the language that is interpreted or compiled, but rather the implementation. In the CPython implementation, the compiler compiles Python source code to bytecode (a .pyc file) behind the scenes; the developer may hardly be aware of it. The bytecode is then executed by the appropriate virtual machine. Compiled because: it compiles source code to bytecode. Interpreted because: the Python interactive prompt executes code immediately, without any obvious explicit step, unlike in Java.

Where did Python get its name?

Its creator, Guido van Rossum, was a fan of Monty Python's Flying Circus.

&&

Logical AND; in Python, we use 'and.'

||

Logical OR. In Python, we use 'or'.

Dictionary

Non-primitive data type Mutable An unordered collection of data values in the format key:value, where keys must be unique and immutable. Declared using curly brackets {}

Set

Non-primitive data type Mutable Items must be unique - no duplicates. Unordered; can't be indexed

Tuple

Non-primitive data type Immutable Sequential collection of items Defined with ()

\r

Notates a raw string, in which escape sequences are not parsed. r'\n' returns two characters, \n, rather than a new line.

Integer

Numeric data Whole numbers from negative to infinity (includes zero) No decimal point One of the four primitive data types in Python. Unlimited size in Python 3

Conda

Open-source package and environment management system; installs, runs and updates packages and their dependencies; easily creates, saves, loads and switches between environments; was created for Python, but can package and distribute software for any language.

Python 2 vs. Python 3

Python 3 is the first intentionally non-backwards-compatible release. It includes new features: (1) Print() function replaces special print statement (2) Integer division is no longer assumed. 3/2 yields 1.5 in Python 3, not 1. (3) Implicit string type is Unicode in Python 3, rather than the default ASCII in Python 2. More flexible Unicode can store foreign characters and emojis and does not need to be explicitly called. (4) New bytes object stores machine-readable data. (5) Range() replaces xrange() - behaves in a similar manner, returning a generator object, which is faster and uses less memory.

list comprehension

Python rules for creating lists intelligently s = [x for x in range(1:51) if x%2 == 0] [2, 4, 6, 8, 10, 12, 14, 16, etc]

String literal

Represents a string value within source code. Ie, a string which appears in code.

Operator precedence

Rules governing the order in which operators are evaluated within an expression or statement. In Python, evaluate left to right.

Set (type)

Set, frozen set

IDE (Integrated Development Environment)

Software suite with basic tools for writing and testing software (auto-completion, syntax highlighting, debugging tools, etc.) Examples: PyCharm, IDLE, Spyder, Eclipse

Sequence (type)

String, list, tuple, bytes, byte array

Operator overloading

The means by which Python evaluates the various operators (+, *, /). The name refers to the fact that an operator can have many different "meanings" and the correct meaning depends on the type of the objects involved. Python evaluates the class or object type on the left. If it is a built-in type, it uses the built-in meaning for that type. Otherwise, it looks for the associated special method (beginning and ending with double underscores) in the class definition.

Primitive Data Type

The simplest forms of representing and manipulating data. Python has four.

Arithmetic Operators

The symbols +, -, *, **, /, //, and % used to perform mathematical operations on operands.

Switch case statement

This does not exist in Python.

Compile

To convert a program in a high-level language to machine code (CPU instructions).


संबंधित स्टडी सेट्स

ECON Lowdown Credit Bureaus: The Record Keepers

View Set

BIO EXAM 2 - PRE/POST lecture questions

View Set

Hazardous Materials Preparer Course (Refresher)

View Set

Macroeconomics chapter 9 (10/21/18)

View Set