ICTPRG435 - Session 1: Introduction to Scripting and Python

Overview: This session introduces software and scripting concepts, coding standards, development platforms and IDEs, and core Python fundamentals (variables, types, functions, recursion, operators, and decision-making). A practical student activity (data type detector) is included.

This session focuses on:

Software

Software is a set of instructions, data, or programs used to run a computer and perform specified activities. In layman's terms, the software instructs a computer on how to operate. It's a catch-all phrase for applications, scripts, and programs that operate on devices like PCs, mobile phones, tablets, and other smart gadgets. In contrast to software, hardware refers to the physical components of a computer that do the job.

Most computers would be useless without software. A web browser, for example, is a software application that allows people to connect to the Internet. An operating system (OS) is software that acts as a bridge between other applications and hardware on a computer or mobile device. TCP/IP is a protocol incorporated into all major operating systems that allow computers to communicate over long-distance networks.

Most software is created in high-level programming languages, which are more human-readable than machine-language. A compiler or interpreter converts the high-level language into low-level machine code that the computer can understand. A low-level assembly language can also be used to write software, but it is less prevalent.

Types of software (concise)

There are various types of software, this includes application software, system software, programming software, and driver software

Software Expectations

The software application requirements of any company may vary greatly depending on the type of project, the wants and wishes of the business and technical stakeholders, and the organisation's business analysis.

The expectation is that software applications:

It is vital to discuss your software expectations with the appropriate personnel, and there are many ways to do this. Listed below are the most common.

Scripting languages

A scripting language is typically executed by a runtime environment (interpreted languages) rather than translated ahead-of-time (compiled languages)into native machine code. Scripting languages are often used for automation, glue code, web pages, system administration, plugins, and rapid prototyping.

Whereas a compiled language compiles (transforms) the entire source code directly into machine code, an interpreted language translates the source code one statement at a time into the language understood by the computer’s processor.

To understand the difference between a compiled and an interpreted programming language we will consider the following analogy. Imagine you purchased a garden shed which came disassembled in a box with the instructions required to assemble it. Now imagine the instructions were written in a foreign language. As you don’t understand the foreign language you can:

Important nuance: "Interpreted" vs "compiled" is a simplification - many modern implementations compile source to an intermediate form (bytecode) and then execute it (for example CPython compiles to bytecode then runs it on a virtual machine). The conceptual difference is how and when translation happens.

Scripting languages are written for a run-time environment to provide functionality to applications and communicate with other programming languages.

There are numerous scripting languages, some of which are presented below:

This course focuses on Python.

Python Characteristics

  1. Easy to Code: Despite being a relatively advanced programming language, Python is simple to learn. Python coding may be learned by anyone in a matter of hours or days. It can take some more time to fully understand all of Python's complex concepts, packages, and modules. However, compared to other well-known languages like C, C++, and Java, understanding the fundamentals of Python syntax is quite simple.
  2. Easy to Read: Python code resembles everyday English terms. The code block is defined by the indentations rather than by semicolons or brackets. Simply by glancing at the code, you can determine what it is designed to perform.
  3. Free and Open-Source: Python is created under an open-source license that has been accepted by OSI. Because of this, using it is totally free, even for profit. Python can be downloaded and used in applications without costing anything. Additionally, it may be freely changed and distributed again. On the Python website, you can download Python.
  4. Robust Standard Library: Anyone can utilise the vast standard library for Python. In contrast to other programming languages, this implies that programmers don't have to write code for everything. There include libraries for databases, unit testing, expressions, image manipulation, and many more features. There are thousands of additional components in addition to the standard library, all of which may be found in the Python Package Index.
  5. Interpreted: Programming languages that are interpreted execute the source code line by line rather than all at once. Because C++ and Java are not interpreted, they must first be compiled in order to be used. Python does not require compilation because the interpreter processes it at runtime.
  6. Portable: The same code can be used on several machines, making Python portable. Let's say you use a Mac to write Python programs. You don't need to modify it if you subsequently decide to run it on Windows or Linux. As a result, it is unnecessary to build a software more than once for different platforms.
  7. Object-Oriented and Procedure-Oriented: If a programming language centres development around data and objects rather than functions and logic, it is considered object-oriented. A programming language is instead procedure-oriented if it emphasises functions more than other concepts (code that can be reused). The fact that Python facilitates both object-oriented and procedure-oriented programming.
  8. Extensible: If a programming language can be expanded to other languages, it is said to be extensible. Python is a very expandable language since code may be written in other languages like C++.
  9. Expressive: Python just requires a small amount of code to complete challenging tasks. For instance, entering print("Hello World") displays the phrase. More lines would be needed for this to run in languages like Java or C.
  10. Support for GUI: Support for the Graphical User Interface, or GUI, is one of the most important features of any programming language. A GUI makes it simple for a user to interact with the software. Python has a number of toolkits, such as Tkinter, wxPython, and JPython, which make it simple to construct graphical user interfaces.
  11. Dynamically Typed: The type of the variable must be declared prior runtime in many programming languages. The type of a variable can be chosen at runtime in Python. Python is now a dynamically typed language as a result. You don't need to write int x = 20 if you have to assign the integer value 20 to the variable x, for instance. All you have to do is type x = 15.
  12. High-level Language: Python is a high-level programming language because it frees programmers from memory management and system design requirements. This makes it incredibly developer-friendly and is a fundamental Python feature.
  13. Simplify Complex Software Development: Python may be used to create sophisticated scientific and numerical applications on the desktop, the web, and other platforms. Python's data analysis tools make it easier and faster to develop unique big data solutions. To show data in a more visually attractive manner, you may also utilise the Python data visualization packages and APIs. Python is used by a number of highly skilled software engineers to complete complex AI and natural language processing jobs.
  14. Other Advanced Programming Features: Python contains several advanced programming features such as generators (used to create iterators with a different approach than most other languages) and list comprehensions (used to create new lists from other iterables). Python also has automatic memory management, eliminating the need to manually allocate and free memory in the code.

Additional notes: Python is one of the most popular languages today; rankings vary by metric and audience. Implementations such as CPython, PyPy and Jython exist for different use cases.

Python GUI toolkits (short)

Common GUI toolkits include Tkinter (standard), PyQt/PySide, PySimpleGUI, and wxPython. Jython is a Python implementation that runs on the JVM (useful for Java interoperability).

Coding standards

Standards provide specifications, procedures and guidelines that endeavour to ensure levels of consistency, reliability and safety are incorporated into products and services developed, this includes software development. Standards are set by the industry and organisation developing the product or service to ensure consistency and quality.

Code standards are the rules and guidelines developers follow to create cleaner, readable and well-structured highly functional code with minimal coding errors. Coding standards:

PEP 8 is the canonical style guide for Python. Follow it to improve readability and maintainability. Common tools that help enforce and apply standards:

The Australian Cyber Security Centre provides guidelines for software development. For more information on these guidelines visit: Government Software Development Guideline

Software Development Platforms

What is an SDP? A Software Development Platform gives developers access to an integrated environment containing the tools required to develop, test, deploy, and maintain software applications.

Stages of Software Development and Example Tools

Stage Purpose Example Tools / SDP Features
Plan Organise and manage work Jira, Trello, Asana, issue-tracking boards
Develop Write and manage code Cloud or local IDEs (VS Code, IntelliJ), Git, GitHub, GitLab, Version Control Tools
Build Compile and prepare software Build pipelines, Maven, Gradle, Jenkins
Test Ensure software quality Unit/integration testing (JUnit, PyTest), Selenium, SonarQube
Deploy Release software to users CI/CD pipelines, Docker, Kubernetes, Ansible
Monitor & Maintain Track performance and issues Grafana, Prometheus, ELK Stack (Elasticsearch/Logstash/Kibana), CloudWatch

Examples of Complete SDPs

An SDP may not include every tool directly, but it integrates everything developers need across the full software lifecycle.

Note: Software development platforms are different to integrated development environments. IDE usually is just a part of SDP.

Integrated Development Environments

An integrated development environment (IDE) is application development software that incorporates common developer tools into a single graphical user interface (GUI). An IDE is often made up of the following components:

  • Source code editor: A text editor that can help you write software code by highlighting syntax with visual clues, giving language-specific auto-completion, and detecting problems as you type.
  • Local build automation: Utilities that automate simple, repeated operations such as converting computer source code into binary code, packaging binary code, and running automated tests as part of building a local version of the software for usage by the developer.
  • Debugger: A program that can graphically display the location of a bug in the original code and is used to test other programmes.
  • IDE for Python Scripting Language

    There are numerous IDEs available for Python, a few of the most popular ones are listed below.

    IDLE is the default editor that comes with Python, but we will not use it in this course.

    For this course we will use Thonny as it is more beginner friendly.

    Thonny - Python IDE

    Quick overview: Thonny is a beginner-friendly Python IDE that includes a small debugger, variable inspector and built-in themes. You can use the regular installer or a portable ZIP for Windows if you prefer not to install system-wide.

    Note: If you opt for a portable version, install it on a fastest media (like SSD, not USB stick), as it affects the speed of the IDE.

    Download & portable version (Windows)

    1. Go to the official site: thonny.org and choose the installer for your OS.
    2. For a portable Windows copy (no installer): download the **windows portable ZIP** from the Thonny releases. Extract the ZIP and run thonny.exe. This keeps Thonny self-contained.
    3. If you use the portable build, create a desktop shortcut to thonny.exe for convenience.

    Open Options / Preferences

    Windows/Linux: Tools → Options… macOS: Thonny → Preferences…

    This is the central place for editor, theme and debugger configuration.

    Set recommended maximum line length

    1. Open Tools → Options → Editor.
    2. Look for Recommended maximum line length (a dropdown) - set it to your preferred value (e.g. 80). Thonny will draw a thin guide line at that column to remind you about PEP8 limits.

    Change colour theme & font

    1. Open Tools → Options → Theme & Font.
    2. Under UI theme select Light / Dark (changes overall UI widgets).
    3. Under Syntax theme choose a syntax colouring scheme for the editor and shell (e.g. Dracula, One Dark, Tomorrow, etc.). You can install extra themes/plugins via Tools → Manage plug-ins… and then choose the installed theme from this tab.
    4. Change the editor font and font size on the same page. Restart Thonny if prompted for the new theme to apply fully.

    Enable the Variables pane (inspect variables while running)

    1. Open: View → Variables. This opens the Variables sidebar where global and local variables appear when your program runs or when you use the debugger.
    2. Run your script or use the debugger (Ctrl+F5 / Debug) to populate the Variables view — variables appear only when they exist in memory (for example while the program is running or paused in the debugger).
    3. Tip: If you want richer variable visualisation (hierarchical or graphical), consider the thonny-data-visualization plug-in which adds extra Views under the View menu after installation. To do this:
      • Navigate to "Tools" in the Thonny menu and select "Manage plug-ins."
      • In the search box, enter thonny-data-visualization and press Enter.
      • Install the plug-in.
      • After this you should see Globals and locals variables, Hierarchical data view and Graphical data view in the View menu.

    Useful shortcuts

    Introduction to Python

    As expressed earlier, Python is a multi-paradigm programming language which supports both functional and object-oriented programming paradigms. It is used in a wide variety of applications and is currently the most popular programming language among developers.

    Basic Data Types

    Python provides several built-in basic data types to represent different kinds of values. The most fundamental ones include:

    Variables

    Variables are names that reference values. Examples:

        a = 10 # int
        b = 5.5 # float
        c = "Hello" # str
        d = True # bool
                    

    In the example above:

    Use type() to inspect a value's type at runtime, and print() to display results. E.g., print(type(b))

    Naming rules

    Note: Variable names are case-sensitive for example pet, Pet and PET are different variables.

    Arithmetic operators

    Arithmetic operators are used with numeric values to perform mathematical calculations:

    Comparison operators

    Decision making

    The Python if statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is True.

    A simple if statement is presented below:

        a = 200
        b = 100
        if a == b:
            print("a and b are equal")
        if a != b:
            print("a is not equal to b") # Result: a is not equal to b
                

    An elif and or an else may be used with an if statement. The elif keyword is used to evaluate a condition if the previous if condition or conditions were not True.

        a = 200
        b = 100
        if a > b:
            print("a is greater than b")  # Result: a is greater than b
        elif a < b:
            print("a is less than b")
                

    The else will catch anything which isn't caught by the preceding if and or elif conditions.

        a = 200
        b = 100
        if a > b:
            print("a is greater than b")  # Result: a is greater than b
        elif a < b:
            print("a is less than b")
        else:
            print("a and b are equal")
                

    Functions

    A Python function is a reusable block of code that performs a given task. Although Python provides many built-in functions such as print() and type(), it also allows us to create our own functions, these are referred to as user-defined functions. User-defined functions names should be lowercase, with words separated by underscores, this improves readability.

    
        # The def keyword is used to define the function.
        def my_function():
            print("Hello")
    
        # Calling the function.
        my_function()
        # Result: Hello            
                

    Arguments can be passed to functions. We will expand on our example to demonstrate this.

    
        # The text1 and text2 parameters accepts the arguments.
        def my_function(text1, text2):
            print("Hello", text1, "I enjoy", text2)
    
        # Passing two arguments to the function.
        my_function("World", "Programming")
        # Result: Hello World I enjoy Programming            
                

    Parameters may contain default values. The default value assigned to the lang parameter is Python.

    
        def language_message(lang="Python"):
            result = "I program in " + lang
            return result
    
        print(language_message()) # Result: I program in Python
        print(language_message("Perl")) # Result: I program in Perl
                    

    A well-structured function should return a value. The Python return statement is a key component of functions and methods which is used to exit the function and go back to the place from where it was called. It is the return statement which makes a function more versatile and reusable. The example below demonstrates a function being used again and again.

    
        def my_function(num1, num2):
            result = num1 + num2
            return result
    
        print(my_function(10,5))    # Result: 15
        print(my_function(8,8))     # Result: 16
        print(my_function(58,51))   # Result: 109
        print(my_function(10,12))   # Result: 22
                    
                    

    Recursion (brief)

    Recursion allows a function to call itself. Always ensure a base case exists to stop recursion, otherwise you'll hit the recursion limit.

    
        def adder(n):
            if n == 0:
                return 0
            else:
                return n + adder(n - 1)
    
        print(adder(5)) # 15
                    

    Recursion is elegant for some problems (e.g. tree traversal, mathematical definitions), but iterative solutions may be clearer or more efficient in other cases.

    Student activity - Data type detector

    You are required to develop a program which evaluates a variable data type and prints a message identifying the data type.

    Note: The incomplete .py file (data_type_check.py) required for the activity is presented below and is located under the Session 1 Files heading on the resources page: Resources

    Task: Your task is to download the .py file (data_type_check.py) and complete the check_type() function which determines if the argument that is passed to the function is an integer, a float, a string or a Boolean.

    Requirements

    1. Function must accept one argument.
    2. The function must return an appropriate message indicating the data type, for example:
      • If the data type is an integer, the function will return: Data type is Integer.
      • If the data type is a float, the function will return: Data type is Float.
      • If the data type is a string, the function will return: Data type is String.
      • If the data type is a Boolean, the function will return: Data type is Boolean.
      • If the data type cannot be determined, the function will return: Data type unknown.
    3. Do not use external libraries.
    4. The function must use the if, elif and else statements. Hint: There are multiple elif statements required.
    
        def check_type():
            # put your code here
    
        
        # Example usage
        a = 10
        b = 5.5
        c = "Hello"
        d = True
        e = [1, 2, 3, 4, 5]
    
    
        print(check_type(a)) # Result: Data type is Integer.
        print(check_type(b)) # Result: Data type is Float.
        print(check_type(c)) # Result: Data type is String.
        print(check_type(d)) # Result: Data type is Boolean.
        print(check_type(e)) # Result: Data type unknown.
                    

    Resources & recommended reading

    Practical tips for students

    Local and Global scope

    The following video demonstrates the meaning of local and global scope. Scope is about which variables in your programs can "see" other variables. In short, variables inside functions can "see" global variables, but global variables cannot "see" inside functions. There are exceptions to this idea and the video tries to explain them. Buy and large, try to avoid global variables where possible because it makes your code harder to maintain. At watch the first half of this video. The complete URL is given so you can follow the link in case the embedded video does not work on your system.