Why is this field calculator expression evaluated incorrectly when using Python syntax?

I have a polygon featureclass containing an integer field 'gridcode'. I've added 2 new float fields VB_calc and Python_calc, both of which should be equal togridcode / 1,000,000.

If I calculate the field using the Field Calculator with the VB Script[fieldname]syntax, the result is as expected.

If I use the Python!fieldname!syntax, the results are all zero.

What am I doing wrong here? I entered those expressions by double-clicking the gridcode fieldname in the calculator. (My goal is to use this within a stand-alone Python script but I'm debugging it here since the script isn't working either.) Both fields are definitely of type FLOAT.

As you've discovered python truncates integers that are divided - this may include floating point fields with integers stored in them, sometimes 'duck typing' isn't your friend!

To force the issue and produce a floating point answer from a division float your number first:


It is best to do this always when dividing otherwise if your enumerator (value in the field) is an integer you could get a truncated answer thanks to pythons' sometimes handy duck typing of variables.

For example if most of your values are like 999.999999 but one is actually 1000 and you divide by 10000 you will get around 0.99999999999 as the answer for most and 0 for the one that has an integer value…

5 Answers 5

This is because the pyparsing code allows functions. (And by the way, it does a lot more than what you need, i.e. create a stack and evaluate that.)

For starters, you could remove pi and ident (and possibly something else I'm missing right now) from the code to disallow characters.

The reason is different: PyParsing parsers won't try to consume the whole input by default. You have to add + StringEnd() (and import it, of course) to the end of expr to make it fail if it can't parse the whole input. In that case, pyparsing.ParseException will be raised. (Source:

If you care to learn a bit of parsing, what you need can propably be built in less than thirty lines with any decent parsing library (I like LEPL).

Why not just evaluate it and catch the syntax error?

It's restricted to only mathematical operations, so it should work a bit better than a crude eval .

You could try building a simple parser yourself to tokenize the string of the arithmetic expression and then build an expression tree, if the tree is valid (the leaves are all operands and the internal nodes are all operators) then you can say that the expression is valid.

The basic concept is to make a few helper functions to create your parser.

def extract() will get the next character from the expression
def peek() similar to extract but used if there is no whitespace to check the next character

Alternatively if you can guarantee whitespace between characters you could use split() to do all the tokenizing.

Reverse Polish Notation (RPN) Calculator

I am trying to solve a codewar challenge (link):

Your job is to create a calculator which evaluates expressions in Reverse Polish notation.

For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14.

For your convenience, the input is formatted such that a space is provided between every token.

Empty expression should evaluate to 0.

Valid operations are + , - , * , / .

You may assume that there won't be exceptional situations (like stack underflow or division by zero).

I have 2 problems, the first is that the code looks awful and I don't know how to improve it tbh, I also want this code to be able to compute multiple digit numbers and i feel like i need to start from scratch if I want to add that.

Note : This is my first time writing a question so if there's anything wrong with it please tell me and I'll change it.


You should use generators more often. They are more memory-efficient than lists because each value is generated on the fly instead of needing to remember them all at once.

This is especially useful in has_op() , for example. All you need to do is remove the opening and closing brackets. That changes to using a generator expression instead of a list comprehension. Let's say the first item in tokens is a match. If you use a generator expression, any() will return True right away, and none of the other tokens is even checked. When you use a list comprehension, any() doesn't start to do anything until all tokens have been processed.

It is also useful in eval_tokens when you are using has_op . In short, it is rare indeed if a list comprehension is to be preferred over a generator expression when using any() .

You have other functions that might work nicely as generator functions, except that the functions using them all require them to be lists, so that would mean that they would need to use the list function. It might still be a good idea, but it isn't a clear advantage.

if key == "name" and item: means if (key == "name") and (item evaluates to True) .

Keep in mind that (item evaluates to True) is possible in several ways. For example if (key == "name") and [] will evaluate to False .

Manoj explained it well. Here goes some complementary notes.

An interesting idiom to do it is:

but it is more useful for really large conditions where you just want to know if some value is equal to any other value from a list.

No, you have to repeat the expression. It evaluates as 2 separate conditions, and checks if both are true -

Check the Python documentation for a list of what is considered False in Python

(However, interesting to note that, as opposed to other languages, the following:

If, hypothetically, you did want

Others have explained how the expression you're asking about is evaluated. An important thing to know is that if the first operand of the "and" operator evaluates to false, the second one is never evaluated, because the result of "and" is always false if one operand is false, and if you know the first operand is false, then the whole "and" is false and you don't have to evaluate the second. This is called "short-circuiting" and applies to "or" as well as "and" (except that "or" is always true when either operand is true, so the second operand is evaluated only when the first is false).

The other thing you need to know is that the result of the whole "and" operation is the value of the last operand evaluated. Since things other than the literal constants True and False are considered logically true or false, this fact (combined with short-circuiting) can be used as a substitute for "if" statements in some situations, and you will occasionally see it used that way.

For example, "x or y" evaluates to x if x is true, but to y if x is false. Sometimes this is used to provide defaults for missing values:

If you don't enter anything at the prompt, just hit Enter, the return value of raw_input is the empty string, "", which is considered false. Since the left branch of the "or" is false, it doesn't short-circuit, and the right branch is evaluated, so the result of the "or" is "dude." If you do enter a value at the prompt, the right branch never gets evaluated, due to short-circuiting, and so the value of the "or" is whatever you entered.

A lot of people consider abusing Boolean operators this way to be poor style now that Python has "x if y else z," but this particular use strikes me as readable enough. (But this is about the only one!) "The value is this, or that if it's empty." Compare it to the following:

Pattern Syntax¶

Regular expressions support more powerful patterns than simple literal text strings. Patterns can repeat, can be anchored to different logical locations within the input, and can be expressed in compact forms that don’t require every literal character be present in the pattern. All of these features are used by combining literal text values with metacharacters that are part of the regular expression pattern syntax implemented by re . The following examples will use this test program to explore variations in patterns.

The output of test_patterns() shows the input text, including the character positions, as well as the substring range from each portion of the input that matches the pattern.


There are five ways to express repetition in a pattern. A pattern followed by the metacharacter * is repeated zero or more times (allowing a pattern to repeat zero times means it does not need to appear at all to match). Replace the * with + and the pattern must appear at least once. Using ? means the pattern appears zero or one time. For a specific number of occurrences, use after the pattern, where m is replaced with the number of times the pattern should repeat. And finally, to allow a variable but limited number of repetitions, use where m is the minimum number of repetitions and n is the maximum. Leaving out n ( ) means the value appears at least m times, with no maximum.

Notice how many more matches there are for ab* and ab? than ab+ .

The normal processing for a repetition instruction is to consume as much of the input as possible while matching the pattern. This so-called greedy behavior may result in fewer individual matches, or the matches may include more of the input text than intended. Greediness can be turned off by following the repetition instruction with ? .

Disabling greedy consumption of the input for any of the patterns where zero occurences of b are allowed means the matched substring does not include any b characters.

Character Sets¶

A character set is a group of characters, any one of which can match at that point in the pattern. For example, [ab] would match either a or b .

The greedy form of the expression, a[ab]+ , consumes the entire string because the first letter is a and every subsequent character is either a or b .

A character set can also be used to exclude specific characters. The special marker ^ means to look for characters not in the set following.

This pattern finds all of the substrings that do not contain the characters - , . , or a space.

As character sets grow larger, typing every character that should (or should not) match becomes tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point.

Here the range a-z includes the lower case ASCII letters, and the range A-Z includes the upper case ASCII letters. The ranges can also be combined into a single character set.

As a special case of a character set the metacharacter dot, or period ( . ), indicates that the pattern should match any single character in that position.

Combining dot with repetition can result in very long matches, unless the non-greedy form is used.

Escape Codes¶

An even more compact representation uses escape codes for several pre-defined character sets. The escape codes recognized by re are:

Code Meaning
d a digit
D a non-digit
s whitespace (tab, space, newline, etc.)
S non-whitespace
w alphanumeric
W non-alphanumeric

Escapes are indicated by prefixing the character with a backslash ( ). Unfortunately, a backslash must itself be escaped in normal Python strings, and that results in expressions that are difficult to read. Using raw strings, created by prefixing the literal value with r , for creating regular expressions eliminates this problem and maintains readability.

These sample expressions combine escape codes with repetition to find sequences of like characters in the input string.

To match the characters that are part of the regular expression syntax, escape the characters in the search pattern.

These patterns escape the backslash and plus characters, since as metacharacters both have special meaning in a regular expression.


In addition to describing the content of a pattern to match, you can also specify the relative location in the input text where the pattern should appear using anchoring instructions.

Code Meaning
^ start of string, or line
$ end of string, or line
A start of string
 end of string
 empty string at the beginning or end of a word
B empty string not at the beginning or end of a word

The patterns in the example for matching words at the beginning and end of the string are different because the word at the end of the string is followed by punctuation to terminate the sentence. The pattern w+$ would not match, since . is not considered an alphanumeric character.

Built-in Functions¶

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__() . If the argument is a complex number, its magnitude is returned.

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

Return True if any element of the iterable is true. If the iterable is empty, return False . Equivalent to:

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.

Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

If prefix “0b” is desired or not, you can use either of the following ways.

See also format() for more information.

Return a Boolean value, i.e. one of True or False . x is converted using the standard truth testing procedure . If x is false or omitted, this returns False otherwise it returns True . The bool class is a subclass of int (see Numeric Types — int, float, complex ). It cannot be subclassed further. Its only instances are False and True (see Boolean Values ).

Changed in version 3.7: x is now a positional-only parameter.

This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook() , passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.

Raises an auditing event builtins.breakpoint with argument breakpointhook .

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types , as well as most methods that the bytes type has, see Bytes and Bytearray Operations .

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters bytearray() then converts the string to bytes using str.encode() .

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface , a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256 , which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256 . bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray() .

Bytes objects can also be created with literals, see String and Bytes literals .

Return True if the object argument appears callable, False if not. If this returns True , it is still possible that a call fails, but if it is False , calling object will never succeed. Note that classes are callable (calling a class returns a new instance) instances are callable if their class has a __call__() method.

New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a' , while chr(8364) returns the string '€' . This is the inverse of ord() .

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

Transform a method into a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

The @classmethod form is a function decorator – see Function definitions for details.

A class method can be called either on the class (such as C.f() ) or on an instance (such as C().f() ). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section. For more information on class methods, see The standard type hierarchy .

Changed in version 3.9: Class methods can now wrap other descriptors such as property() .

Compile the source into a code or AST object. Code objects can be executed by exec() or eval() . source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read pass some recognizable value if it wasn’t read from a file ( '<string>' is commonly used).

The mode argument specifies what kind of code must be compiled it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling compile() . If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the flags (future features and compiler options) in the surrounding code are ignored.

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module. Compiler flags can be found in ast module, with PyCF_ prefix.

The argument optimize specifies the optimization level of the compiler the default value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes.

If you want to parse Python code into its AST representation, see ast.parse() .

Raises an auditing event compile with arguments source and filename . This event may also be raised by implicit compilation.

When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also input in 'exec' mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, TypeError was raised when null bytes were encountered in source.

New in version 3.8: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT can now be passed in flags to enable support for top-level await , async for , and async with .

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float . If both arguments are omitted, returns 0j .

For a general Python object x , complex(x) delegates to x.__complex__() . If __complex__() is not defined then it falls back to __float__() . If __float__() is not defined then it falls back to __index__() .

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError .

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.8: Falls back to __index__() if __complex__() and __float__() are not defined.

This is a relative of setattr() . The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar .

Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in list , set , and tuple classes, as well as the collections module.

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__() , this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__() , the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__() .

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b) . For floating point numbers the result is (q, a % b) , where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b) .

Return an enumerate object. iterable must be a sequence, an iterator , or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__ , a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

This function can also be used to execute arbitrary code objects (such as those created by compile() ). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval() ’s return value will be None .

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec() .

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). 1 If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the nonlocal , yield , and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None .

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key __builtins__ , a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec() .

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec() .

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None , the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None .

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-' a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals . Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x , float(x) delegates to x.__float__() . If __float__() is not defined then it falls back to __index__() .

If no argument is given, 0.0 is returned.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __float__() is not defined.

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language .

The default format_spec is an empty string which usually gives the same effect as calling str(value) .

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.

Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in set , list , tuple , and dict classes, as well as the collections module.

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar . If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with getattr() .

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine. See __hash__() for details.

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function, when invoking help() , it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters .

This function is added to the built-in namespace by the site module.

Changed in version 3.4: Changes to pydoc and inspect mean that the reported signatures for callables are now more comprehensive and consistent.

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

See also format() for more information.

See also int() for converting a hexadecimal string to an integer using a base of 16.

To obtain a hexadecimal string representation for a float, use the float.hex() method.

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

Raises an auditing event with argument id .

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Raises an auditing event builtins.input with argument prompt before reading input

Raises an auditing event builtins.input/result with the result after successfully reading input.

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__() , int(x) returns x.__int__() . If x defines __index__() , it returns x.__index__() . If x defines __trunc__() , it returns x.__trunc__() . For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes , or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z ) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b / 0B , 0o / 0O , or 0x / 0X , as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8) .

Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__ .

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

Changed in version 3.8: Falls back to __index__() if __int__() is not defined.

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual ) subclass thereof. If object is not an object of the given type, the function always returns False . If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

issubclass ( class, classinfo ) ¶

Return True if class is a subclass (direct, indirect or virtual ) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0 ). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

CPython implementation detail: len raises OverflowError on lengths larger than sys.maxsize , such as range(2 ** 100) .

Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range .

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

The contents of this dictionary should not be modified changes may not affect the values of local and free variables used by the interpreter.

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap() .

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable . The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort() . The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc) .

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None .

Return a “memory view” object created from the given argument. See Memory Views for more information.

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable . The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort() . The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc) .

New in version 3.4: The default keyword-only argument.

Changed in version 3.8: The key can be None .

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

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.

object does not have a __dict__ , so you can’t assign arbitrary attributes to an instance of the object class.

Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

If you want to convert an integer number to octal string either with prefix “0o” or not, you can use either of the following ways.

See also format() for more information.

Open file and return a corresponding file object . If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False .)


To find all of the entities of the Person kind whose ages are between 18 and 35 (i.e. both Charlies and Edna), use this query:

To find the three entities of the Person kind whose ages are the greatest (i.e. Amy, Betty and Charlie), use this query:

To find the entities of the Person kind whose names are one of "Betty" or "Charlie", use this query:

To return only the name values for each Person , use this query:

To return only the name values for each Person , ordered by age , use this query:

To find the keys of the entities of the Person kind that have an age of None (i.e. KEY('Person', 'georgemichael') ), use this query:

To find all the entities, regardless of kind, that are in Amy's entity group (i.e. Amy and Fred), use this query:

To match by Key, we can use __key__ on the left hand side of a condition. For example, we can use this to get all Person entities that have a username that starts with "a".

Note: If you ever build a query with an equality on __key__ , consider using get() instead to fetch the entity directly.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Get Extra Features in Python

So far, you&rsquove learned a few basic Python concepts and features. When you start to dive deeper into the language, you may find that you need a certain feature and decide to code it by yourself. If that&rsquos the case, then consider that you might be reinventing the wheel.

Python&rsquos been in use for almost three decades now. It has an incredibly large community of developers, and it&rsquos likely that someone else has run into the same problem as you. With a little research, you may be able to find a code snippet, library, framework, or other solution that can save you a lot of time and effort.

The first place to look is the Python standard library. If you don&rsquot find anything there, then you can also look at the Python Package Index (PyPI). Finally, you can check out some other third-party libraries.

The Standard Library

One of the great things about Python is the plethora of available modules, packages, and libraries both built into the Python core and made available by third-party developers. These modules, packages, and libraries can be quite helpful in your day-to-day work as a Python coder. Here are some of the most commonly used built-in modules:

    for mathematical operations for generating pseudo-random numbers for working with regular expressions for using operating system&ndashdependent functionalities for working with iterators for specialized container data types

For example, here you import math to use pi , find the square root of a number with sqrt() , and raise a number to a power with pow() :

Once you import math , you can use any function or object defined in that module. If you want a complete list of the functions and objects that live in math , then you can run something like dir(math) in an interactive session.

You can also import specific functions directly from math or any other module:

This kind of import statement brings the name sqrt() into your current namespace, so you can use it directly without the need to reference the containing module.

If you&rsquore using modules, such as math or random , then make sure not to use those same names for your custom modules, functions, or objects. Otherwise, you might run into name conflicts, which can cause in unexpected behavior.

The Python Package Index and pip

The Python package index, also known as PyPI (pronounced &ldquopie pea eye&rdquo), is a massive repository of Python packages that includes frameworks, tools, packages, and libraries. You can install any PyPI package using pip . This is one of the recommended tools for managing third-party modules, packages, and libraries in Python.

New coders frequently hit a wall when they&rsquore following an example and they see ModuleNotFoundError: No module named module_x when they run the code. This means that the code depends on module_x , but that module isn&rsquot installed in the current Python environment, creating a broken dependency. Modules like module_x can be manually installed using pip .

For example, say you&rsquore trying to run an application that uses pandas, but you don&rsquot have this library installed on your computer. In this case, you can open your terminal and use pip like this:

This command downloads pandas and its dependencies from PyPI and installs them in your current Python environment. Once the installation is finished, you can run your application again and, if there&rsquos no other broken dependency, the code should work.

In Python, the data type is set when you assign a value to a variable:

Example Data Type Try it
x = "Hello World" str Try it »
x = 20 int Try it »
x = 20.5 float Try it »
x = 1j complex Try it »
x = ["apple", "banana", "cherry"] list Try it »
x = ("apple", "banana", "cherry") tuple Try it »
x = range(6) range Try it »
x = dict Try it »
x = set Try it »
x = frozenset(<"apple", "banana", "cherry">) frozenset Try it »
x = True bool Try it »
x = b"Hello" bytes Try it »
x = bytearray(5) bytearray Try it »
x = memoryview(bytes(5)) memoryview Try it »

Watch the video: How to use field calculator in ArcMap with Python expression? Lecture (October 2021).