n : Execute next line
c : complete execution
l : list lines before and after the current line
s : step into function call
b : show list of all breakpoints
cl : clear all break points
assert
:: Assert statements are a convenient way to insert debugging assertions into a program, tests the condition and continue if true and halt the program if false.
Example
>>> def average(numbers):
... assert len(numbers) !=0,"Error Description"
... return sum(numbers)/len(numbers)
...
>>> N1=[1,2,3]
>>> print(average(N1))
2
>>> N2=[]
>>> print(average(N2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in average
AssertionError: Error Description
try:
␣␣␣␣# code with possible runtime error except[type [as value]]:
␣␣␣␣# code when there is error
[else:
␣␣␣␣# code when there is NO error ]
␣␣␣␣# or just 'pass' statement if nothing to execute
[finally:
␣␣␣␣# code to run always ]
Example 1 - read 2 values perform int division
>>> a,b = input().split()
1 0
>>> try:
... print(int(a) // int(b))
... except ValueError as error:
... print("Error code:",error)
... except ZeroDivisionError as error:
... print("Error code:",error)
...
Error code: integer division or modulo by zero
>>> a,b = input().split()
2 $
...
Error code: invalid literal for int() with base 10: '$'
foridentifier in list :
␣␣␣␣# list processing code
␣␣␣␣[if somecondition1 ␣␣␣␣␣␣␣␣break # exit the loop now]
␣␣␣␣[if somecondition2 ␣␣␣␣␣␣␣␣continue # jump to next cycle in the loop]
␣␣␣␣# more processing code
[else:
␣␣␣␣# code to run when loop ends
␣␣␣␣# without a break
␣␣␣␣]
whilecondition
␣␣␣␣# repeat code if condition is true
␣␣␣␣[if somecondition1 ␣␣␣␣␣␣␣␣break # exit the loop now]
␣␣␣␣[if somecondition2 ␣␣␣␣␣␣␣␣continue # jump to next cycle in the loop]
␣␣␣␣# more processing code
[else:
␣␣␣␣# code when condition is false
␣␣␣␣# and terminate ]
Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True
any()
any(iterable)
Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
ascii()
ascii(obj)
Return an ASCII-only representation of an object. As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.
bin()
bin(number)
Return the binary representation of an integer
bool()
bool(int)
Returns True when the argument x is true, False otherwise.
breakpoint()
breakpoint(*args, **kws)
Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept whatever arguments are passed. By default, this drops you into the pdb debugger.
Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
The source code may represent a Python module, statement or expression. The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if true, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or false these statements do influence the compilation, in addition to any features explicitly specified
complex()
complex(real=0, imag=0)
Create a complex number from a real part and an optional imaginary part
delattr()
delattr(obj, name)
Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y''
Create new empty dictionary.
Create new dictionary initialized from a mapping object's (key, value) pairs
Create new dictionary initialized by for k,v in iterable d[k] = v
Create new dictionary initialized with the name=value pairs in the keyword argument list.
dir()
dir([object])
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it
divmod()
divmod(x, y)
Return the tuple (x//y, x%y).
enumerate()
enumerate(iterable, start=0)
The enumerate object yields pairs containing a count (from start, which
| defaults to zero) and a value yielded by the iterable argument.
>>> L=[2,4,6,8]
>>> for c in enumerate(L,2):
... print(c)
...
(2, 2)
(3, 4)
(4, 6)
(5, 8)
>>> for c in enumerate(L):
... print(c)
...
(0, 2)
(1, 4)
(2, 6)
(3, 8)
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it
example
>>> x=1>>> eval('x+1')2
exec()
exec(source, globals=None, locals=None)
Execute the given source in the context of globals and locals.
The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it
filter()
filter(function or None)
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true
float()
float(x=0
Convert a string or number to a floating point number
format()
format(value, format_spec=''
Return value.__format__(format_spec)
frozenset()
frozenset()
frozenset(iterable)
Build an immutable unordered collection of unique elements
getattr()
getattr(object, name[, default])
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case
globals()
globals()
Return the dictionary containing the current scope's global variables
hasattr()
hasattr(obj, name)
Return whether the object has an attribute with the given name
hash()
hash(obj)
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true
hex()
hex(number)
Return the hexadecimal representation of an integer
id()
id(obj
Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects
input()
input(prompt=None)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
int()
int([x])
int(x, base=10)
Convert a number or string to an integer.
If x is not a number or if base is given, then x must be a string
Return whether an object is an instance of a class or of a subclass thereof
issubclass()
issubclass(cls, class_or_tuple)
Return whether 'cls' is a derived from another class or is the same class
iter()
iter(iterable)
iter(callable, sentinel)
Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel
len()
len(obj)
Return the number of items in a container
list()
list(iterable=())
Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified
locals()
locals()
Return a dictionary containing the current scope's local variables
map()
map(func, *iterables)
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument
memoryview()
memoryview(object)
Create a new memoryview object which references the given object
>>> randomByteArray = bytearray('ABC', 'utf-8')
>>> mv=memoryview(randomByteArray)
>>> for m in mv:
... print(m)
...
65
66
67
With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument
next()
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIterationith two or more arguments, return the smallest argument
object()
object()
Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments
Prints the values to a stream, or to sys.stdout by default.
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
fget : function to be used for getting an attribute value
fset : function to be used for setting an attribute value
fdel :function to be used for del'ing an attribute
doc : docstring
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
repr()
repr(obj)
Return the canonical string representation of the object
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
sum()
sum(iterable, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types
The super() builtin returns a proxy object that allows you to refer parent class by 'super'
tuple()
tuple(iterable=())
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object.
type()
type(object)
Return the object's type
vars()
vars([object])
Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__.
zip()
zip(iter1 [,iter2 [...]])
Return a zip object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__() method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration.
Starts with def and take note the colon : at the end, optionally ends with return statement
Functions without return statement will have resulting value of None
return leaves the current function call with the expression list (or None) as return value
## Example function with no parameters def MyFunction1():
## Example function with 1 parameter def MyFunction1(p1):
## Example function with 1 parameter and 1 return value def MyFunction2(p1):
result=p1**2 return result
## Example function with 1 parameter
## and multiple return values
## multiple values returned as data type Tuple
>>> def ConvertSeconds(totalseconds):
... minutes = totalseconds//60
... seconds = totalseconds - minutes*60
... return minutes, seconds
...
>>> print(ConvertSeconds(130))
(2, 10)
>>> result=ConvertSeconds(130)
>>> print(result)
(2, 10)
>>> print(type(result))
<type 'tuple'>
>>>
## Example to specify specific data types
## for the arguments
>>> def mysum(x: int, y: int):
... result = x+y
... return result
...
>>> mysum(1,2)
3
## Example to specify specific data type
## for the function return value
>>> def myfloatsum(x: int, y: int) -> float:
... result = float(x+y)
... return(result)
...
>>> myfloatsum(1,2)
3.0
Anonymous inline Functions : Lambda
lambda[parameters]:expression
Example, generate a list of squares of numbers 1-10:
name="Tom"
age="30"
print("Your name is {} and you are {} years old".format(name,age)
Example 4
>>> name="Tom"
>>> age="30"
>>> print("Your name is {} and you are {} years old".format(name,age))
Your name is Tom and you are 30 years old
>>> print("Your name is {0} and you are {1} years old".format(name,age))
Your name is Tom and you are 30 years old
>>> print("Your name is {1} and you are {0} years old".format(age,name))
Your name is Tom and you are 30 years old
>>> print("Your name is {pName} and you are {pAge} years old".format(pName=name,pAge=age))
Your name is Tom and you are 30 years old
>>> print("Your name is {pName} and you are {pAge} years old".format(pAge=age,pName=name))
Your name is Tom and you are 30 years old
To use variable as width use a nested {} within the replacement field
Example
>>> M=27
>>> print("{:-^{}s}".format('WELCOME',M))
----------WELCOME----------
< align left
> align right
= for numeric types, places padding after sign but before digit e.g. +000000120
^ center align
+ sign should be used for both positive and negative
- sign should be used only for negative
'' space should be used for positive, - should be used for negative
b Binary format
c Character format
d Decimal integer, base 10
e Exponent notation with lowecase e, precision is 6
E Exponent notation with uppercase E
f fixed point notation, default precision 6
F same as F, but converts 'nan' to 'NAN', 'inf' to 'INF'
g General format
G same as g but switches to 'E' if number is too large
n Number format, uses current local setting for number separator
o Octal format, base 8
s String format
x Hex format using lowercase
X Hex format using UPPERCASE
% Percentage format. Multiples number by 100, uses f format and appends %
string with its first character capitalized and the rest lowercased
str.casefold()
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Different from converting to lowercase, stronger, more agressive,
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'
str.endswith(suffix[, start[, end]])
Return True; if the string ends with the specified suffix, otherwise return . suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position
str.expandtabs(tabsize=8)
Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8)
str.find(sub[, start[, end]])
Return the lowest index in str where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
str.format(*args,**kwargs)
Return a formatted version of str, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
str.format_map(mapping)
Similar to "str.format(**mapping)", except that "mapping" is used directly and not copied to a "dict". This is useful if for example "mapping" is a dict subclass:
str.index(sub[, start[, end]])
Return the lowest index in str where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
str.isalnum()
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character "c" is alphanumeric if one of the following returns "True": "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".
str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as ôLetterö, i.e., those with general category property being one of ôLmö, ôLtö, ôLuö, ôLlö, or ôLoö. Note that this is different from the Alphabetic property defined in the Unicode Standard.
str.isascii()
Return true if the string is empty or all characters in the string are ASCII, false otherwise. ASCII characters have code points in the range U+0000-U+007F.
str.isdecimal()
Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers.
str.isidentifier()
Return true if the string is a valid identifier according to the language definition, section Identifiers and keywords. Use "keyword.iskeyword()" to test for reserved identifiers such as "def" and "class".
str.islower()
Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise
str.isnumeric()
Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property
str.isprintable()
Return true if all characters in the string are printable or the string is empty, false otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable
str.isspace()
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise
str.istitle()
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise
str.isupper()
Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise
str.join(iterable)
Return a string which is the concatenation of the strings in *iterable*. A "TypeError" will be raised if there are any non- string values in *iterable*, including "bytes" objects. The separator between elements is the string providing this method.
str.ljust(width[, fillchar])
Return the string left justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to "len(s)".
str.lower()
Return a copy of the string with all the cased characters [4] converted to lowercase.
str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None;, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.
static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for "str.translate()". If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or "None". Character keys will then be converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to "None" in the result.
str.partition(sep)
Split the string at the first occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring *sub* is found, such that *sub* is contained within "s[start:end]". Optional arguments *start* and *end* are interpreted as in slice notation. Return "-1" on failure.
str.rindex(sub[, start[, end]])
Like "rfind()" but raises "ValueError" when the substring *sub* is not found.
str.rjust(width[, fillchar])
Return the string right justified in a string of length *width*. Padding is done using the specified *fillchar* (default is an ASCII space). The original string is returned if *width* is less than or equal to "len(s)".
str.rpartition(sep)
Split the string at the last occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
str.rsplit(sep=None, maxsplit=-1)
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* ones. If *sep* is not specified or "None", any whitespace string is a separator. Except for splitting from the right, "rsplit()" behaves like "split()" which is described in detail below.
str.rstrip([chars])
Return a copy of the string with trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or "None", the *chars* argument defaults to removing whitespace. The *chars* argument is not a suffix; rather, all combinations of its values are stripped:
str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most "maxsplit+1" elements). If *maxsplit* is not specified or "-1", then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, "'1,,2'.split(',')" returns "['1', '', '2']"). The *sep* argument may consist of multiple characters (for example, "'1<>2<>3'.split('<>')" returns "['1', '2', '3']"). Splitting an empty string with a specified separator returns "['']".
If *sep* is not specified or is "None", a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a "None" separator returns "[]".
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless *keepends* is given and true.
This method splits on the following line boundaries. In particular, the boundaries are a superset of *universal newlines*.
\n : Line Feed
\r : Carriage Return
\r\n : Carriage Return + Line Feed
\v or \x0b : Line Tabulation
\f or \x0c : Form Feed
\x1c : File Separator
\x1d : Group Separator
\x1e : Record Separator
\x85 : Next Line
\u2028 : Line Separator
\u2029 : Paragraph Separator
Unlike "split()" when a delimiter string *sep* is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
str.startswith(prefix[, start[, end]])
Return "True" if string starts with the *prefix*, otherwise return "False". *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or "None", the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
str.swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that "s.swapcase().swapcase() == s".
str.title()
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
str.translate(table)
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via "__getitem__()", typically a *mapping* or *sequence*. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return "None", to delete the character from the return string; or raise a "LookupError" exception, to map the character to itself.
You can use "str.maketrans()" to create a translation map from character-to-character mappings in different formats.
str.upper()
Return a copy of the string with all the cased characters [4] converted to uppercase.
str.zfill(width)
Return a copy of the string left filled with ASCII "'0'" digits to make a string of length *width*. A leading sign prefix ("'+'"/"'-'") is handled by inserting the padding *after* the sign character rather than before. The original string is returned if *width* is less than or equal to "len(s)".
str.format_map() >>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'
str.index()
>>> S="Hello, world!"
>>> S.index(",")
5
>>> S.index(",",0,10)
5
>>> S.index(",",10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
list.clear()
Remove all items from the list. Equivalent to del a[:].
list.copy()
Return a shallow copy of the list. Equivalent to a[:].
list.count(x)
Return the number of times x appears in the list.
list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
list.reverse()
Reverse the elements of the list in place.
list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation). list.sort() does not return a value, but sorts the items in place. To see the result, call the sort method first and then use the list later
Create a new dictionary with keys from *seq* and values set to *value*. "fromkeys()" is a class method that returns a new dictionary. *value* defaults to "None".
D.get(key[, default])
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to "None", so that this method never raises a "KeyError".
D.items()
Return a new view of the dictionaryÆs items ("(key, value)"
pairs). See the documentation of view objects.
D.keys()
Return a new view of the dictionaryÆs keys. See the
documentation of view objects.
D.pop(key[, default])
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is
not in the dictionary, a "KeyError" is raised.
D.popitem()
Remove and return a "(key, value)" pair from the dictionary.
Pairs are returned in LIFO (last-in, first-out) order.
"popitem()" is useful to destructively iterate over a
dictionary, as often used in set algorithms. If the dictionary
is empty, calling "popitem()" raises a "KeyError".
Changed in version 3.7: LIFO order is now guaranteed.
In prior versions, "popitem()" would return an arbitrary
key/value pair.
D.setdefault(key[, default])
If *key* is in the dictionary, return its value. If not, insert
*key* with a value of *default* and return *default*. *default*
defaults to "None".
D.update([other])
Update the dictionary with the key/value pairs from *other*,
overwriting existing keys. Return "None".
"update()" accepts either another dictionary object or an
iterable of key/value pairs (as tuples or other iterables of
length two). If keyword arguments are specified, the
dictionary is then updated with those key/value pairs:
"d.update(red=1, blue=2)".
D.values()
Return a new view of the dictionaryÆs values. See the
documentation of view objects.
.clear() >>> d = dict(one=1, two=2, three=3)
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d.clear()
>>> d
{}
classClassName[ ] :
"doc string for the class, accessible by calling the .__doc__ attr"
Notes:
Functions defined within the class (methods) have self as the first argument, whenever an object calls its method, the object itself is passed as the first argument.
calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method's object before the first argument
__init__() function is the constructor for the class. This function gets called whenever a new object of that class is instantiated
__str__() function defines whatt is printed when you call the print() function with the instance of the class as parameter
eg.
>>> class Apple:
... def __init__(self, color, flavor):
... self.color = color
... self.flavor = flavor
... def __str__(self):
... return "This apple is {} and it is {}".format(self.color,self.flavor)
...
>>> grannysmith = Apple("green","sour")
>>> print(grannysmith)
This apple is green and it is sour
>> myset = {1, 2} # Directly assigning values to a set
>> myset = set() # Initializing a set
>> myset = set(['a', 'b']) # Creating a set from a list
>> myset
{'a', 'b'}
Add
>> myset.add('c')
>> myset
{'a', 'c', 'b'}
>> myset.add('a') # As 'a' already exists in the set, nothing happens
>> myset.add((5, 4))
>> myset
{'a', 'c', 'b', (5, 4)}
>> a = {2, 4, 5, 9}
>> b = {2, 4, 11, 12}
>> a.union(b) # Values which exist in a or b
{2, 4, 5, 9, 11, 12}
>> a.intersection(b) # Values which exist in a and b
{2, 4}
>> a.difference(b) # Values which exist in a but not in b
{9, 5}
Methods
add(...)
Add an element to a set.
This has no effect if the element is already present.
clear(...)
Remove all elements from this set.
copy(...)
Return a shallow copy of a set.
difference(...)
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
difference_update(...)
Remove all elements of another set from this set.
discard(...)
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
intersection(...)
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
intersection_update(...)
Update a set with the intersection of itself and another.
isdisjoint(...)
Return True if two sets have a null intersection.
issubset(...)
Report whether another set contains this set.
issuperset(...)
Report whether this set contains another set.
pop(...)
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
remove(...)
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
symmetric_difference(...)
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
symmetric_difference_update(...)
Update a set with the symmetric difference of itself
and another.
union(...)
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
update(...)
Update a set with the union of itself and others.
Using a pair of parentheses to denote the empty tuple: ()
Using a trailing comma for a singleton tuple: a, or (a,)
Separating items with commas: a,b,c or (a,b,c)
Using the tuple() built-in: tuple() or tuple(iterable)
Accessing
Although you use brackets () to initialize Tuples, when accessing elements of the Tuple, use square brackets [] to slice or obtain value of specific index
is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as global in scope
Allows you to assign values to a global variable
example
when "global" statement is used:
>>> def myfun():
... global S
... S = S + " modified"
... print("Print from inside function : " + S)
...
>>> S="a global variable"
>>> print(S)
a global variable
>>> myfun()
Print from inside function : a global variable modified
when "global" statement not used
>>> def myfun():
... S = S + " modified"
... print("Print from inside function : " + S)
...
>>> S="a global variable"
>>> print(S)
a global variable
>>> myfun() Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in myfun
UnboundLocalError: local variable 'S' referenced before assignment
Makes the value bound to a variable available to the enclosing function in nested functions.
Introduced from version 3.8
def outer():
x = "local"
def inner(): nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
output
inner: nonlocal
outer: nonloca
pass
pass is a null operation, when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.
Examples:
def f(arg): pass
# function that does nothing (yet)
if x < 0: raise Exception("You entered a negative number")
eg. 2
if not type(n) is int: raise TypeError("Not an integer")
e.g. 3
## raise ValueError if the item to be removed
## is not in the list
def RemoveValue(myVal):
if myVal not in my_list: raise ValueError("Value must be in the given list")
else:
my_list.remove(myVal)
return my_list
withsmthg_that_returns_context_manager asvar:
# process var
The with statement is used to wrap the execution of a block with methods defined by a context manager
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code
eg. 1
# using with statement
with open('filepath', 'w') as file:
file.write('some data')
# The with statement will ensure the file is closed at the end of the block.
# no need to explicitly close the file.
yield
yield <expr> yield from <expr>
yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function.
A generator function, is like a normal function but with yield statement instead of a return statement.
The difference is that, while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.
Examples:
>>> def MyGen():
... list=range(5)
... for i in list:
... yield i*i
...
>>> for x in MyGen():
... print(x)
...
0
1
4
9
16