top of page

SEARCH RESULTS

88 results found with an empty search

  • Python Data Types: A Quick Guide

    This article explains how to use Python's data types effectively to create scalable and maintainable applications. Alexander S. Ricciardi February 21th, 2024 Python offers a rich variety of data types that are fundamental to writing effective and efficient code. Understanding these data types is crucial for any developer, as it allows for proper data storage, manipulation, and retrieval. In this guide, we’ll explore common Python data types, their applications, and strategies for determining which data types to use in different scenarios.   A quick explanation of Python data types. First, Python offers a vast array of data types. The Python documentation provides detailed descriptions of each data type, and you can find the list at the following link:  Data Types . “Python also provides some built-in data types, in particular,  dict ,  list ,  set , and  frozenset ,  tuple . The  str  class is used to hold Unicode strings, and the  bytes  and  bytearray  classes are used to hold binary data” (Python Software Foundation (a), n.d., Data Type).  Built-in data types in Python are fundamental data structures that come standard with Python; you don't need to import any external library to use them. The table below shows Python's common data types. Table-1 Common Data Types Note: from  Programming in Python 3,  by Bailey, 2016.   Strategy for Determining Data Types To determine the data types needed for an application, it is crucial to analyze the data that needs to be collected and understand the application's functionality requirements. In general, this equates to these four key steps: Identifying the Data: identifying what types of data the application will collect and handle, such as textual information and numerical data. Understanding Data Operations: which operations will be performed on the data, such as sorting, searching, or complex manipulations, to ensure the chosen data types can support these functionalities. Structuring Data Relations: how different pieces of data relate to each other and deciding on the appropriate structures (e.g., nested dictionaries or lists) to represent these relationships efficiently. Planning for Scalability and Maintenance: future expansions or modifications to the application and selecting data types and structures that allow for modification, updates, and scalability. For this specific application, this translates to the following steps: Note that the information provided does not explicitly state whether the data needs to be manipulated (sorted or modified). However, for the application to be useful and functional, the data needs to be manipulated to some extent. Based on the information provided, the application functionality requirements are as follows: Storing Personal Information: storing basic personal information for each family member, such as names and birth dates. Address Management: manage and store current and possibly multiple addresses for each family member. Relationship Tracking: tracking and representing the relationships between different family members (e.g., parent-child, spouses, siblings). Data Manipulation: functionalities for editing, sorting, and updating the stored information, including personal details, addresses, and family relationships. Based on the information provided, the data that needs to be collected is as follows: Names: this includes names and family members' names are text data Birth dates: birth dates can be text data, numbers data, or a mix of both. Address: addresses can be complex, potentially requiring storage of multiple addresses per family member with components like street, city, state, and zip code. It is a mix of numbers and text data. Relationship: relationships between family members (e.g., parent-child, spouses, siblings) is text data. Four data elements and the corresponding data types Taking into account the application functionality requirements and data information the following are the four data elements and the corresponding data types. Names: the string data type str. This allows us to easily store and manipulate individual names. I will use a tuple to separate the first name and last name, name = (‘first_name’, ‘last_name’). Tuples are great in this case because they are immutable, meaning once a tuple is created, it cannot be altered ensuring that the integrity of first and last names is preserved. Additionally,  they are indexed meaning that they can be searched by index. For example, a list name tuple can be searched by last or first name. Furthermore, a tuple takes less space in memory than a dictionary or a list. Birth Dates: they could technically be stored as strings, integers, lists, or dictionaries, however utilizing the datetime.date object from Python's datetime module has significant advantages such as easy date manipulations and functionality. For example, calculating ages, or sorting members by their birth dates. In most cases storing birth dates, requires converting input strings into datetime.date objects. Note that datetime is a class. Additionally, in Python data types (floats, str, int, list, tuple, set, ...) are instances of the Python `object`. In other words, they are objects. A  datetime.date object utilizes the following data type : Year : An integer representing the year, e.g., 2024. Month : An integer representing the month, from 1 (January) to 12 (December). Day : An integer representing the day of the month, from 1 to 31, depending on the month and year.  For example: Note: the method date.fromisoformat() coverts strings into datetime.date () object with integer arguments. from datetime import date >>> date.fromisoformat('2019-12-04') datetime.date (2019, 12, 4) >>> date.fromisoformat('20191204') datetime.date (2019, 12, 4) >>> date.fromisoformat('2021-W01-1') datetime.date (2021, 1, 4) (Python Software Foundation (b), n.d., datetime - Basic date and time types ) Address: addresses have multiple components such as street, city, state, and zip code. I would use a dictionary data type dict . The dictionary key-value pair items structure is great for storing, modifying, and accessing the various parts of an address. Relationship: relationships between family members, such as parent-child, spouses, and siblings. I would use a dictionary data type dict with embedded List and tuple data types. In this structure, the keys represent the types of relationships, and the values are lists of names or identifiers referencing other family members. This would allow for easy storing, modifying, and accessing relationships data. Below is an example of what the Python code could be like:    from datetime import date user_123 = {     "name": ("John", "Doe"),  # Using tuple for the name     "birth_date": date(1974, 6, 5),  # Using datetime for birth dates     "address": {  # Using a dictionary for the address         "street": "123 My Street",         "city": "Mytown",         "state": "Mystate",         "zip_code": "12345"     },     "relationships": {  # Using a dictionary with embedded lists and tuples         "spouse": ("Jane", "Doe"),         "children": [("George", "Doe"), ("Laura", "Doe")],         "parents": [("Paul", "Doe"), ("Lucy", "Doe")],     } }   To create well-structured and maintainable applications in Python, it is essential to choose the right data types. To ensure your code is both efficient and scalable, it’s crucial to understand the differences between Python’s built-in data types—such as strings, tuples, dictionaries, and datetime objects—and to implement them effectively   References: Bailey, M. (2016, August). Chapter 3: Types,  Programming in Python 3.  Zyante Inc. Python Software Foundation (a). (n.d.). Data Type.  Python . python.org .  https://docs.python.org/3/library/datatypes.htmlLinks to an external site. Python Software Foundation (b). (n.d.). datetime - Basic date and time types   Python . python.org . https://docs.python.org/3/library/datetime.html

  • Key Criteria for Developing Python Functions

    This article discusses key criteria for developing Python functions, focusing on code reusability, complexity management, and testability. Alexander S. Ricciardi March 10th, 2024 In Python, you can either use a predefined function/method or write a user-defined function/method. In this discussion, provide at least three criteria that would be used to develop an appropriate method of your choice and the rationale behind selecting these criteria. Then give an example of your method declaration and return type. The three criteria that I consider when developing my functions/methods are as follows: Code reusability : When a block of code needs to be repeated multiple times in a program, the block of code is a good candidate to be modularized into a reusable function. This promotes DRY (Don't Repeat Yourself) code, a principal in software development whose goal is to reduce repetition (Schafer, 2015). DRY. The rationale behind Reusable functions is to make the code more modular, readable, and maintainable. Changes only need to be made in one place. Task complexity : If a task is made of many steps (code blocks), wrapping the task's steps in well-named functions makes the task more modular and hides complexity. The rationale is to reduce the tasks' readable complexity by hiding the details. In other words, the goal is to separate the "what" from the "how" making the code more understandable, readable, and maintainable. This is very useful for tasks with many steps and very complex logic. Code testability : Encapsuling code blocks in functions with clear inputs and outputs makes testing large programs easier to test. The rationale is that isolating code into functions with clear inputs and outputs enhances the program's robustness and maintainability by facilitating easier testing of the codebase. Considering these three criteria is key to creating a professional and high-quality codebase which, in the long run, saves time and reduces frustration not only for you but also for your ‘coding teammates.’This is particularly true when it comes to refactoring the code. “Refactoring, or code refactoring in full, is a systematic process of amending previously built source code, without introducing new functionalities or altering the fundamental workings of the subject software.” (Slingerland, 2023) Some of the actions that software development teams commonly take during refactoring include: Reducing the size of the code Restructuring confusing code into simpler code Cleaning up code to make it tidier  Removing redundant, unused code and comments  Doing away with unnecessary repetitions Combining similar code Creating reusable code Breaking up long functions into simpler, manageable bits  (Slingerland, 2023) Example: Here is a code example without functions and a code example with functions.The following program filters prime numbers from a list, and then checks if the square of the prime number are less than 50. No functions: num_lst = [2, 3, 4, 5, 6, 7, 8, 9, 10] squared_primes_less_than_50 = [] for n in num_lst: # Check if n is prime if n > 1: is_prime = True for i in range(2, int(n**0.5) + 1): if n % i == 0: is_prime = False break if is_prime: # Calculate square square = n**2 # Check if square is less than 50 if square < 50: squared_primes_less_than_50.append(square) print(squared_primes_less_than_50) With functions: def is_prime(n: int) -> bool: """ Check if a number is prime. :param n: Integer to check for primality :return: Boolean indicating if the number is prime """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def filter_primes(num_lst: list[int]) -> list[int]: """ Filter prime numbers from a list. :param num_lst: List of integers to filter :return: List of prime numbers from the input list """ return [n for n in num_lst if is_prime(n)] def square_numbers(num_lst: list[int]) -> list[int]: """ Square each number in a list. :param num_lst: List of integers to square :return: List of squared integers """ return [n**2 for n in num_lst] def squares_less_than(num_lst: list[int], threshold: int) -> list[int]: """ Filter numbers less than a specified threshold from a list. :param num_lst: List of integers to filter :param threshold: Threshold value for filtering :return: List of numbers from the input list that are less than the threshold """ return [n for n in num_lst if n < threshold] # --- Execute the program def main() -> None: """ Main function to execute the program logic. :param None: :return: None """ numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10] primes = filter_primes(numbers) squared_primes = square_numbers(primes) result = squares_less_than(squared_primes, 50) print(result) # --- Execute the program if __name__ == "__main__": main() Please see the functions' docstrings and hints for information about the return types. In summary, by applying the principles of reusability, complexity management, and testability, you can create a robust and scalable codebase that is easier to refactor and extend. This not only improves code quality but also makes maintenance and collaboration more efficient. References: Schafer, C. (2015, June 16). Programming terms: Dry (don’t repeat yourself) . YouTube. https://www.youtube.com/watch?v=IGH4-ZhfVDk&t=7s Slingerland, C. (2023, December 5). What is refactoring? 5 techniques you can use to improve your software. CloudZero. https://www.cloudzero.com/blog/refactoring-techniques/

  • Short-Circuit in Python's Compound Conditional Expressions

    This article explains how Python's short-circuit evaluation in compound conditional expressions enhances efficiency by stopping the evaluation as soon as the outcome is determined. Alexander S. Ricciardi February 25th, 2024 To understand the concept of short-circuiting in compound conditional expressions in Python, it is important to be familiar with the logical operators  and  and  or . The table below summarizes the logical outcomes for these operators. Table 1 The ‘and’ and ‘or’ Operators A B A  AND B A OR B False False False False False True False True True False False True True True True True Note:  From Module 3: Understanding Python decision control structure, ITS320: Basic Programming, by Colorado State University Global, 2024. Modified 2024, February 25. In Python, short-circuiting in the context of compounded conditional expressions is when the interpreter stops evaluating a logical expression as soon as the logical expression outcome is determined (Severance, 2016). In other words, when in the process of reading a logical expression, if the interpreter can determine the outcome of the expression before reaching the end of it, it would stop reading the expression.Note: the interpreter reads from left to right. This occurs when using the operators  and  and  or  in an expression. This is called a short-circuit boolean evaluation. (Hrehirchuk et al, 2024) For example: When using the and operator: a = 1 b = 2 c = 3 d = 4 if a < b and a > c and a < d:               #--- Do something Here the short-circuiting happens when the Python interpreter stops evaluating the logical expression  a < b and a > c and a < d  at step  a > c  because  a > c  returns  False . Consequently, the expression  a < b and a > c and a < d  is  False , it does not matter if the expression  a < d  returns  False  or  True . When using the  or  operator: a = 1 b = 2 c = 3 d = 4  if a > b or a < c or a > d:             #--- Do something Here the short-circuiting happens when the Python interpreter stops evaluating the logical expression  a > b or a < c or a > d  at step  a < c  because a < c returns  True . Consequently, the expression  a > b or a < c or a > d  is  True , it does not matter if the expression  a > d  returns  False  or  True . When using a combination of  and  and  or  logical operators, the and operator has precedent over the or operator. This is similar to the arithmetic operator precedence between '+' and '*', where '*' has precedence over '+'.The table below depicts the logical operators' precedence utilizing parentheses. Table 2 Precedence of Logical Operators A or B and C means A or (B and C) A and B or C and D means (A and B) or (C and D) A and B and C or D means ((A and B) and C) or D !A and B or C means ((!A) and B) and C Note : from Chapter 40 Boolean Expressions and Short-Circuit Operators - Precedence of Logical Operators, by Kjell, n.d. Modified 2024, February 25. In conclusion, short-circuiting occurs when the logical operators and and or determine when the Python interpreter stops evaluating an expression once the outcome is clear. For example, when the operator and is used it stops the evaluation at the first False and when the operator or is used it stops at the first True , this enhances efficiency. Therefore, understanding short-circuit evaluation in Python is crucial for writing efficient and effective conditional expressions.

  • Programming Fundamentals: The Power of Modular Development

    This article explores the essential components of programming, highlighting the importance of modular development in creating scalable, maintainable software applications. Alexander S. Ricciardi February 11th, 2024 What are the principal components involved in developing a program?     The principal components involved in developing an application are planning and analysis, design, implementation, testing, and maintenance. The process is cyclical, meaning that the components are treated as repeatable steps during the lifetime of the applications. This was not always the case, in the past most applications were sold on Compact Disks (CDs). Software maintenance was only accessible to businesses that could afford to have a team of programmers capable of maintaining (upgrading/updating) their software. This application development model was not accessible to individual users or smaller businesses. Today, most individual user applications are developed using a programming development cycle model. The following list outlines six components or steps involved in a programming development cycles model.   Analyze the problem or need: Understand the issue or need and decide on a programmatic solution. Design the program (logic): Use tools like flowcharts to visualize the program's flow. Code the program: Write the source code using a programming language. Debug the program (test): Identify and fix errors or "bugs" in the code. Formalize the solution: Ensure the program is ready for release and formalize documentation for understanding and future maintenance. Release and maintain the program. (Nguyen, 2019)   The word “cycles” is pluralized in the expression “programming development cycles” because the development steps can be repeated by section. For example, the steps ‘Code the program’ and ‘Debug the program’ can form a cyclic section of the development, meaning that after you debug the program you may need to recode the program and then debug it again.   The diagram below shows the cyclical nature of a programming development cycle model. Figure 1 Programming Development Cyclical Nature Note: From  Programming Development Cycles , by Nguyen, 2019.   Describe the benefits of breaking up a program into small modules and provide an example of an application that makes the most of one of these benefits.   Breaking up a program into small modules has several benefits such as readability, manageability, easier testing, reusability, and maintenance of code. Block-structured languages structurally implement what can be considered a low level of modulation for readability and functionality. For example, c and c++ use brackets {} to groups (modularized) and Python utilizes indentation for the same purpose (Klein, 2022). Object-oriented programming languages take it a step further by implementing classes that allow the creation of object instances that encapsulate both code and data allowing modulation of a program. I store my program classes in different files and directories. Additionally, importing libraries, for example, in c++ and Python is a form of modular programming.   Modular programming is:   “Modular programming is a general programming concept where developers separate program functions into independent pieces. These pieces then act like building blocks, with each block containing all the necessary parts to execute one aspect of functionality.” (Macdonald, 2023)   “Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.” (Busbee & Braunschweig, 2018)   The benefits of breaking up a program into small modules or modular programming can be listed as follows:   Readability: Modular code is easier to read and understand because it's divided into logical sections, each performing a distinct function. Manageability: Smaller, self-contained modules are easier to manage because changes in one module are less likely to impact others. Easier Testing: Modules can be tested independently, making it simpler to isolate and resolve defects. Reusability: Functions or classes defined in one module can be reused in other parts of the program or in future projects, saving development time. Maintenance: Updating a module for new requirements or fixing bugs is more straightforward when the application is modularized, enhancing long-term code maintenance. (Busbee, 2013)   In general, it is good practice to modularize your program small or large. Applications that benefit from modular programming are large-scale web applications. Large-scale web applications are complex systems. They need to handle a large and increasing number of users, higher loads of traffic, and an exponentially growing data pool. An example of a large-scale web application is an online retail platform, which needs to manage vast amounts of user and product data, process transactions securely, and scale dynamically (Struk, 2023). For large-scale web applications, modular programming combined with microservices architecture (a form of modulation that breaks up a program into separate services)  is crucial for manageability, efficiency, scalability, and maintainability.    A popular framework for web applications is React , it utilizes the concept of components as modules.   “In React, you develop your applications by creating reusable components that you can think of as independent Lego blocks. These components are individual pieces of a final interface, which, when assembled, form the application’s entire user interface.” (Herbert, 2023)   “React's component-based architecture allows you to create modular and reusable code that can help you scale your web application as your business grows. This makes React a great choice for developing large-scale applications that require maintainability, scalability, and flexibility.” (Hutsulyak, 2023) The modular development approach helps developers create software that is maintainable, scalable, and efficient. By breaking down complex applications into smaller, independent modules, developers can create systems that are easier to manage, test, and update. Whether you're working on a small project or a large-scale web application, utilizing modular programming will empower you to build more resilient and adaptable software solutions. References: Busbee, K. L. (2013, January 10). Programming Fundamentals - A Modular Structured Approach using C++. Internet Archive.   Busbee, K. L., & Braunschweig, D. (2018, December 15). Modular Programming. Programming Fundamentals. https://press.rebus.community/programmingfundamentals/chapter/modular-programming/   Herbert, D. (2023, November 13). What is react.js? uses, examples, & more. HubSpot Blog. https://blog.hubspot.com/website/react-js

bottom of page