{"id":712,"date":"2022-02-22T18:13:55","date_gmt":"2022-02-22T23:13:55","guid":{"rendered":"https:\/\/molecularsciences.org\/content\/?p=712"},"modified":"2023-11-29T14:57:35","modified_gmt":"2023-11-29T19:57:35","slug":"python3-for-programmers","status":"publish","type":"post","link":"https:\/\/molecularsciences.org\/content\/python3-for-programmers\/","title":{"rendered":"Python3 for Programmers"},"content":{"rendered":"\n<p>This publication is for programmers who want to learn python. It is assumed that you know what variable, arrays, data structures, functions, etc. already are. You only need python&#8217;s syntax and tips for using them. So here, you will see more code and less explanation. If you are a programmer who only needs to fill in the blanks to become functional in python3, then you have come to the right place. If you need to learn programming, try googling &#8220;python for beginners&#8221;. There are many excellent free online sources to learn python. You don&#8217;t need to buy a book.<\/p>\n\n\n\n<p>The best way to learn from this booklet is to copy paste the code, run it, modify it, and understand it.<\/p>\n\n\n\n<p>python is:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>an interpreting language<\/li><li>a fully object-oriented language<\/li><li>dynamically typed<\/li><li>strongly typed<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"installing-and-running\">Installing and running<\/h3>\n\n\n\n<p>If you are using Linux, python3 is probably already installed on your system. Type the following to check:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>which python3<\/code><\/pre>\n\n\n\n<p>If you don&#8217;t have it installed, the command to install on Ubuntu is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt-get install python3\nsudo apt-get install python-pip3<\/code><\/pre>\n\n\n\n<p>On mac,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>brew install python3\nbrew install pip3<\/code><\/pre>\n\n\n\n<p>To check if the python3 and pip3 was installed,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>which python3\nwhich pip3<\/code><\/pre>\n\n\n\n<p>To run a python program, simply type python3 and the file you want to run.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python3 hello.py<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"variables\">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))<\/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<\/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'><\/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\" id=\"commandline-input\">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)<\/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<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"type-casting\">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))<\/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'>\n&lt;class 'int'><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"numeric-operators\">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<\/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<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"string-operations\">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<\/code><\/pre>\n\n\n\n<p>Output of the code is in comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"lists\">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]<\/code><\/pre>\n\n\n\n<p>Output is in the comments<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"tuple\">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()<\/code><\/pre>\n\n\n\n<p>Output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"set\">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()<\/code><\/pre>\n\n\n\n<p>Output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"dictionary\">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'])<\/code><\/pre>\n\n\n\n<p>The output is in the comments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"conditionals\">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 ({}) >= ({})'.format(a, b))<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a (100) &lt; b (200)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"loops\">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)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>red\ngreen\nblue<\/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)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>green\nblue<\/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<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>0\n1\n2<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"functions\">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\n\n\n<p>Python is a fully object-oriented programming language but it can also be used for scripting. It is assumed that you are already familiar with object-orientation concepts and have experience writing object-oriented code in another language. This page will show how to write object-oriented code in Python without explaining object-oriented concepts.<\/p>\n\n\n\n<p>The following class computes the area of a rectangle. Classes are defined with class keyword.&nbsp;<strong>init<\/strong>&nbsp;is the constructor. length and width are initialized in the constructor. Area is calculated by calcArea().<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># class definition\nclass Rectangle():\n\n   # constructor\n    def __init__(self, length, width):\n        self.length = length\n        self.width = width\n\n    # calculate area\n    def calcArea(self):\n        return self.length * self.width\n\n# run the code\nr = Rectangle(23, 32)\nprint(r.calcArea())       # output = 736<\/code><\/pre>\n\n\n\n<p>To use the class, we first create and object, r and then call r.calcArea() function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"inheritance\">Inheritance<\/h3>\n\n\n\n<p>Following example shows how to use inheritance in Python3.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Vehicle():\n\n    def __init__(self, make, model):\n        self.make = make\n        self.model = model\n\n    def __str__(self):\n        return self.make + \" \" + self.model\n\nclass Car(Vehicle):\n\n    def __init__(self, make, model, wheels):\n        Vehicle.__init__(self, make, model)\n        self.wheels = wheels\n\n    def __str__(self):\n        return Vehicle.__str__(self) + \" has \" + self.wheels + \" wheels\"\n\nv = Vehicle('Toyota','Corolla')\nprint(v)             \nm = Car('Toyota','Corolla','four')\nprint(m)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Toyota Corolla\nToyota Corolla has four wheels<\/code><\/pre>\n\n\n\n<p>Vehicle is the base class. Car is the subclass. Note that declaration of the class Car takes superclass name as input parameter. Also note the use of Vehicle.<strong>init<\/strong>&nbsp;in Car class to initialize superclass variables and the use of Vehicle.<strong>str<\/strong>(self) in the&nbsp;<strong>str<\/strong>&nbsp;method to print values from superclass.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"polymorphism\">Polymorphism<\/h3>\n\n\n\n<p>Polymorphism basically refers to the same method call doing different things for different subclasses. In the following example, seats() method returns different results based on which subclass is called. The property name in the super class is used by all subclasses.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Vehicle():\n    def __init__(self, name):\n        self.name = name\n\n    # abstract method\n    def seats(self):\n        raise NotImplementedError(\"Subclass must implement abstract method\")\n\nclass Sedan(Vehicle):\n    def seats(self):\n        return '4'\n\nclass Minivan(Vehicle):\n    def seats(self):\n        return '7'\n\nclass Motorbike(Vehicle):\n    def seats(self):\n        return '2'\n\nvehicles = &#91;Sedan('Tesla Model S'),\n            Minivan('Toyota Sedona'),\n            Motorbike('Harley Davidson')]\n\nfor vehicle in vehicles:\n    print(vehicle.name + ' has ' + vehicle.seats() + ' seats')<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Tesla Model S has 4 seats\nToyota Sedona has 7 seats\nHarley Davidson has 2 seats<\/code><\/pre>\n\n\n\n<p>In Python, you can handle errors with exceptions. The following code will generate an FileNotFound error because the file it is trying to open does not exist:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fh = open('data.txt')\nfor strline in fh.readlines():\n    print(strline)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FileNotFoundError: &#91;Errno 2] No such file or directory: 'data.txt'<\/code><\/pre>\n\n\n\n<p>An error is generated and the program stop executing. Suppose, we want to program to continue because we will compensate for this error later in the code. We can use try: except:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    fh = open('data.txt')\n    for strline in fh.readlines():\n        print(strline)\nexcept:\n    print('Error generated')\nprint('ignore and continue')<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Error generated\ncontinue regardless<\/code><\/pre>\n\n\n\n<p>If the code is try block generate an error, the action to be taken in response to this error is define in the except block. In this code, the error is caught is try and the action we defined is simply print and message and move one. If you come across this error while running a software, this error is not very helpful so let&#8217;s write a more useful error.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    fh = open('data.txt')\n    for strline in fh.readlines():\n        print(strline)\nexcept IOError as err:\n    print(\"Error generated in file open and print code: ({})\".format(err)) \nprint('ignore and continue')<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Error generated in file open and print code: (&#91;Errno 2] No such file or directory: 'data.txt')\nignore and continue<\/code><\/pre>\n\n\n\n<p>Python uses re library for regular expressions. re comes with standard python installation. Regular expressions is a very big topic. This page only covers the basics of how to search and substitute. The syntax for patterns is the same as Perl. Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import re\n\nline = \"apple banana carrot date eggplant fig guava\"\n\n# is there a match?\nif re.search(\"carrot\", line):\n    print('match found')\nelse:\n    print('match not found')\n\n# what was matched?\nmat = re.search(r'(.*) date (.*)', line)\nif mat:\n    print(mat.group())\n    print(mat.group(1))\n    print(mat.group(2))\nelse:\n    print('no')\n\n# how to match and substitute a substring\nres = re.sub(r'guava', \"grapefruit\", line)\nif res:\n    print(res)\nelse:\n    print('not substitution')<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>match found\napple banana carrot date eggplant fig guava\napple banana carrot\neggplant fig guava\napple banana carrot date eggplant fig grapefruit<\/code><\/pre>\n\n\n\n<p>First, we need to import re. The two function of re that we are interested in a re are search and sub. Search finds the substring (m\/\/ in Perl). sub finds and substitutes the substring with another (s\/\/\/ in Perl).<\/p>\n\n\n\n<p>Unit testing functionality is built into Python3. Following is a very simple example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def Arithmetic(a)\n    return a * a<\/code><\/pre>\n\n\n\n<p>Save this file as mycode.py. Save the following code as mycode_unittest.py<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import unittest\nfrom mycode import Arithmetic\n\nclass ArithmeticTest(unittest.TestCase):\n\n    def setUp(self):\n        self.arr1 = ((0,0),(1,1))\n        self.arr2 = ((1,2),(3,4))\n\n    def testCalculation(self):\n        for (i,val) in self.arr1:\n            self.assertEqual(Arithmetic(i), val)\n        for (i,val) in self.arr2:\n            self.assertNotEqual(Arithmetic(i), val)\n\n    def tearDown(self):\n        self.arr1 = None\n        self.arr2 = None\n\nif __name__ == \"__main__\": \n    unittest.main()<\/code><\/pre>\n\n\n\n<p>When you run the unit test code, you will not get any errors. Change assertEqual to assertNotEqual. Then you will get unit test failure.<\/p>\n\n\n\n<p>This page shows how to work with text files using Python3 code. Following is a sample txt file we will be using. Lets called it stocks.txt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bce.to\nhnd.to \nmtl.to<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"reading-from-file\">Reading from File<\/h3>\n\n\n\n<p>You can use read(), readline(), or readlines() function to read from a file. This example uses read()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>stocks = open(\"data\/stocks.txt\",\"r\")\nstocks.read()\nstocks.close()<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>'bce.to\\nhnd.to\\nmtl.to'<\/code><\/pre>\n\n\n\n<p><strong>Using readline():<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>stocks = open(\"data\/stocks.txt\",\"r\")\nstocks.readline()\nstocks.readline()\nstocks.close()<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bce.to\n\nhnd.to<\/code><\/pre>\n\n\n\n<p>Note that each readline() will print the next row in the file.<\/p>\n\n\n\n<p><strong>Using readlines():<\/strong>&nbsp;Note the plural readlines as opposed to readline.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>stocks = open(\"data\/stocks.txt\",\"r\")\nstocks.readlines()\nstocks.close()<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'bce.to\\n', 'hnd.to\\n', 'mtl.to']<\/code><\/pre>\n\n\n\n<p>readlines() outputs each row as a list element<\/p>\n\n\n\n<p><strong>Easy way to remove newlines<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>stocks = open(\"data\/stocks.txt\",\"r\")\nfor stocksymbol in stocks.read().splitlines():\n    print(stocksymbol)\nstocks.close()<\/code><\/pre>\n\n\n\n<p>output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bce.to\nhnd.to\nmtl.to<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"write-to-file\">Write to File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fh = open(\"data\/stocks.txt\", \"w\")\nnewstock = 'ta.to'\nfh.write(newstock)\nfh.close()<\/code><\/pre>\n\n\n\n<p>After you run the code, stocks.txt will contain<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ta.to<\/code><\/pre>\n\n\n\n<p>Your code overwrote the existing contents of the file. To append the text rather than overwriting, use the &#8220;a&#8221; option:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fh = open(\"data\/stocks.txt\", \"w\")\nnewstock = 'ta.to'\nfh.write(newstock)\nfh.close()<\/code><\/pre>\n\n\n\n<p>After you run the code, stocks.txt will contain<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bce.to\nhnd.to\nmtl.to\nta.to<\/code><\/pre>\n\n\n\n<p>NumPy is a python library that makes it easy to perform mathematical and logical operations on arrays. It provides high performance n-dimensional array object and tools to work with the arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"why-use-numpy-instead-of-a-python-list\">Why use numpy instead of a python list<\/h3>\n\n\n\n<ol class=\"wp-block-list\"><li>Takes less memory<\/li><li>Faster than python lists<\/li><li>More powerful<\/li><li>Easier to use<\/li><\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"what-is-my-numpy-version\">What is my numpy version<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import numpy as np\nprint (np.__version__)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1.9.3<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"creating-numpy-arrays\">Creating numpy arrays<\/h3>\n\n\n\n<p>There are many ways to create numpy arrays<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create arrays\navalues = &#91;12, 34, 45]\na = np.array(avalues)\nb = np.array(&#91;11.1,22.2,33.3])\n\n# 2D array, matrix\nc = np.array(&#91;(1, 2, 3), (4 , 5, 6)])\n\n# print results\nprint('a = ', a)              \nprint('b = ', b)               \nprint(c)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a =  &#91;12 34 45]\nb =  &#91; 11.1  22.2  33.3]\n&#91;&#91;1 2 3]\n &#91;4 5 6]] <\/code><\/pre>\n\n\n\n<p>Using arange() function to create arrays<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>d = np.arange(5)              # create array of 5 numbers starting from 0\ne = np.arange(9)+1            # create array of 9 numbers starting from 1\nf = np.arange(10, 20)         # array of numbers 10 to 19\ng = np.arange(10, 31, 5)      # array 10 to 30 with 5 increments\nh = len(np.arange(10,15))     # get size of array\ni = np.arange(10, 20).size    # get size of array\nj = np.arange(9).reshape(3,3) # create 2D array\n\n# print results\nprint('d = ', d)\nprint('e = ', e)\nprint('f = ', f)\nprint('g = ', g)\nprint('h = ', h)\nprint('i = ', i)\nprint(j)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>d =  &#91;0 1 2 3 4]\ne =  &#91;1 2 3 4 5 6 7 8 9]\nf =  &#91;10 11 12 13 14 15 16 17 18 19]\ng =  &#91;10 15 20 25 30]\nh =  5\ni =  10\n&#91;&#91;0 1 2]\n &#91;3 4 5]\n &#91;6 7 8]]<\/code><\/pre>\n\n\n\n<p>Using numpy function linspace()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>d = np.linspace(10, 20, 5)                # create elements with 2.5 intervals\ne = np.linspace(10, 20, 5, retstep=True)  # also shows the interval size\nprint(d)\nprint(e)\nprint(e&#91;1])                               # get the interval size<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; 10.   12.5  15.   17.5  20. ]\n(array(&#91; 10. ,  12.5,  15. ,  17.5,  20. ]), 2.5)\n2.5<\/code><\/pre>\n\n\n\n<p>Using zeros() and ones() functions<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = np.zeros(4)               # array of 4 zero elements\nb = np.ones(4)                # array of 4 one elements\nc = np.ones(5, dtype='int64') # create int64 array\nd = np.zeros((4,3))           # 4 x 3 matrix of zeros\ne = np.zeros((2,3,4))         # Two 3 x 4 matrices of zeros\nprint(a, \"\\n\", b, \"\\n\", c, \"\\n-----\\n\", d, \"\\n-----\\n\", e)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; 0.  0.  0.  0.] \n &#91; 1.  1.  1.  1.] \n &#91;1 1 1 1 1] \n-----\n&#91;&#91; 0.  0.  0.]\n &#91; 0.  0.  0.]\n &#91; 0.  0.  0.]\n &#91; 0.  0.  0.]] \n-----\n &#91;&#91;&#91; 0.  0.  0.  0.]\n  &#91; 0.  0.  0.  0.]\n  &#91; 0.  0.  0.  0.]]\n\n &#91;&#91; 0.  0.  0.  0.]\n  &#91; 0.  0.  0.  0.]\n  &#91; 0.  0.  0.  0.]]]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"array-type\">Array Type<\/h3>\n\n\n\n<p>A numpy array can only have one type. To find the type of an array,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(a.dtype)         # int64\nprint(b.dtype)         # float64<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type of a =  int64\ntype of b =  float64<\/code><\/pre>\n\n\n\n<p>Since every element of a numpy array must have the same data type, in the following example, int and float elements will be converted to complex numbers:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>tpl = (10, -1.23, 2+3j)\nc = np.array(tpl)\nprint(c)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91; 10.00+0.j  -1.23+0.j   2.00+3.j]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"using-arrays\">Using arrays<\/h3>\n\n\n\n<p>Working with 1D array<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = np.array(&#91;-3, -2, 0, 1, 2])\nprint(a)\nprint(a&#91;1])\na&#91;2] = 100\nprint(a)\nprint(a.size)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;-3 -2  0  1  2]\n-2\n&#91; -3  -2 100   1   2]\n5<\/code><\/pre>\n\n\n\n<p>Working with 2D array<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>b = np.arange(21)\nb.shape = (3, 7)\nprint(b)\nprint('-----')\nprint(b&#91;2])\nprint(b&#91;2,1])\nprint(b&#91;2]&#91;1])<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;&#91; 0  1  2  3  4  5  6]\n &#91; 7  8  9 10 11 12 13]\n &#91;14 15 16 17 18 19 20]]\n-----\n&#91;14 15 16 17 18 19 20]\n15\n15<\/code><\/pre>\n\n\n\n<p>Working with 3D array<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>c = np.arange(27)\nc.shape = (3,3,3)\nprint(c)\nprint('-----')\nprint(c&#91;0])\nprint('-----')\nprint(c&#91;0,1])\nprint('-----')\nprint(c&#91;0,1,2])\nprint('-----')\nc&#91;0,1,2] = 999\nprint(c)<\/code><\/pre>\n\n\n\n<p>output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;&#91;&#91; 0  1  2]\n  &#91; 3  4  5]\n  &#91; 6  7  8]]\n\n &#91;&#91; 9 10 11]\n  &#91;12 13 14]\n  &#91;15 16 17]]\n\n &#91;&#91;18 19 20]\n  &#91;21 22 23]\n  &#91;24 25 26]]]\n-----\n&#91;&#91;0 1 2]\n &#91;3 4 5]\n &#91;6 7 8]]\n-----\n&#91;3 4 5]\n-----\n5\n-----\n&#91;&#91;&#91;  0   1   2]\n  &#91;  3   4 999]\n  &#91;  6   7   8]]\n\n &#91;&#91;  9  10  11]\n  &#91; 12  13  14]\n  &#91; 15  16  17]]\n\n &#91;&#91; 18  19  20]\n  &#91; 21  22  23]\n  &#91; 24  25  26]]]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"arithmetic-operations-on-arrays\">Arithmetic operations on arrays<\/h3>\n\n\n\n<p>Note that numpy overloads operators operate differently on python arrays and numpy arrays.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># subtract all values\nprint(a - b)           # &#91;  0.9  11.8  11.7]\n# cube all values\nprint(a**3)            # &#91; 1728 39304 91125]\nprint(2 * np.cos(a))   # &#91;  1367.631  10941.048  36926.037]\nprint(a &lt; 30)          # &#91; True False False]\n# multiply values\nprint(a * b)           # &#91;  133.2   754.8  1498.5]\n# matrix product\nprint(a.dot(b))        # 2386.5<\/code><\/pre>\n\n\n\n<p>Output is in the code comments.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This publication is for programmers who want to learn python. It is assumed that you know what variable, arrays, data structures, functions, etc. already are. You only need python&#8217;s syntax and tips for using them. So here, you will see more code and less explanation. If you are a programmer who only needs to fill [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1239,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[203],"tags":[137],"class_list":["post-712","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python"],"_links":{"self":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/712","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=712"}],"version-history":[{"count":1,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/712\/revisions"}],"predecessor-version":[{"id":713,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/712\/revisions\/713"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media\/1239"}],"wp:attachment":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media?parent=712"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/categories?post=712"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/tags?post=712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}