Advertisement
Python253

function_demonstrator

Jun 6th, 2024
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.43 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: function_demonstrator.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This Python script demonstrates various common programming tasks through a user-friendly menu-driven interface.
  10.    - Users can interact with different functions, gaining hands-on experience and understanding of their functionality.
  11.    - Functions cover tasks from simple greetings to complex operations like string concatenation and numerical calculations.
  12.    - Presented in a menu driven format, users can explore and understand functions easily.
  13.    - This script serves as a valuable resource for learners and a reference for experienced programmers.
  14.    - The script offers a clear and intuitive interface, allowing users to navigate effortlessly and interact through prompts.
  15.    - It gracefully handles user input, ensuring a smooth experience even for those with minimal programming knowledge.
  16.    - No matter your programming skill level, this script offers an accessible way to engage with fundamental programming concepts.
  17.  
  18. Requirements:
  19.    - Python 3.x
  20.    - From typing module: (List, Optional, Dict, Tuple, Callable functions)
  21.    
  22. Functions:
  23.    - Greet:
  24.        Function with no arguments and no return value. Prints a greeting message.
  25.    - Display Message:
  26.        Function with arguments and no return value. Prints the given message.
  27.    - Add:
  28.        Function with arguments and a return value. Returns the sum of two numbers.
  29.    - Concat Strings:
  30.        Function with multiple argument types and a return value. Concatenates two strings.
  31.    - Sum List:
  32.        Function with a list argument and a return value. Returns the sum of all elements in the list.
  33.    - Find Element:
  34.        Function with a list argument and an optional target value. Finds the index of the target element in the list. Returns None if not found.
  35.    - Get Value:
  36.        Function with a dictionary argument and a return value. Returns the value associated with the key in the dictionary, or 0 if not found.
  37.    - Swap Values:
  38.        Function with a tuple argument and a return value. Swaps the two values in the tuple.
  39.    - Apply Function:
  40.        Function with a callable argument and two integer arguments. Applies the given function to the two integer arguments.
  41.    
  42. Usage:
  43.    - Run the script and choose an option from the displayed menu.
  44.    - Follow the prompts to interact with each function.
  45.    
  46. Example Output:
  47.  
  48.                _________________________
  49.  
  50.                   :: Function Menu ::
  51.                _________________________
  52.  
  53.                1. Greet
  54.                2. Display Message
  55.                3. Add
  56.                4. Concat Strings
  57.                5. Sum List
  58.                6. Find Element
  59.                7. Get Value
  60.                8. Swap Values
  61.                9. Apply Function
  62.                0. Exit
  63.                _________________________
  64.  
  65.                Choose an option: 4
  66.                _________________________
  67.  
  68.                    - Function with multiple argument types and a return value.
  69.                    - Concatenates two strings.
  70.                    
  71.                Enter first string:  this+
  72.                Enter second string: that
  73.  
  74.                Result: this+that
  75.  
  76. Additional Notes:
  77.    - For functions with optional arguments, if the argument is not provided, a default value or behavior is assumed.
  78.    - Ensure to input valid data types as required by each function to avoid errors.
  79. """
  80.  
  81.  
  82. from typing import List, Optional, Dict, Tuple, Callable
  83.  
  84. def greet() -> None:
  85.     """
  86.    - Function with no arguments and no return value.
  87.    - Prints a greeting message.
  88.    """
  89.     print("Hello, world!")
  90.  
  91. def display_message(message: str) -> None:
  92.     """
  93.    - Function with arguments and no return value.
  94.    - Prints the given message.
  95.    """
  96.     print(message)
  97.  
  98. def add(a: int, b: int) -> int:
  99.     """
  100.    - Function with arguments and a return value.
  101.    - Returns the sum of a and b.
  102.    """
  103.     return a + b
  104.  
  105. def concat_strings(a: str, b: str) -> str:
  106.     """
  107.    - Function with multiple argument types and a return value.
  108.    - Concatenates two strings.
  109.    """
  110.     return a + b
  111.  
  112. def sum_list(numbers: List[int]) -> int:
  113.     """
  114.    - Function with a list argument and a return value.
  115.    - Returns the sum of all elements in the list.
  116.    """
  117.     return sum(numbers)
  118.  
  119. def find_element(elements: List[int], target: int) -> Optional[int]:
  120.     """
  121.    - Function with an optional argument.
  122.    - Finds the index of the target element in the list. Returns None if not found.
  123.    """
  124.     try:
  125.         return elements.index(target)
  126.     except ValueError:
  127.         return None
  128.  
  129. def get_value(data: Dict[str, int], key: str) -> int:
  130.     """
  131.    - Function with a dictionary argument.
  132.    - Returns the value associated with the key in the dictionary, or 0 if not found.
  133.    """
  134.     return data.get(key, 0)
  135.  
  136. def swap_values(pair: Tuple[int, int]) -> Tuple[int, int]:
  137.     """
  138.    - Function with a tuple argument and a return value.
  139.    - Swaps the two values in the tuple.
  140.    """
  141.     return pair[1], pair[0]
  142.  
  143. def apply_function(f: Callable[[int, int], int], x: int, y: int) -> int:
  144.     """
  145.    - Function with a callable argument.
  146.    - Applies the given function to x and y.
  147.    """
  148.     return f(x, y)
  149.  
  150. # Print a separator line
  151. def line():
  152.     print("_" * 25)
  153.  
  154. def main():
  155.     while True:
  156.         line()                                                               # Print a separator line
  157.         print("\n   :: Function Menu ::")                                    # Print the menu title
  158.         line()
  159.         print("\n1. Greet")  
  160.         print("2. Display Message")
  161.         print("3. Add")  
  162.         print("4. Concat Strings")
  163.         print("5. Sum List")  
  164.         print("6. Find Element")
  165.         print("7. Get Value")  
  166.         print("8. Swap Values")
  167.         print("9. Apply Function")
  168.         print("0. Exit")
  169.        
  170.         line()
  171.         choice = input("\nChoose an option: ")                               # Prompt the user to choose an option
  172.         line()
  173.        
  174.         if choice == '1':
  175.             print()
  176.             print(greet.__doc__)                                             # Print the documentation for the greet function
  177.             print()
  178.             print("Result: ", end='')                                        # Print "Result: " without newline
  179.             greet()                                                          # Call the greet function
  180.             print()                                                          # Print a newline
  181.         elif choice == '2':
  182.             print()
  183.             print(display_message.__doc__)                                   # Print the documentation for the display_message function
  184.             print()
  185.             message = input("Enter a message: ")                             # Prompt the user to enter a message
  186.             print()
  187.             print(f"Result: {message}")                                      # Print the entered message
  188.             print()
  189.         elif choice == '3':
  190.             print(add.__doc__)                                               # Print the documentation for the add function
  191.             a = int(input("Enter first number:  "))                          # Prompt the user to enter the first number
  192.             b = int(input("Enter second number: "))                          # Prompt the user to enter the second number
  193.             print("\nResult:", add(a, b))                                    # Print the result of adding the two numbers
  194.         elif choice == '4':
  195.             print(concat_strings.__doc__)                                    # Print the documentation for the concat_strings function
  196.             first_string: str = input("Enter first string:  ")               # Prompt the user to enter the first string
  197.             second_string: str = input("Enter second string: ")              # Prompt the user to enter the second string
  198.             print("\nResult:", concat_strings(first_string, second_string))  # Print the result of concatenating the strings
  199.         elif choice == '5':
  200.             print(sum_list.__doc__)                                          # Print the documentation for the sum_list function
  201.                                                                              # Prompt the user to enter numbers
  202.             numbers = list(map(int, input("Enter numbers separated by space: ").split()))
  203.             print("\nResult:", sum_list(numbers))                            # Print the sum of the numbers
  204.         elif choice == '6':
  205.             print(find_element.__doc__)                                      # Print the documentation for the find_element function
  206.                                                                              # Prompt the user to enter numerical elements
  207.             elements = list(map(int, input("Enter numerical elements separated by space: ").split()))
  208.             target = int(input("Enter target element: "))                    # Prompt the user to enter the target element
  209.             result = find_element(elements, target)                          # Find the target element in the list
  210.                                                                              # Print the result of finding the element
  211.             print("\nResult:", "Element found at index " + str(result) if result is not None else "Element not found")
  212.         elif choice == '7':
  213.             print(get_value.__doc__)                                         # Print the documentation for the get_value function
  214.             data = {'a': 42, 'b': 69, 'c': 420}                              # Define a dictionary of numerical values
  215.             key = input("Enter key (a, b, or c): ")                          # Prompt the user to enter a key
  216.             print("\nResult:", get_value(data, key))                         # Print the value associated with the key in the dictionary
  217.         elif choice == '8':
  218.             print(swap_values.__doc__)                                       # Print the documentation for the swap_values function
  219.             x = int(input("Enter first value:  "))                           # Prompt the user to enter the first value
  220.             y = int(input("Enter second value: "))                           # Prompt the user to enter the second value
  221.             print("\nResult:", swap_values((x, y)))                          # Print the result of swapping the values
  222.         elif choice == '9':
  223.             print(apply_function.__doc__)                                    # Print the documentation for the apply_function function
  224.             x = int(input("Enter first number:  "))                          # Prompt the user to enter the first number
  225.             y = int(input("Enter second number: "))                          # Prompt the user to enter the second number
  226.             print("\nResult:", apply_function(add, x, y))                    # Print the result of applying the function to the numbers
  227.         elif choice == '0':
  228.             print("\n  Exiting...   GoodBye!")                               # Print an exit message
  229.             line()                                                           # Print a separator line
  230.             break
  231.         else:
  232.             print("Invalid choice. Please try again.")                       # Print an error message for invalid choices
  233.  
  234. if __name__ == "__main__":
  235.     main()
  236.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement