{"id":735,"date":"2022-02-24T14:12:13","date_gmt":"2022-02-24T19:12:13","guid":{"rendered":"https:\/\/molecularsciences.org\/content\/?p=735"},"modified":"2022-02-24T14:12:15","modified_gmt":"2022-02-24T19:12:15","slug":"python-basics","status":"publish","type":"post","link":"https:\/\/molecularsciences.org\/content\/python-basics\/","title":{"rendered":"Python Basics"},"content":{"rendered":"\n<p>This is a quick introduction to the basics of python programming language. It covers python3.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Variables<\/h3>\n\n\n\n<p>See the following program. Save as datatype.py:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = 100    # integer\nb = 1.23   # float\nc = \"python\"    # string\n\n# print variables\nprint(a)\nprint(b)\nprint(c)\n\n# convert int to float\nprint(float(100))         \n\n# convert float to int\nprint(int(3.14))\n\n# convert string to int\nd = \"12\"\ne = \"12.3\"\nprint(int(d))\n# print(int(e)) - this will generate an error\n\n# convert string to float\nprint(float(d))\nprint(float(e))\n\n# convert int to string\nf = str(12)\nprint(type(f))\n<\/code><\/pre>\n\n\n\n<p>To run<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>chmod 755 datatype.py\npython3 datatype.py\n<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>100\n1.23\npython\n100.0\n3\n12\n12.0\n12.3\n&lt;class 'str'&gt;\n<\/code><\/pre>\n\n\n\n<p>Casting between string, int, and float is very simple is python. Simply use int(), float(), or str() functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Commandline Input<\/h3>\n\n\n\n<p>To take commandline input:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>name = input(\"What is your name: \")\nprint(name)\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>What is your name:  mole\nmole\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Type casting<\/h3>\n\n\n\n<p>type() shows the data type. int() and float() casts to int and float, respectively.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>age = input(\"What is your age\")\nprint(type(age))\na = int(age)\nprint(type(a))\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>What is your age: 23\n&lt;class 'str'&gt;\n&lt;class 'int'&gt;\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Numeric Operators<\/h3>\n\n\n\n<p>See the example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(2 + 2 * 2 - 2)\nprint(5 \/ 2)    # float division\nprint(5 \/\/ 2)   # integer division\nprint(5 % 2)  # modulus\nprint(5 ** 2)  # exponent\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>4\n2.5\n2\n1\n25\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">String operations<\/h3>\n\n\n\n<p>The following example covers the most common string manipulations.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(\"hello\")\n\n# string vs character\nname = \"Justin\"                    # string\nachar = 'a'                        # character\n\n# str() function\naddress = str()                    # empty string\naddress = str(\"25 Sussex Drive\")   # create a list\n\n# substrings\nprint(name&#91;0])                     # J\nprint(name&#91;4:6])                   # in\nprint(name&#91;:4])                    # Just\nprint(name&#91;3:])                    # tin\nprint(name&#91;1:-1])                  # usti\n\n# does the substring exist in string\nprint(\"tin\" in name)               # True\nprint(\"xin\" in name)               # False\n\n# comparison\nprint(name == \"Justin\")            # True\nprint(name != \"Justin\")            # False\n\n# commonly used functions\nprint(len(name))                   # 6\nprint(max(name))                   # u\nprint(min(name))                   # J\nprint('--------------------')\n\n# ending strings, default is \\n\nprint(\"python\", end=\"\")            # end without \\n\nprint(\"python\", end=\"|\")           # end with |\nprint(\"\\n\")   # output for 3 lines # pythonpython|\n\n# does the string contain\ns1 = \"abc123\"                      # True\n# true if string contains alphanumeric characters only\nprint(s1.isalnum())                # True\n# digits only\nprint(\"123\".isdigit())             # True\n# lowercase English alphabet only\nprint(\"abc\".islower())             # True\n# uppercase English alphabet only\nprint(\"ABC\".isupper())             # True\n# whitespace characters only (space, \\t, \\n)\nprint(\"\\t\".isspace())              # True\n<\/code><\/pre>\n\n\n\n<p>Output of the code is in comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Lists<\/h3>\n\n\n\n<p>Lists can hold collection of values. The following example cover the common operations performed on lists.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># creating lists                   \na = list()         # empty list    # &#91;]\nb = &#91;1,2,3]                        # &#91;1, 2, 3]\nc = list(&#91;\"python\",\"programming\"]) # &#91;'python', 'programming']\n# without &#91;], each character becomes a separate element in the list\nd = list(\"python\")                 # &#91;'p', 'y', 't', 'h', 'o', 'n']\n\nprint(a)\nprint(b)\nprint(c)\nprint(d)\n\n# accessing list elements, indexing begins at 0\nprint(b&#91;1])                        # 2\n\n# concatenating lists\ne = &#91;4,5,6]\nf = b + e\nprint(f)                           # &#91;1, 2, 3, 4, 5, 6]\n\n# replicating a list\ng = b * 2\nprint(g)                           # &#91;1, 2, 3, 1, 2, 3]\n\n# using a for loop\nfor i in b:\n    print(i, end=\" \")              # 1 2 3\n\n# list functions\nprint(1 in b)                      # True\nprint(4 not in b)                  # True\nprint(len(b))                      # 3\nprint(max(b))                      # 3\nprint(min(b))                      # 1\nprint(sum(b))                      # 6\n\n# inserting values in list\nb.append(4)\nprint(b)                           # &#91;1, 2, 3, 4]\nb.extend(e)\nprint(b)                           # &#91;1, 2, 3, 4, 4, 5, 6]\nb.insert(3,22)\nprint(b)                           # &#91;1, 2, 3, 22, 4, 4, 5, 6]\n\n# taking values out of list\nb.pop()\nprint(b)                           # &#91;1, 2, 3, 22, 4, 4, 5]\nb.remove(4)\nprint(b)                           # &#91;1, 2, 3, 22, 4, 5]\n\n# sort and reverse the list\nb.reverse()\nprint(b)                           # &#91;5, 4, 22, 3, 2, 1]\nb.sort()\nprint(b)                           # &#91;1, 2, 3, 4, 5, 22]\n<\/code><\/pre>\n\n\n\n<p>Output is in the comments<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Tuple<\/h3>\n\n\n\n<p>A tuple is an immutable list. Once created, it cannot be modified.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = ()                              \nb = (1, 2, 3)                      \nc = &#91;4, 5, 6]\nd = tuple(c)\ne = tuple(\"python\")\nprint(a)                           # ()\nprint(b)                           # (1, 2, 3)\nprint(d)                           # (4, 5, 6)\nprint(e)                           # ('p', 'y', 't', 'h', 'o', 'n')\n\n# substrings\nprint(b&#91;0:2])                      # (1, 2)\n\n# does a value exist in the tuple\nprint(2 in b)                      # True\nprint(5 not in b)                  # True\n\n# basic functions\nprint(len(b))                      # 3\nprint(sum(b))                      # 6\nprint(min(b))                      # 1\nprint(max(b))                      # 3\n\n# looping through tuple\nfor i in b:\nprint(i, end=\" \")              # 1 2 3\nprint()\n<\/code><\/pre>\n\n\n\n<p>Output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Set<\/h3>\n\n\n\n<p>A set is an unordered collection on unique elements. Following example shows how to create and manipulate sets:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create set\na = {'perl', 'php', 'python'}\nprint(a)          # {'python', 'perl', 'php'}\n\nb = lang.copy()\nprint(b)          # {'python', 'perl', 'php'}\n\n# add element to set\na.add('java')\nprint(a)          # {'python', 'perl', 'java', 'php'}\n\n# difference between 2 sets\nprint(a.difference(b))    # {'java'}\n\n# discard element from set, no error for missing element\n# discard element from set, generate error for missing element\nb.discard('php')\nb.remove('perl')\nprint(b)          # {'python'}\n\n# elements present in both sets\nprint(a.intersection(b))  # {'python'}\n\n# return true for null intersection, false otherwise\nprint(a.isdisjoint(b))    # False\n\n# is b a subset of a?\nprint(b.issubset(a))      # True\nprint(a.issubset(b))      # False\n\n# is b a superset of a?\nprint(b.issuperset(a))      # False\nprint(a.issuperset(b))      # True\n\n# empty set\nb.clear()\nprint(b)          # set()\n<\/code><\/pre>\n\n\n\n<p>Output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Dictionary<\/h3>\n\n\n\n<p>A dictionary is an associated array. See the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create dictionary\nemptydict = {}                     \nprint(emptydict)                   # {}\n\nemergency = {\n    'Canada' : '911',\n'Switzerland' : '112'\n}\nprint(emergency)                   # {'Canada': '911', 'Switzerland': '112'}\n\n# retrieve and element\nprint(emergency&#91;'Canada'])         # 911\n\n# add an element \nemergency&#91;'Seychelles'] = '999'\nprint(emergency)    \n# {'Canada': '911', 'Seychelles': '999', 'Switzerland': '112'}\n\n# delete an element\ndel emergency&#91;'Seychelles']\nprint(emergency)                   # {'Canada': '911', 'Switzerland': '112'}\n\n# length of dictionary\nprint(len(emergency))              # 2\n\n# in and not in operators\nprint('Canada' in emergency)       # True\nprint('USA' not in emergency)      # True\n\n# empty the dictionary\ndeleteme = {\n'useless' : 'information'      \n}\nprint(deleteme)                        # {'useless' : 'information'}\ndeleteme.clear()                   \nprint(deleteme)                        # {}\n\n# find key\nprint(emergency.get('Canada','not found'))  # 911\nprint(emergency.get('USA','not found'))     # not found\n\n# get all keys or values\nprint(emergency.keys())            # dict_keys(&#91;'Switzerland', 'Canada'])\nprint(emergency.values())          # dict_values(&#91;'112', '911'])\n<\/code><\/pre>\n\n\n\n<p>The output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conditionals<\/h3>\n\n\n\n<p>Python supports if-else conditions. See code below<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a, b = 100, 200\nif a &lt; b:\n    print('a ({}) &lt; b ({})'.format(a, b))\nelse:\n    print('a ({}) &gt;= ({})'.format(a, b))\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a (100) &lt; b (200)\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Loops<\/h3>\n\n\n\n<p>Python uses while and for loops. Python for loops are similar to foreach loop in PHP. See code below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># loop through entire array\ncolor = &#91;'red','green','blue']\nfor i in color:\n    print(i)\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>red\ngreen\nblue\n<\/code><\/pre>\n\n\n\n<p>Loop through part of the array<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>color = &#91;'red','green','blue']\n\n# skip first element\nfor i in color&#91;1:]:\n    print(i)\n\n# only last 2 elements\nfor i in color&#91;-2:]:\n    print(i)\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>green\nblue\n<\/code><\/pre>\n\n\n\n<p>Using while loop<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>count = 0 \nwhile (count &lt; 3):\n    print(count)\n    count += 1\n<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>0\n1\n2\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Functions<\/h3>\n\n\n\n<p>Python functions are defined by def. Once again, indentation, not {}, are used to define blocks. See code below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def xply(m,n):\n    return m * n\n\nprint(xply(32,54))    # output = 1728<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This is a quick introduction to the basics of python programming language. It covers python3. Variables See the following program. Save as datatype.py: To run Output Casting between string, int, and float is very simple is python. Simply use int(), float(), or str() functions. Commandline Input To take commandline input: output Type casting type() shows [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[203],"tags":[137],"class_list":["post-735","post","type-post","status-publish","format-standard","hentry","category-python","tag-python"],"_links":{"self":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/735","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/comments?post=735"}],"version-history":[{"count":1,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/735\/revisions"}],"predecessor-version":[{"id":736,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/735\/revisions\/736"}],"wp:attachment":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media?parent=735"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/categories?post=735"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/tags?post=735"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}