{ "cells": [ { "cell_type": "raw", "metadata": { "raw_mimetype": "text/restructuredtext" }, "source": [ ".. meta::\n", " :description: Topic: Basics of Python Objects, Difficulty: Easy, Category: Section\n", " :keywords: integers, booleans, floats, floating point precision, lists, strings, fundamentals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic Object Types\n", "\n", "
| | "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```python\n",
"# demonstrating boolean-logic operators\n",
">>> True or False\n",
"True\n",
"\n",
">>> True and False\n",
"False\n",
"\n",
">>> not False \n",
"True\n",
"```\n",
"\n",
"Operator symbols are available in place of the reserved words `and` and `or`:\n",
"```python\n",
"# demonstrating the symbolic logic operators\n",
">>> False | True # equivalent to: `False or True`\n",
"True\n",
"\n",
">>> False & True # equivalent to: `False and True`\n",
"False\n",
"```\n",
"That being said, it is generally more \"Pythonic\" (i.e. in-vogue with Python users) to favor the use of the word-operators over the symbolic ones. \n",
"\n",
"Multiple logic operators can be used in a single line and parentheses can be used to group expressions:\n",
"```python\n",
">>> (True or False) and True\n",
"True\n",
"```\n",
"\n",
"Comparison statements used in basic mathematics naturally return boolean objects.\n",
"```python\n",
">>> 2 < 3\n",
"True\n",
"\n",
">>> 10.5 < 0\n",
"False\n",
"\n",
">>> (2 < 4) and not (4 != -1)\n",
"False\n",
"```\n",
"\n",
"The `bool` type has additional utilities, which will be discussed in the \"Conditional Statements\" section."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Boolean Objects are Integers\n",
"The two boolean objects `True` and `False` formally belong to the `int` type in addition to `bool`, and are associated with the values `1` and `0`, respectively:\n",
"\n",
"```python\n",
">>> isinstance(True, int)\n",
"True\n",
"\n",
">>> int(True)\n",
"1\n",
"\n",
">>> isinstance(False, int)\n",
"True\n",
"\n",
">>> int(False)\n",
"0\n",
"```\n",
"\n",
"As such, they can be used in mathematical expressions interchangeably with `1` and `0` \n",
"```python\n",
">>> 3*True - False # equivalent to: 3*1 + 0 \n",
"3\n",
"\n",
">>> True / False # equivalent to: 1 / 0\n",
"---------------------------------------------------------------------------\n",
"ZeroDivisionError Traceback (most recent call last)\n",
"