it:python

Python language

Python scripts and modules

  • Python code is written in text files and given an extension .py
  • Most python code files are “modules” which are designed to be imported into other python files and are NOT designed to be ran
  • Other python code files are “scripts” which are designed to be ran by a user and these generally call a number of modules by first importing them
    • script files can be run from the MSDOS command prompt:
      • eg. python3 yourscriptfile.py
      • python3 hello.py » output.txt will output the results into a text file called output.txt
    • in Windows, when Python has been installed and made the default app to run a .py file, you can just call yourscriptfile.py at the command prompt
    • scripts can also be ran in apps such as:
      • PyCharm - is a code editor specifically designed for Python coding with a ToDo list by using # todo comments
        • you need to download Community Edition and install it then set the Anaconda environment so it can find the environment's python file
      • MS Visual Studio Code
  • When developing or testing code, you often write the code in cell blocks within Jupyter notebooks and these are saved as .ipynb files which need to be opened in Jupyter

Language basics

  • Python is partly derived from Pascal including naming conventions but it is case sensitive!
  • most things (variables, objects, functions, etc) are lower case with words within the name separated by underscore for readability
  • Classes are usually typed with a capital letter at start of each word part of the class name and don't use the underscores
  • Hyperparameters are usually fully upper case to show that the user can change these values
  • X tensor inputs are generally uppercase X, with y labels remaining lower case y
  • documentation string style guide:
    • # comments out remainder of that line (similar to double forward slash in Delphi or double hyphen in SQL)
    • 3 double quotes at start and end of multi-line section comments out that section (similar to { and } in Delphi)
  • formatted strings
    • print(f“Print this variable to 2 decimal places followed by new line: {variablename:.2f} /n—-”) # /n creates new lines of number of hypens

data types, variables, operators

  • numbers can be written with underscore as thousands separator (eg 5_439 = 5439)
  • variables can be declared automatically without a var or a type
  • variable type conversions are int(), float(), str(), bool() - must be True or False (not true or false)
  • thus, birth_year = int(input('Type your year of birth' )) will prompt user for a string and then int will convert this into an integer and place it in the birth_year variable
  • arithmetic operands include +,-,asterix,/,two forward slashes (returns the integer component of the result only), % (modulus), two asterixes (exponential)
  • x += value is same as x = x + value
  • strings are zero-based - ie. first character is at zero, one can surround the string with either ' or “ however, if you are using apostrophes inside the string then you must bind with ” instead hence “It's a hot day” and 'It is a hot day' will both work
  • string methods include find(''), replace('repl','new'), upper(), etc
  • format string eg. print(f'({x},{y})') will output the values for x and y as (x,y)
  • can multiply a string
  • can split a string containing words into a list of those words via list_of_words = string_of_words.split(' ') as the space is the separator between words
  • one can get a boolean with 'subst' in input('Type your year of birth' ) - this uses the in command
    • other boolean result comparative operands include >, >=, <, ⇐, ==, !=
  • logical operators: and, or, not,

if statements and loops

  • if statements line ends with a colon not a then and then the code to run starts as indented new lines - to terminate the if statement start a new line and remove the indent with Shift-Enter (ie. there is no begin end clauses)
    • use elif condition: at the start of a new line without indentation to create an else if block of code
    • use else: to start an else block
  • while condition: - is used for a while loop block
  • for loop block

complex types

  • list is represented by square brackets with comma delimited and are zero based
    • list_of_names = [“name1”, “name2”] then can find the first one with list_of_names[0] and strangely, can find the last one with list_of_names[-1]
    • to return a section of elements in a list use list_of_names[startIndex:endIndex] (but endIndex does not include the endIndex item)
    • list methods include append, insert(index, value), remove(index), clear(), len(list_of_names) returns the number of items in the list, pop() removes last item
    • note that “if not list_of_names” then this means list is empty
    • can use for item in list_of_names: to iterate through each element (which is accessed as item) which is much more abbreviated than doing so with a while blocks which would require:
      • i = 0
      • while i < len(list_of_names):
        • i = i + 1
  • sets
    • these are non-indexed unsorted lists with no duplicates and are designated by { }
    • thus numberlist = [1,4,4,6,7] uniques = set(numberlist) which will return {1,4,6,7}
    • set1 | set2 gives a union of the two sets
    • set1 & set2 gives the intersection of the two sets
    • set1 - set2 gives the difference between the two sets
    • set1 ^ set2 gives the items in each of the two sets but not in both
  • range() function
  • range(startnumber,endnumber,step) will then give a list of numbers from startnumber to endnumber -1 (if no startnumber is provided zero is used, if no step is used the step = 1)
    • as with list you can use a for loop to extract the items
  • tuples
  • represented by curved brackets and are immutable (unchangeable once created) lists
  • methods are count and index only
  • unpacking
  • instead of individually allocating values from a list or tuple to variables, they can be done in one line as: x,y,z = yourlist
  • dictionaries
  • this is similar to a record in Delphi and a great for mapping values including emoji converters which is akin to using case statements in Delphi
  • used to store key value pairs however cannot duplicate a keyname for a key pair within the dictionary and keynames are case sensitive
     
    customer = {
      "name": "John"
      "age": 20
      }
  • access a key pair value via customer[“keyname”] or to avoid a keyerror if keyname does not exist, use customer.get(“keyname”) and if doesn't exist returns None or you can return a default value if it doesn't exist by using customer.get(“keyname”, defaultvalue)
  • assign a value via customer[“keyname”] = keyvalue
  • eg. translate a user input message to emoji:
      message = input(">")
      words = message.split(' ')
      emojis = {
        ":)" = smiley emoji font,
        ":(" = sad emoji font
      }
      output = ""
      for word in words:
        output += emojis.get(word, word) + " " # use word as default as not found in emoji list so use the original word user typed 

functions

  • Python functions equate to both function and procedures in Delphi
  • create a function via:
    • def function_name():
      • function code is indented then at end of code is followed by two line breaks for better readability
  • cannot call a function prior to it being defined so the definition must precede the code which calls it
  • parameters
    • can pass positional argument(s) or keyword arguments to function parameter(s) as a local variable via def function_name(paramName1, paramName2):
    • keyword arguments
      • instead of relying upon strict positional arguments which must match the position of the function parameters, one can use keyword arguments:
        • function_name(paramname2 = arg2, paramname1 = arg1) which avoids having to check the positions in the function and in complex functions can improve readability
        • if using both types of arguments, then the keyword arguments MUST follow the positional arguments
  • return values
    • default return value is None
    • can return a value from a function as follows:
      def functionname(paramname):
        return paramname * 24 

handling exceptions

  • error types
    • ValueError
    • ZeroDivisionError
    • AttributeError (when objects do not have an attribute that has been referenced)
  • successful running of code gives exit code = 0 anything else crashes the program so to prevent a crash, handle the error to ensure you end up with exit code = 0
    try:
      indented code
    except errortype:
      print(yourErrorMessage) 
  • comments
  • # starts comment line

classes

  • used to define new types to model new concepts and add new methods
  • class names should be capitalised and words should not be joined by underscores but each word in the name is capitalised
  • classes are defined as below:
    class Point:
      def move(self):
        indented method code
      def draw(self):
        indented method code
      # definition is terminated with two line breaks 
  • create an object of that class, you do not explicitly need creation and freeing as per Delphi, nor do they need properties to be defined but are used as follows:
    • point1 = Point()
    • point1.x = 10 #note this property does not need to be defined in the class definition constructor but can be automatically defined in your object but cannot be referenced until the property has been created either in this manner or via the definition constructor otherwise you get a AttributeError exception!
  • constructors
    • add a constructor to a class definition via:
      def __init__(self, paramnamevalue1, paramnamevalue2):
        # constructor code such as:
        self.paramName1 = paramvalue1
        self.paramName2 = paramvalue2 
    • thus if we change ParamName1 to X and paramName2 to Y and paramvalue1 to X and paramvalue2 to Y in the above code, we can create a object and set these values at creation via:
      • point2 = Point(10,7)
  • inheritance
  • when defining a class one can inherit from another class simply by referencing that class as follows:
    class OakTree(Tree):
      pass #this allows you to not have any additional code as you can't leave this blank and have an empty class

modules

  • Python code files which have extension .py
  • to use in code in either way by importing them (in Delphi you would just add to the Uses clause):
    import module_name # do not use the file extension here
    module_name.module_function() # use a function 
    from module_name import module_function # this just imports a function (or could be a class) and allows direct reference to function without need to reference module_name
    module_function() # use a function 
  • packages
    • collection of modules within a file system folder which contains a file named
       __init__.py
    • to import a module within a package
      import package_name.module_name 
      package_name.module_name.module_function()
      from package_name import module_name 
      module_name.module_function()
      from package_name.module_name  import module_function1(), module_function2()
      module_function1()
  • built-in modules and functions
    • these will be located under the External Libraries folder then Python subfolder
    • there is no need to use a package_name for built-in standard Python modules hence:
      import random
      your_list = [list1,list2,list3]
      for i in range(3):
        print(random.random() ) # generates random decimal between 0 and 1
        print(random.randint(1,100) ) # generates random integer between 1 and 100
      print(random.choice(your_list) #gives random item from your list

files and directories

from  pathlib import Path
path = Path() # this will reference the current folder
path = Path("foldername") # this will reference a relative folder
path.exists()
path.mkdir() # creates the folder
path.rmdir() # deletes the folder
for file in  path.glob('*') 
  print(file) # lists the contents of the folder
for file in path.glob('*.py')
  print(file)  # lists the python files in  the folder

Pypi and pip

  • Pypi = Python Package Index of available Python packages go to https://pypi.org/ and search for what you need
  • to install a package:
    • $pip install packagename
  • these will install in a folder under ExternalLibraries\site-packages

Example manipulating an Excel spreadsheet

  • need to install openpyxl package first
import openpyxl as xl
from openpyxl.chart import BarChart, Reference

wb = xl.load_workbook("spreadsheetfilename")
sheet = wb['Worksheetname'] #case sensitive!
cell = sheet['a1'] # this will also give same result: cell = sheet.cell(1,1)
print(cell.value)
for row in range(1,sheet.max_row + 1)
  cell = sheet.cell(row, 3) #get 3rd cell column
# now add a chart:
values = Reference(sheet,min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) #skip 1st row as contains column titles and only use data in column 4
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'e2') #places chart upper left corner at e2
wb.save('newfilename')

commonly used basic Python libraries

it/python.txt · Last modified: 2024/01/16 03:30 by gary1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki