{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Data Values & Types, Variables, Std I/O, Computations\n", "- A value is one of the fundamental things -- like a letter or number -- that a program manipulates. \n", "- These values are classified into data types.\n", "\n", "- In Python, there're mainly two data types: numbers and strings - numbers can be integer or float\n", "- Boolean (True/False) is also supported type!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## first program - hello world!" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!\n" ] } ], "source": [ "# First program\n", "# This is a comment line...\n", "# By Programmer info...\n", "print('Hello world!')\n", "# In python 2: print is a statement not a function\n", "# print 'Hello World!' " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## comments\n", "- Programming languages provide a way to write comment along with the codes\n", "- Python uses # symbol to write a single line comment\n", "- comments are for humans/programmers to convey/explain what the code is doing or supposed to do\n", "- Python interpreter ignores the comments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## data types\n", "- built-in type() function can be used to know type of data\n", "- functions will be covered in Chapter 04" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(100)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(1000.99)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type('Hello World!')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type('A')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "Missing parentheses in call to 'print'. Did you mean print(hello)? (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m print hello\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m Missing parentheses in call to 'print'. Did you mean print(hello)?\n" ] } ], "source": [ "print hello" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(\"17\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(\"\"\"Triple double quoted data\"\"\")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type('''Type of Triple single quote data is''')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## type conversion/casting\n", "- changing data from one type into another when possible\n", "- use built-in function such as str(), int(), float(), etc. to convert data to that particular type\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "data = 'hello' # can't conver it to int or float types" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = '100'\n", "type(data)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num = int(data)\n", "type(num)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "price = float('500.99')\n", "type(price)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num = 99.99\n", "strNum = str(num)\n", "type(strNum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## standard output\n", "- printing or writing output to common/standard output such as monitor\n", "- way to display the results and interact with the users of your program" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"Oh no\", she exclaimed, \"Ben's bike is broken!\"\n" ] } ], "source": [ "print('''\"Oh no\", she exclaimed, \"Ben's bike is broken!\"''')" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What's up\n", " Shaq O'Neal?\n" ] } ], "source": [ "print(\"What\\'s up\\n Shaq O\\'Neal?\")" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "bool" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(True)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "source": [ "print(x)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class str in module builtins:\n", "\n", "class str(object)\n", " | str(object='') -> str\n", " | str(bytes_or_buffer[, encoding[, errors]]) -> str\n", " | \n", " | Create a new string object from the given object. If encoding or\n", " | errors is specified, then the object must expose a data buffer\n", " | that will be decoded using the given encoding and error handler.\n", " | Otherwise, returns the result of object.__str__() (if defined)\n", " | or repr(object).\n", " | encoding defaults to sys.getdefaultencoding().\n", " | errors defaults to 'strict'.\n", " | \n", " | Methods defined here:\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __format__(self, format_spec, /)\n", " | Return a formatted version of the string as described by format_spec.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(self, key, /)\n", " | Return self[key].\n", " | \n", " | __getnewargs__(...)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self int\n", " | \n", " | Return the number of non-overlapping occurrences of substring sub in\n", " | string S[start:end]. Optional arguments start and end are\n", " | interpreted as in slice notation.\n", " | \n", " | encode(self, /, encoding='utf-8', errors='strict')\n", " | Encode the string using the codec registered for encoding.\n", " | \n", " | encoding\n", " | The encoding in which to encode the string.\n", " | errors\n", " | The error handling scheme to use for encoding errors.\n", " | The default is 'strict' meaning that encoding errors raise a\n", " | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n", " | 'xmlcharrefreplace' as well as any other name registered with\n", " | codecs.register_error that can handle UnicodeEncodeErrors.\n", " | \n", " | endswith(...)\n", " | S.endswith(suffix[, start[, end]]) -> bool\n", " | \n", " | Return True if S ends with the specified suffix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | suffix can also be a tuple of strings to try.\n", " | \n", " | expandtabs(self, /, tabsize=8)\n", " | Return a copy where all tab characters are expanded using spaces.\n", " | \n", " | If tabsize is not given, a tab size of 8 characters is assumed.\n", " | \n", " | find(...)\n", " | S.find(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | format(...)\n", " | S.format(*args, **kwargs) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from args and kwargs.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | format_map(...)\n", " | S.format_map(mapping) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from mapping.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | index(...)\n", " | S.index(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found, \n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | isalnum(self, /)\n", " | Return True if the string is an alpha-numeric string, False otherwise.\n", " | \n", " | A string is alpha-numeric if all characters in the string are alpha-numeric and\n", " | there is at least one character in the string.\n", " | \n", " | isalpha(self, /)\n", " | Return True if the string is an alphabetic string, False otherwise.\n", " | \n", " | A string is alphabetic if all characters in the string are alphabetic and there\n", " | is at least one character in the string.\n", " | \n", " | isascii(self, /)\n", " | Return True if all characters in the string are ASCII, False otherwise.\n", " | \n", " | ASCII characters have code points in the range U+0000-U+007F.\n", " | Empty string is ASCII too.\n", " | \n", " | isdecimal(self, /)\n", " | Return True if the string is a decimal string, False otherwise.\n", " | \n", " | A string is a decimal string if all characters in the string are decimal and\n", " | there is at least one character in the string.\n", " | \n", " | isdigit(self, /)\n", " | Return True if the string is a digit string, False otherwise.\n", " | \n", " | A string is a digit string if all characters in the string are digits and there\n", " | is at least one character in the string.\n", " | \n", " | isidentifier(self, /)\n", " | Return True if the string is a valid Python identifier, False otherwise.\n", " | \n", " | Use keyword.iskeyword() to test for reserved identifiers such as \"def\" and\n", " | \"class\".\n", " | \n", " | islower(self, /)\n", " | Return True if the string is a lowercase string, False otherwise.\n", " | \n", " | A string is lowercase if all cased characters in the string are lowercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | isnumeric(self, /)\n", " | Return True if the string is a numeric string, False otherwise.\n", " | \n", " | A string is numeric if all characters in the string are numeric and there is at\n", " | least one character in the string.\n", " | \n", " | isprintable(self, /)\n", " | Return True if the string is printable, False otherwise.\n", " | \n", " | A string is printable if all of its characters are considered printable in\n", " | repr() or if it is empty.\n", " | \n", " | isspace(self, /)\n", " | Return True if the string is a whitespace string, False otherwise.\n", " | \n", " | A string is whitespace if all characters in the string are whitespace and there\n", " | is at least one character in the string.\n", " | \n", " | istitle(self, /)\n", " | Return True if the string is a title-cased string, False otherwise.\n", " | \n", " | In a title-cased string, upper- and title-case characters may only\n", " | follow uncased characters and lowercase characters only cased ones.\n", " | \n", " | isupper(self, /)\n", " | Return True if the string is an uppercase string, False otherwise.\n", " | \n", " | A string is uppercase if all cased characters in the string are uppercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | join(self, iterable, /)\n", " | Concatenate any number of strings.\n", " | \n", " | The string whose method is called is inserted in between each given string.\n", " | The result is returned as a new string.\n", " | \n", " | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\n", " | \n", " | ljust(self, width, fillchar=' ', /)\n", " | Return a left-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | lower(self, /)\n", " | Return a copy of the string converted to lowercase.\n", " | \n", " | lstrip(self, chars=None, /)\n", " | Return a copy of the string with leading whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | partition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string. If the separator is found,\n", " | returns a 3-tuple containing the part before the separator, the separator\n", " | itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing the original string\n", " | and two empty strings.\n", " | \n", " | replace(self, old, new, count=-1, /)\n", " | Return a copy with all occurrences of substring old replaced by new.\n", " | \n", " | count\n", " | Maximum number of occurrences to replace.\n", " | -1 (the default value) means replace all occurrences.\n", " | \n", " | If the optional argument count is given, only the first count occurrences are\n", " | replaced.\n", " | \n", " | rfind(...)\n", " | S.rfind(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | rindex(...)\n", " | S.rindex(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | rjust(self, width, fillchar=' ', /)\n", " | Return a right-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | rpartition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string, starting at the end. If\n", " | the separator is found, returns a 3-tuple containing the part before the\n", " | separator, the separator itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing two empty strings\n", " | and the original string.\n", " | \n", " | rsplit(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | Splits are done starting at the end of the string and working to the front.\n", " | \n", " | rstrip(self, chars=None, /)\n", " | Return a copy of the string with trailing whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | split(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | splitlines(self, /, keepends=False)\n", " | Return a list of the lines in the string, breaking at line boundaries.\n", " | \n", " | Line breaks are not included in the resulting list unless keepends is given and\n", " | true.\n", " | \n", " | startswith(...)\n", " | S.startswith(prefix[, start[, end]]) -> bool\n", " | \n", " | Return True if S starts with the specified prefix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | prefix can also be a tuple of strings to try.\n", " | \n", " | strip(self, chars=None, /)\n", " | Return a copy of the string with leading and trailing whitespace remove.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | swapcase(self, /)\n", " | Convert uppercase characters to lowercase and lowercase characters to uppercase.\n", " | \n", " | title(self, /)\n", " | Return a version of the string where each word is titlecased.\n", " | \n", " | More specifically, words start with uppercased characters and all remaining\n", " | cased characters have lower case.\n", " | \n", " | translate(self, table, /)\n", " | Replace each character in the string using the given translation table.\n", " | \n", " | table\n", " | Translation table, which must be a mapping of Unicode ordinals to\n", " | Unicode ordinals, strings, or None.\n", " | \n", " | The table must implement lookup/indexing via __getitem__, for instance a\n", " | dictionary or list. If this operation raises LookupError, the character is\n", " | left untouched. Characters mapped to None are deleted.\n", " | \n", " | upper(self, /)\n", " | Return a copy of the string converted to uppercase.\n", " | \n", " | zfill(self, width, /)\n", " | Pad a numeric string with zeros on the left, to fill a field of the given width.\n", " | \n", " | The string is never truncated.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | maketrans(x, y=None, z=None, /)\n", " | Return a translation table usable for str.translate().\n", " | \n", " | If there is only one argument, it must be a dictionary mapping Unicode\n", " | ordinals (integers) or characters to Unicode ordinals, strings or None.\n", " | Character keys will be then converted to ordinals.\n", " | If there are two arguments, they must be strings of equal length, and\n", " | in the resulting dictionary, each character in x will be mapped to the\n", " | character at the same position in y. If there is a third argument, it\n", " | must be a string, whose characters will be mapped to None in the result.\n", "\n" ] } ], "source": [ "help(str)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## escape sequences\n", "- some letters or sequence of letters have special meaning to Python\n", "- single, double and tripple single or double quotes represent string data\n", "- use backslash \\ to represent these escape sequences, e.g.,\n", " - \\n - new line\n", " - \\\\ - back quote\n", " - \\t - tab\n", " - \\r - carriage return\n", " - \\' - single quote\n", " - \\\" - double quote" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello \there...\n", " how are you?\n" ] } ], "source": [ "print('hello \\there...\\n how are you?')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "how many back slahses will be printeted? \\\\\n" ] } ], "source": [ "print('how many back slahses will be printeted? \\\\\\\\')" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "how many back slahses will be printeted? \\\\\\\\\n" ] } ], "source": [ "print(r'how many back slahses will be printeted? \\\\\\\\')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## variables\n", "- Variables are identifiers that are used to store values which can be then easily manipulated\n", "- variables give names to data so the data can be easily referenced by their names over and again\n", "- Rules and best practices for creating identifiers and variable names:\n", " - can't be a keyword -- what are the built-in keywords?\n", " - can start with only alphabets or underscore ( _ )\n", " - can't have symbols such as $, %, &, white space, etc.\n", " - can't start with a digit but digits can be used anywhere else in the name\n", " - use camelCase names or use _ for_multi_word_names\n", " - use concise yet meaningul and unambigous names for less typing and avoid typos" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Here is a list of the Python keywords. Enter any keyword to get more help.\n", "\n", "False class from or\n", "None continue global pass\n", "True def if raise\n", "and del import return\n", "as elif in try\n", "assert else is while\n", "async except lambda with\n", "await finally nonlocal yield\n", "break for not \n", "\n" ] } ], "source": [ "help('keywords')" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on bool object:\n", "\n", "class bool(int)\n", " | bool(x) -> bool\n", " | \n", " | Returns True when the argument x is true, False otherwise.\n", " | The builtins True and False are the only two instances of the class bool.\n", " | The class bool is a subclass of the class int, and cannot be subclassed.\n", " | \n", " | Method resolution order:\n", " | bool\n", " | int\n", " | object\n", " | \n", " | Methods defined here:\n", " | \n", " | __and__(self, value, /)\n", " | Return self&value.\n", " | \n", " | __or__(self, value, /)\n", " | Return self|value.\n", " | \n", " | __rand__(self, value, /)\n", " | Return value&self.\n", " | \n", " | __repr__(self, /)\n", " | Return repr(self).\n", " | \n", " | __ror__(self, value, /)\n", " | Return value|self.\n", " | \n", " | __rxor__(self, value, /)\n", " | Return value^self.\n", " | \n", " | __str__(self, /)\n", " | Return str(self).\n", " | \n", " | __xor__(self, value, /)\n", " | Return self^value.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from int:\n", " | \n", " | __abs__(self, /)\n", " | abs(self)\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __bool__(self, /)\n", " | self != 0\n", " | \n", " | __ceil__(...)\n", " | Ceiling of an Integral returns itself.\n", " | \n", " | __divmod__(self, value, /)\n", " | Return divmod(self, value).\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __float__(self, /)\n", " | float(self)\n", " | \n", " | __floor__(...)\n", " | Flooring an Integral returns itself.\n", " | \n", " | __floordiv__(self, value, /)\n", " | Return self//value.\n", " | \n", " | __format__(self, format_spec, /)\n", " | Default object formatter.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getnewargs__(self, /)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __index__(self, /)\n", " | Return self converted to an integer, if self is suitable for use as an index into a list.\n", " | \n", " | __int__(self, /)\n", " | int(self)\n", " | \n", " | __invert__(self, /)\n", " | ~self\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __lshift__(self, value, /)\n", " | Return self<>self.\n", " | \n", " | __rshift__(self, value, /)\n", " | Return self>>value.\n", " | \n", " | __rsub__(self, value, /)\n", " | Return value-self.\n", " | \n", " | __rtruediv__(self, value, /)\n", " | Return value/self.\n", " | \n", " | __sizeof__(self, /)\n", " | Returns size in memory, in bytes.\n", " | \n", " | __sub__(self, value, /)\n", " | Return self-value.\n", " | \n", " | __truediv__(self, value, /)\n", " | Return self/value.\n", " | \n", " | __trunc__(...)\n", " | Truncating an Integral returns itself.\n", " | \n", " | bit_length(self, /)\n", " | Number of bits necessary to represent self in binary.\n", " | \n", " | >>> bin(37)\n", " | '0b100101'\n", " | >>> (37).bit_length()\n", " | 6\n", " | \n", " | conjugate(...)\n", " | Returns self, the complex conjugate of any int.\n", " | \n", " | to_bytes(self, /, length, byteorder, *, signed=False)\n", " | Return an array of bytes representing an integer.\n", " | \n", " | length\n", " | Length of bytes object to use. An OverflowError is raised if the\n", " | integer is not representable with the given number of bytes.\n", " | byteorder\n", " | The byte order used to represent the integer. If byteorder is 'big',\n", " | the most significant byte is at the beginning of the byte array. If\n", " | byteorder is 'little', the most significant byte is at the end of the\n", " | byte array. To request the native byte order of the host system, use\n", " | `sys.byteorder' as the byte order value.\n", " | signed\n", " | Determines whether two's complement is used to represent the integer.\n", " | If signed is False and a negative integer is given, an OverflowError\n", " | is raised.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Class methods inherited from int:\n", " | \n", " | from_bytes(bytes, byteorder, *, signed=False) from builtins.type\n", " | Return the integer represented by the given array of bytes.\n", " | \n", " | bytes\n", " | Holds the array of bytes to convert. The argument must either\n", " | support the buffer protocol or be an iterable object producing bytes.\n", " | Bytes and bytearray are examples of built-in objects that support the\n", " | buffer protocol.\n", " | byteorder\n", " | The byte order used to represent the integer. If byteorder is 'big',\n", " | the most significant byte is at the beginning of the byte array. If\n", " | byteorder is 'little', the most significant byte is at the end of the\n", " | byte array. To request the native byte order of the host system, use\n", " | `sys.byteorder' as the byte order value.\n", " | signed\n", " | Indicates whether two's complement is used to represent the integer.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from int:\n", " | \n", " | denominator\n", " | the denominator of a rational number in lowest terms\n", " | \n", " | imag\n", " | the imaginary part of a complex number\n", " | \n", " | numerator\n", " | the numerator of a rational number in lowest terms\n", " | \n", " | real\n", " | the real part of a complex number\n", "\n" ] } ], "source": [ "help('True')" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "# Define some variables to show the values stored in variables can be changed from one type to another\n", "# Python is loosely typed\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## computation - operators and operands\n", "- **operators** are special tokens/symbols that represent computations like addition, multiplication and division \n", "- the values an operator uses are called **operands**\n", "- some binary operators that take two operands\n", " - addition: 10 + 20\n", " - subtraction: 20 - 10 \n", " - true division: 10 / 3 \n", " - integer division: 10 // 3 \n", " - remainder: 10 % 2\n", " - power: 2 ** 3" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# play with some examples of various operators supported by Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## order of operations\n", " depends on the rules of precedence: PEMDAS from high to low order
\n", "1. Parenthesis\n", "2. Exponentiation\n", "3. Multiplication and Division (left to right)\n", "4. Addition and Subtraction (left to right)\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "18\n" ] } ], "source": [ "# some examples\n", "print(2 * 3 ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## operations on string\n", "- Chapter 08 covers more on string data type" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class str in module builtins:\n", "\n", "class str(object)\n", " | str(object='') -> str\n", " | str(bytes_or_buffer[, encoding[, errors]]) -> str\n", " | \n", " | Create a new string object from the given object. If encoding or\n", " | errors is specified, then the object must expose a data buffer\n", " | that will be decoded using the given encoding and error handler.\n", " | Otherwise, returns the result of object.__str__() (if defined)\n", " | or repr(object).\n", " | encoding defaults to sys.getdefaultencoding().\n", " | errors defaults to 'strict'.\n", " | \n", " | Methods defined here:\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __format__(self, format_spec, /)\n", " | Return a formatted version of the string as described by format_spec.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(self, key, /)\n", " | Return self[key].\n", " | \n", " | __getnewargs__(...)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self int\n", " | \n", " | Return the number of non-overlapping occurrences of substring sub in\n", " | string S[start:end]. Optional arguments start and end are\n", " | interpreted as in slice notation.\n", " | \n", " | encode(self, /, encoding='utf-8', errors='strict')\n", " | Encode the string using the codec registered for encoding.\n", " | \n", " | encoding\n", " | The encoding in which to encode the string.\n", " | errors\n", " | The error handling scheme to use for encoding errors.\n", " | The default is 'strict' meaning that encoding errors raise a\n", " | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n", " | 'xmlcharrefreplace' as well as any other name registered with\n", " | codecs.register_error that can handle UnicodeEncodeErrors.\n", " | \n", " | endswith(...)\n", " | S.endswith(suffix[, start[, end]]) -> bool\n", " | \n", " | Return True if S ends with the specified suffix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | suffix can also be a tuple of strings to try.\n", " | \n", " | expandtabs(self, /, tabsize=8)\n", " | Return a copy where all tab characters are expanded using spaces.\n", " | \n", " | If tabsize is not given, a tab size of 8 characters is assumed.\n", " | \n", " | find(...)\n", " | S.find(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | format(...)\n", " | S.format(*args, **kwargs) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from args and kwargs.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | format_map(...)\n", " | S.format_map(mapping) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from mapping.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | index(...)\n", " | S.index(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found, \n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | isalnum(self, /)\n", " | Return True if the string is an alpha-numeric string, False otherwise.\n", " | \n", " | A string is alpha-numeric if all characters in the string are alpha-numeric and\n", " | there is at least one character in the string.\n", " | \n", " | isalpha(self, /)\n", " | Return True if the string is an alphabetic string, False otherwise.\n", " | \n", " | A string is alphabetic if all characters in the string are alphabetic and there\n", " | is at least one character in the string.\n", " | \n", " | isascii(self, /)\n", " | Return True if all characters in the string are ASCII, False otherwise.\n", " | \n", " | ASCII characters have code points in the range U+0000-U+007F.\n", " | Empty string is ASCII too.\n", " | \n", " | isdecimal(self, /)\n", " | Return True if the string is a decimal string, False otherwise.\n", " | \n", " | A string is a decimal string if all characters in the string are decimal and\n", " | there is at least one character in the string.\n", " | \n", " | isdigit(self, /)\n", " | Return True if the string is a digit string, False otherwise.\n", " | \n", " | A string is a digit string if all characters in the string are digits and there\n", " | is at least one character in the string.\n", " | \n", " | isidentifier(self, /)\n", " | Return True if the string is a valid Python identifier, False otherwise.\n", " | \n", " | Use keyword.iskeyword() to test for reserved identifiers such as \"def\" and\n", " | \"class\".\n", " | \n", " | islower(self, /)\n", " | Return True if the string is a lowercase string, False otherwise.\n", " | \n", " | A string is lowercase if all cased characters in the string are lowercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | isnumeric(self, /)\n", " | Return True if the string is a numeric string, False otherwise.\n", " | \n", " | A string is numeric if all characters in the string are numeric and there is at\n", " | least one character in the string.\n", " | \n", " | isprintable(self, /)\n", " | Return True if the string is printable, False otherwise.\n", " | \n", " | A string is printable if all of its characters are considered printable in\n", " | repr() or if it is empty.\n", " | \n", " | isspace(self, /)\n", " | Return True if the string is a whitespace string, False otherwise.\n", " | \n", " | A string is whitespace if all characters in the string are whitespace and there\n", " | is at least one character in the string.\n", " | \n", " | istitle(self, /)\n", " | Return True if the string is a title-cased string, False otherwise.\n", " | \n", " | In a title-cased string, upper- and title-case characters may only\n", " | follow uncased characters and lowercase characters only cased ones.\n", " | \n", " | isupper(self, /)\n", " | Return True if the string is an uppercase string, False otherwise.\n", " | \n", " | A string is uppercase if all cased characters in the string are uppercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | join(self, iterable, /)\n", " | Concatenate any number of strings.\n", " | \n", " | The string whose method is called is inserted in between each given string.\n", " | The result is returned as a new string.\n", " | \n", " | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\n", " | \n", " | ljust(self, width, fillchar=' ', /)\n", " | Return a left-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | lower(self, /)\n", " | Return a copy of the string converted to lowercase.\n", " | \n", " | lstrip(self, chars=None, /)\n", " | Return a copy of the string with leading whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | partition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string. If the separator is found,\n", " | returns a 3-tuple containing the part before the separator, the separator\n", " | itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing the original string\n", " | and two empty strings.\n", " | \n", " | replace(self, old, new, count=-1, /)\n", " | Return a copy with all occurrences of substring old replaced by new.\n", " | \n", " | count\n", " | Maximum number of occurrences to replace.\n", " | -1 (the default value) means replace all occurrences.\n", " | \n", " | If the optional argument count is given, only the first count occurrences are\n", " | replaced.\n", " | \n", " | rfind(...)\n", " | S.rfind(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | rindex(...)\n", " | S.rindex(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | rjust(self, width, fillchar=' ', /)\n", " | Return a right-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | rpartition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string, starting at the end. If\n", " | the separator is found, returns a 3-tuple containing the part before the\n", " | separator, the separator itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing two empty strings\n", " | and the original string.\n", " | \n", " | rsplit(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | Splits are done starting at the end of the string and working to the front.\n", " | \n", " | rstrip(self, chars=None, /)\n", " | Return a copy of the string with trailing whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | split(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | splitlines(self, /, keepends=False)\n", " | Return a list of the lines in the string, breaking at line boundaries.\n", " | \n", " | Line breaks are not included in the resulting list unless keepends is given and\n", " | true.\n", " | \n", " | startswith(...)\n", " | S.startswith(prefix[, start[, end]]) -> bool\n", " | \n", " | Return True if S starts with the specified prefix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | prefix can also be a tuple of strings to try.\n", " | \n", " | strip(self, chars=None, /)\n", " | Return a copy of the string with leading and trailing whitespace remove.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | swapcase(self, /)\n", " | Convert uppercase characters to lowercase and lowercase characters to uppercase.\n", " | \n", " | title(self, /)\n", " | Return a version of the string where each word is titlecased.\n", " | \n", " | More specifically, words start with uppercased characters and all remaining\n", " | cased characters have lower case.\n", " | \n", " | translate(self, table, /)\n", " | Replace each character in the string using the given translation table.\n", " | \n", " | table\n", " | Translation table, which must be a mapping of Unicode ordinals to\n", " | Unicode ordinals, strings, or None.\n", " | \n", " | The table must implement lookup/indexing via __getitem__, for instance a\n", " | dictionary or list. If this operation raises LookupError, the character is\n", " | left untouched. Characters mapped to None are deleted.\n", " | \n", " | upper(self, /)\n", " | Return a copy of the string converted to uppercase.\n", " | \n", " | zfill(self, width, /)\n", " | Pad a numeric string with zeros on the left, to fill a field of the given width.\n", " | \n", " | The string is never truncated.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | maketrans(x, y=None, z=None, /)\n", " | Return a translation table usable for str.translate().\n", " | \n", " | If there is only one argument, it must be a dictionary mapping Unicode\n", " | ordinals (integers) or characters to Unicode ordinals, strings or None.\n", " | Character keys will be then converted to ordinals.\n", " | If there are two arguments, they must be strings of equal length, and\n", " | in the resulting dictionary, each character in x will be mapped to the\n", " | character at the same position in y. If there is a third argument, it\n", " | must be a string, whose characters will be mapped to None in the result.\n", "\n" ] } ], "source": [ "help(str)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John islower False\n", "John isalpha True\n", "John upper JOHN\n", "000000John\n", "jOHN\n", "False\n", "['hello', 'world']\n", "['hello', 'world']\n" ] } ], "source": [ "# some examples\n", "name = \"John\"\n", "print(name, 'islower', name.islower())\n", "print(name, 'isalpha', name.isalpha())\n", "print(name, 'upper', name.upper())\n", "print(name.zfill(10))\n", "print(name.swapcase())\n", "print(name.startswith('j'))\n", "print(' hello world'.split())\n", "print('hello$world'.split('$'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## standard input\n", "- read data from standard or common input such as keyboards\n", "- allows your program to receive data during program execution facilitating user interactions" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your name? John\n" ] } ], "source": [ "name = input('What is your name? ')" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number =>100\n", "You entered: 100\n" ] } ], "source": [ "num = input('Enter a number =>')\n", "print('You entered: ', num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## composition\n", "- break a problem into many smallers sub-problems or steps using high-level algorithms\n", "- incrementally build the solution using the sub-problems or steps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### exercise\n", "\n", "write a program that finds area and perimeter of rectangle" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Demonstrate composition step by step\n", "# Algorithm steps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### excercise\n", "write a program that finds perimeter and area of a circle.

\n", "" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "# Demonstrate composition step by step\n", "# Algorithm steps" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.2" } }, "nbformat": 4, "nbformat_minor": 2 }