Python Concepts

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

Decorators

Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more "Pythonic". By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it Essentially, decorators work as wrappers, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it.

Dictionary

Dictionary is a collection of many values. items in dictionaries are unordered. Because dictionaries are not ordered, they can't be sliced like lists.

IN

Evaluates to true if it finds a variable in the specified sequence and false otherwise. If it's a string (as in your example), then in checks for substrings. >>> "in" in "indigo" True >>> "in" in "violet True If it's a different kind of iterable (list, tuple, dictionary...), then in checks for membership. In a dictionary, membership is seen as "being one of the keys":

For loop vs List Comprehension

Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension. When working with nested loops in list comprehensions remember that the for clauses remain in the same order as in our original for loops. Longer list comprehensions can be written on multiple lines

Generator

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly: Then, your code will be run each time the for uses the generator. 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. ex: def gencubes(n): for num in range(n): yield num**3 Yield:yield is a keyword that is used like return, except the function will return a generator. To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-) Likewise there are generator expressions, which provide a means to succinctly describe certain common types of generators: Ex: g = (n for n in range(3, 5)) >>> next(g)

lambda

Lambda is a tool for building functions ( and procedures), or more precisely, for building function objects. That means that Python has two tools for building functions: def and lambda. User when: Situations in which (a) the function is fairly simple, and (b) it is going to be used only once.

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. Ex: x = [i for i in range(10)] Ex2: [x for x in range(1,50) if x%3 == 0]

logging

Logging on Screen: import logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') Logging to a file: import logging logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') Levels: 1) DEBUG logging.debug() The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems. ex: logging.debug('Some debugging details.') 2) INFO logging.info() Used to record information on general events in your program or confirm that things are working at their point in the program. ex: logging.info('The logging module is working.') 3) WARNING logging.warning() Used to indicate a potential problem that doesn't prevent the program from working but might do so in the future. ex: logging.warning('An error message is about to be logged.') 4) ERROR logging.error() Used to record an error that caused the program to fail to do something. ex:logging.error('An error has occurred.') 5)CRITICAL logging.critical() The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely. ex: logging.critical('The program is unable to recover!') Disable Logging: logging.disable(logging.CRITICAL). All errors below this level will be ignored.

Modules

Modules in Python are simply Python files with the .py extension, which implement a set of definitions, functions and statements. Modules are imported from other modules using the import command import "module": Ex Import math ( in built module) or directly access the function in the module ex: from math import sqrt. Use dir(math) to show all function in that module Download Modules: pip install "module name" Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

Data Structures

Primitive: Integers, Float, Strings, Boolean Non-Primitive: Arrays, Lists,Tuples,Dictionary,Sets, Files

Slicing

When you want to extract part of a string, or some part of a list, you use a slice. Lists have a default bit of functionality when slicing. If there is no value before the first colon, it means to start at the beginning index of the list. If there isn't a value after the first colon, it means to go all the way to the end of the list a[::-1] ---> Reverses the string a. Think of a[-x] as a[len(a)-x]

Strings

While you can use the \n escape character to put a newline into a string, it is often easier to use multiline strings. A multiline string in Python begins and ends with either three single quotes or three double quotes.

For loop

for num in range(10,20):

Files - 1

import os - module for file handling os.path.sep - os specific path seperator 1. os.listdir(path) 2. os.path.exists(path) 3. os.path.isfile(path) 4. os.path.isdir(path) 5. File operrations: All these return a file object Open(filepath including file name) read(filepath including file name) write((filepath including file name) close(filepath including file name)

regex

import re Create a Regex object with the re.compile() function. (Remember to use a raw string - r'.) Ex: ph = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') use regex object's (ph here) method to carry out other operations such as find / count / replace / match etc.

Map, reduce, filter

map() is a function that takes in two arguments: a function (or lamba) and a sequence iterable. In the form: map(function, sequence) Ex: original items = [1, 2, 3, 4, 5] squared = [] for i in items: squared.append(i**2) map: items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, items)) The function reduce(function, sequence) continually applies the function to the sequence. It then returns a single value. Ex: product = 1 list = [1, 2, 3, 4] for num in list: product = product * num from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) The function filter(function, list) offers a convenient way to filter out all the elements of an iterable, for which the function returns True. ex: number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) print(less_than_zero)

shelve

save variables in your Python programs to binary shelf files using the shelve module. Your program can restore data to variables from the hard drive. The shelve module will let you add Save and Open features to your program.

Exception Handling

try: Code here is exceuted except: , except IOError : If any error occurs in the try block it's caught here else: if there is no exception code here execute finally : code here executes regardless

Zip, enumerate, all(), any()

zip takes n number of iterables and returns list of tuples In Python3, zip methods returns a zip object instead of a list.We convert the zip object to a list by list(zipped). After this we can use all the methods of list. Enumerate allows you to keep a count as you iterate through an object. It does this by returning a tuple in the form (count,element). Ex: for count,it in enumerate(l1): print(count) print(it) all() and any() are built-in functions in Python that allow us to conveniently check for boolean matching in an iterable. all() will return True if all elements in an iterable are True.


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

Unit 8 can/ can´t I Love English 1

View Set

Histology Chapter 6 Connective Tissue

View Set

EXIT HESI -PN Exam A PRACTICE QUESTION

View Set

PSY 108 6c) The Nonvisual Senses

View Set

Spanish 1 VHL Central Combined Lesson 1 Hola, ¿qué tal?

View Set