Python

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

What is a docstring (pair of triple quotes) used for?

1. Comments 2. Actually printing out multi-line strings

What type will pets = ["Cash", "Carter"] evaluate to?

<class 'list'>

What eight kinds of functions can use a key function?

min() max() list.sort() sorted() heapq.merge() heapq.nsmallest() heapq.nlargest() itertools.groupby()

What names does local (function) scope contain?

names that you define inside the function

What does enclosing (or nonlocal) scope exist for?

nested functions If the local scope is an inner or nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function. The names in the enclosing scope are visible from the code of the inner and enclosing functions.

What keyword do you use when you do not want to add any other properties or methods to the class?

pass

What is the name of Python's built-in debugger?

pdb

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

send the parent class as a parameter when creating the child class:

What do you need to do if you want to work with arrays, specifially, in Python?

to work with arrays in Python you will have to import a library, like the NumPy library.

Does Python have a built-in Array type?

No

What's a docstring?

A multi-line string

What does the strftime (/stir-eff-time/) method do?

Allows you to print a string formatted using a series of formatting directives

How is .remove() different from other file handling methods? I

It requires the OS module to be imported

What are the six built-in modules in Python?

OS Module. Sys Module. Math Module. Statistics Module. Collections Module. Random Module.

What is closure in Python?

The idea that an inner function always has access to the variables and parameters of its outer function, even after the outer function has returned.

Do Lists in Python core and Arrays in NumPy share the same built-in methods?

Yes

What in JavaScript are Python lambdas similar to?

Arrow functions

When should you use lambdas in Python?

1. When an anonymous function is required for a short period of time 2. You want to provide encapsulation

What is a key function?

A callable that returns a value used for sorting or ordering.

What is PyCharm?

A dedicated Python Integrated Development Environment (IDE) providing a wide range of essential tools for Python developers, tightly integrated to create a convenient environment for productive Python, web, and data science development. It's a JetBrains product and there is a limited free version, as there is with IntelliJ with Java.

What is the LEBG rule?

A kind of name lookup procedure that determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope. If the name exists, then you'll get the first occurrence of it. Otherwise, you'll get an error.

What is the difference between a package and a module?

A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts.

What is pip?

A package manager for Python. That means it's a tool that allows you to install and manage additional libraries and dependencies that are not distributed as part of the standard library.

What scope is the scope of a code block, or body, of any Python function?

Local (or function) scope These names will only be visible from the code of the function. It's created at function call, not at function definition, so you'll have as many different local scopes as function calls. This is true even if you call the same function multiple times, or recursively Each call will result in a new local scope being created

What case are Python class names in?

Pascal Case

What are all the built-in errors in Python?

1 Exception Base class for all exceptions 2 StopIteration Raised when the next() method of an iterator does not point to any object. 3 SystemExit Raised by the sys.exit() function. 4 StandardError Base class for all built-in exceptions except StopIteration and SystemExit. 5 ArithmeticError Base class for all errors that occur for numeric calculation. 6 OverflowError Raised when a calculation exceeds maximum limit for a numeric type. 7 FloatingPointError Raised when a floating point calculation fails. 8 ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. 9 AssertionError Raised in case of failure of the Assert statement. 10 AttributeError Raised in case of failure of attribute reference or assignment. 11 EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 12 ImportError Raised when an import statement fails. 13 KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. 14 LookupError Base class for all lookup errors. 15 IndexError Raised when an index is not found in a sequence. 16 KeyError Raised when the specified key is not found in the dictionary. 17 NameError Raised when an identifier is not found in the local or global namespace. 18 UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. 19 EnvironmentError Base class for all exceptions that occur outside the Python environment. 20 IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 21 OSError Raised for operating system-related errors. 22 SyntaxError Raised when there is an error in Python syntax. 23 IndentationError Raised when indentation is not specified properly. 24 SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. 25 SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. 26 TypeError Raised when an operation or function is attempted that is invalid for the specified data type. 27 ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. 28 RuntimeError Raised when a generated error does not fall into any category. 29 NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

What are the three most common ways a single underscore by itself is used in Python?

1. In the interpreter: The _ name points to the result of the last executed statement in an interactive interpreter session. This was first done by the standard CPython interpreter, and others have followed too. >>> _ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name '_' is not defined >>> 42 >>> _ 42 >>> 'alright!' if _ else ':(' 'alright!' >>> _ 'alright!' 2. As a name: This is somewhat related to the previous point. _ is used as a throw-away name. This will allow the next person reading your code to know that, by convention, a certain name is assigned but not intended to be used. For instance, you may not be interested in the actual value of a loop counter: n = 42 for _ in range(n): do_something() 3. i18n: One may also see _ being used as a function. In that case, it is often the name used for the function that does internationalisation and localisation string translation lookups. This seems to have originated from and follow the corresponding C convention.For instance, as seen in the Django documentation for translation, you may have: from django.utils.translation import ugettext as _ from django.http import HttpResponse def my_view(request): output = _("Welcome to my site.") return HttpResponse(output) Note: The second and third purposes can conflict, so one should avoid using _ as a throw-away name in any code block that also uses it for i18n lookup and translation.

What are naive and aware datetime objects?

A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An aware datetime object contains the time zone information embedded in it.

What is built-in scope?

A special Python scope that's created or loaded whenever you run a script or open an interactive session. This scope contains names such as keywords, functions, exceptions, and other attributes that are built into Python. Names in this Python scope are also available from everywhere in your code. It's automatically loaded by Python when you run a program or script.

What does the strptime (/stir-epp-time/) method do?

Allows you to create a datetime object from a string Since the string can be formatted in any way, it's necessary to tell datetime what format to expect. Using the same set of formatting directives, we can pass in a string and the expected format to create a datetime object.

What is a single underscore before a name used for?

For encapsulation: To specify that the name is to be treated as "private" by a programmer. It's kind of* a convention so that the next person (or yourself) using your code knows that a name starting with _ is for internal use. As the Python documentation notes: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

What is a namespace in Python?

In Python, the concept of scope is closely related to the concept of the namespace. As you've learned so far, a Python scope determines where in your program a name is visible. Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces. These are the concrete mechanisms that Python uses to store names. They're stored in a special attribute called .__dict__. Names at the top level of a module are stored in the module's namespace. In other words, they're stored in the module's .__dict__ attribute. Take a look at the following code: >>>>>> import sys >>> sys.__dict__.keys() dict_keys(['__name__', '__doc__', '__package__',..., 'argv', 'ps1', 'ps2']) After you import sys, you can use .keys() to inspect the keys of sys.__dict__. This returns a list with all the names defined at the top level of the module. In this case, you can say that .__dict__ holds the namespace of sys and is a concrete representation of the module scope. Note: The output of some of the examples in this tutorial has been abbreviated (...) to save space. The output may vary based on your platform, Python version, or even on how long you've been using your current Python interactive session. As a further example, suppose that you need to use the name ps1, which is defined in sys. If you know how .__dict__ and namespaces work in Python, then you can reference ps1 in at least two different ways: Using the dot notation on the module's name in the form module.name Using a subscription operation on .__dict__ in the form module.__dict__['name'] Take a look at the following code: >>>>>> sys.ps1 '>>> ' >>> sys.__dict__['ps1'] '>>> ' Once you've imported sys you can access ps1 using the dot notation on sys. You can also access ps1 using a dictionary key lookup with the key 'ps1'. Both actions return the same result, '>>> '. Note: ps1 is a string specifying the primary prompt of the Python interpreter. ps1 is only defined if the interpreter is in interactive mode and its initial value is '>>> '. Whenever you use a name, such as a variable or a function name, Python searches through different scope levels (or namespaces) to determine whether the name exists or not. If the name exists, then you'll always get the first occurrence of it. Otherwise, you'll get an error.

Why is the use of a single underscore before a variable name more than just a convention?

It actually does mean something to the interpreter: if you write from <module/package> import *, none of the names that start with an _ will be imported unless the module's/package's __all__ list explicitly contains them. See "Importing * in Python" for more on this.

What is a double underscore(__) in front of a method name used for?

It has a specific meaning to the interpreter: Python mangles these names and it is used to avoid name clashes with names defined by subclasses. As the Python documentation notes, any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. Take the following example: >>> class A(object): ... def _internal_use(self): ... pass ... def __method_name(self): ... pass ... >>> dir(A()) ['_A__method_name', ..., '_internal_use'] As expected, _internal_use doesn't change but __method_name is mangled to _ClassName__method_name. Now, if you create a subclass of A, say B (argh, bad, bad names!) then you can't easily override A's __method_name: >>> class B(A): ... def __method_name(self): ... pass ... >>> dir(B()) ['_A__method_name', '_B__method_name', ..., '_internal_use'] The intended behaviour here is almost equivalent to final methods in Java and normal (non-virtual) methods in C++.

Do the outer functions in closures in JavaScript also have a specific kind of scope?

No

What does a null return value return in Python?

None

At what points do variable names, function and class names, and module names come into existence in Python?

Since Python is a dynamically-typed language, variables in Python come into existence when you first assign them a value. On the other hand, functions and classes are available after you define them using def or class, respectively. Finally, modules exist after you import them.

What are the options for the Python debugger?

Startup and Help python-mpdb.py[args] begin the debugger help[command] view a list of commands, or view help for a specific command within a python file: importpdb ... pdb.set_trace() begin the debugger at this line when the file is run normally Navigating Code (within the Pdb interpreter) l(ist) list 11 lines surrounding the current line w(here) display the file and line number of the current line n(ext) execute the current line s(tep) step into functions called at the current line Controlling Execution b[#] create a breakpoint at line [#] b list breakpoints and their indices c(ontinue) execute until a breakpoint is encountered clear[#] clear breakpoint of index [#] Changing Variables / Interacting with Code p print value of the variable ! execute the expression NOTE: this acts just like a python interpreter run[args] restart the debugger with sys.argv arguments [args] q(uit) exit the debugger

What is scope?

That a variable is only available from inside the region it is created.

What is DateTime.tzinfo()?

The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects. It finds its applications in situations such as the conversion of local time to UTC or to account for daylight saving time.

What is CPython?

The reference implementation of the Python programming language. Written in C and Python, CPython is the default and most widely used implementation of the language. CPython can be defined as both an interpreter and a compiler as it compiles Python code into bytecode before interpreting it.

What is global (or module) scope?

The top-most scope in a Python program, script, or module. This Python scope contains all of the names that you define at the top level of a program or a module. Names in this Python scope are visible from everywhere in your code.

What is a double underscore before and after a name (e.g. __init__) used for?

These are special method names used by Python. As far as one's concerned, this is just a convention, a way for the Python system to use names that won't conflict with user-defined names. You then typically override these methods and define the desired behavior for when Python calls them. For example, you often override the __init__ method when writing a class. There is nothing to stop you from writing your own special-method-looking name (but, please don't)

Can CPython be defined as both an interpreter and a compiler?

Yes, as CyPython compiles Python code into bytecode before interpreting it.

What is the dir() function in the Python console used for?

You can use dir() without arguments to get the list of names in the current Python scope. If you call dir() with an argument, then the function attempts to return a list of valid attributes for that object:

How do you provide the debugger with features from IPython?

extend pdb with ipdb


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

hematology and cancer practice questions

View Set

NTR 213 Chapter 14: Feeding the World

View Set

Chapter 6: Understand Consumers and Business Markets

View Set

Topic 2 - volume of distribution

View Set

Astronomy Chapter 4 and 5 Study Guide

View Set

Chapter 1: Introduction to Legal Principles and Authorities

View Set