Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: function_demonstrator.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This Python script demonstrates various common programming tasks through a user-friendly menu-driven interface.
- - Users can interact with different functions, gaining hands-on experience and understanding of their functionality.
- - Functions cover tasks from simple greetings to complex operations like string concatenation and numerical calculations.
- - Presented in a menu driven format, users can explore and understand functions easily.
- - This script serves as a valuable resource for learners and a reference for experienced programmers.
- - The script offers a clear and intuitive interface, allowing users to navigate effortlessly and interact through prompts.
- - It gracefully handles user input, ensuring a smooth experience even for those with minimal programming knowledge.
- - No matter your programming skill level, this script offers an accessible way to engage with fundamental programming concepts.
- Requirements:
- - Python 3.x
- - From typing module: (List, Optional, Dict, Tuple, Callable functions)
- Functions:
- - Greet:
- Function with no arguments and no return value. Prints a greeting message.
- - Display Message:
- Function with arguments and no return value. Prints the given message.
- - Add:
- Function with arguments and a return value. Returns the sum of two numbers.
- - Concat Strings:
- Function with multiple argument types and a return value. Concatenates two strings.
- - Sum List:
- Function with a list argument and a return value. Returns the sum of all elements in the list.
- - Find Element:
- 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.
- - Get Value:
- Function with a dictionary argument and a return value. Returns the value associated with the key in the dictionary, or 0 if not found.
- - Swap Values:
- Function with a tuple argument and a return value. Swaps the two values in the tuple.
- - Apply Function:
- Function with a callable argument and two integer arguments. Applies the given function to the two integer arguments.
- Usage:
- - Run the script and choose an option from the displayed menu.
- - Follow the prompts to interact with each function.
- Example Output:
- _________________________
- :: Function Menu ::
- _________________________
- 1. Greet
- 2. Display Message
- 3. Add
- 4. Concat Strings
- 5. Sum List
- 6. Find Element
- 7. Get Value
- 8. Swap Values
- 9. Apply Function
- 0. Exit
- _________________________
- Choose an option: 4
- _________________________
- - Function with multiple argument types and a return value.
- - Concatenates two strings.
- Enter first string: this+
- Enter second string: that
- Result: this+that
- Additional Notes:
- - For functions with optional arguments, if the argument is not provided, a default value or behavior is assumed.
- - Ensure to input valid data types as required by each function to avoid errors.
- """
- from typing import List, Optional, Dict, Tuple, Callable
- def greet() -> None:
- """
- - Function with no arguments and no return value.
- - Prints a greeting message.
- """
- print("Hello, world!")
- def display_message(message: str) -> None:
- """
- - Function with arguments and no return value.
- - Prints the given message.
- """
- print(message)
- def add(a: int, b: int) -> int:
- """
- - Function with arguments and a return value.
- - Returns the sum of a and b.
- """
- return a + b
- def concat_strings(a: str, b: str) -> str:
- """
- - Function with multiple argument types and a return value.
- - Concatenates two strings.
- """
- return a + b
- def sum_list(numbers: List[int]) -> int:
- """
- - Function with a list argument and a return value.
- - Returns the sum of all elements in the list.
- """
- return sum(numbers)
- def find_element(elements: List[int], target: int) -> Optional[int]:
- """
- - Function with an optional argument.
- - Finds the index of the target element in the list. Returns None if not found.
- """
- try:
- return elements.index(target)
- except ValueError:
- return None
- def get_value(data: Dict[str, int], key: str) -> int:
- """
- - Function with a dictionary argument.
- - Returns the value associated with the key in the dictionary, or 0 if not found.
- """
- return data.get(key, 0)
- def swap_values(pair: Tuple[int, int]) -> Tuple[int, int]:
- """
- - Function with a tuple argument and a return value.
- - Swaps the two values in the tuple.
- """
- return pair[1], pair[0]
- def apply_function(f: Callable[[int, int], int], x: int, y: int) -> int:
- """
- - Function with a callable argument.
- - Applies the given function to x and y.
- """
- return f(x, y)
- # Print a separator line
- def line():
- print("_" * 25)
- def main():
- while True:
- line() # Print a separator line
- print("\n :: Function Menu ::") # Print the menu title
- line()
- print("\n1. Greet")
- print("2. Display Message")
- print("3. Add")
- print("4. Concat Strings")
- print("5. Sum List")
- print("6. Find Element")
- print("7. Get Value")
- print("8. Swap Values")
- print("9. Apply Function")
- print("0. Exit")
- line()
- choice = input("\nChoose an option: ") # Prompt the user to choose an option
- line()
- if choice == '1':
- print()
- print(greet.__doc__) # Print the documentation for the greet function
- print()
- print("Result: ", end='') # Print "Result: " without newline
- greet() # Call the greet function
- print() # Print a newline
- elif choice == '2':
- print()
- print(display_message.__doc__) # Print the documentation for the display_message function
- print()
- message = input("Enter a message: ") # Prompt the user to enter a message
- print()
- print(f"Result: {message}") # Print the entered message
- print()
- elif choice == '3':
- print(add.__doc__) # Print the documentation for the add function
- a = int(input("Enter first number: ")) # Prompt the user to enter the first number
- b = int(input("Enter second number: ")) # Prompt the user to enter the second number
- print("\nResult:", add(a, b)) # Print the result of adding the two numbers
- elif choice == '4':
- print(concat_strings.__doc__) # Print the documentation for the concat_strings function
- first_string: str = input("Enter first string: ") # Prompt the user to enter the first string
- second_string: str = input("Enter second string: ") # Prompt the user to enter the second string
- print("\nResult:", concat_strings(first_string, second_string)) # Print the result of concatenating the strings
- elif choice == '5':
- print(sum_list.__doc__) # Print the documentation for the sum_list function
- # Prompt the user to enter numbers
- numbers = list(map(int, input("Enter numbers separated by space: ").split()))
- print("\nResult:", sum_list(numbers)) # Print the sum of the numbers
- elif choice == '6':
- print(find_element.__doc__) # Print the documentation for the find_element function
- # Prompt the user to enter numerical elements
- elements = list(map(int, input("Enter numerical elements separated by space: ").split()))
- target = int(input("Enter target element: ")) # Prompt the user to enter the target element
- result = find_element(elements, target) # Find the target element in the list
- # Print the result of finding the element
- print("\nResult:", "Element found at index " + str(result) if result is not None else "Element not found")
- elif choice == '7':
- print(get_value.__doc__) # Print the documentation for the get_value function
- data = {'a': 42, 'b': 69, 'c': 420} # Define a dictionary of numerical values
- key = input("Enter key (a, b, or c): ") # Prompt the user to enter a key
- print("\nResult:", get_value(data, key)) # Print the value associated with the key in the dictionary
- elif choice == '8':
- print(swap_values.__doc__) # Print the documentation for the swap_values function
- x = int(input("Enter first value: ")) # Prompt the user to enter the first value
- y = int(input("Enter second value: ")) # Prompt the user to enter the second value
- print("\nResult:", swap_values((x, y))) # Print the result of swapping the values
- elif choice == '9':
- print(apply_function.__doc__) # Print the documentation for the apply_function function
- x = int(input("Enter first number: ")) # Prompt the user to enter the first number
- y = int(input("Enter second number: ")) # Prompt the user to enter the second number
- print("\nResult:", apply_function(add, x, y)) # Print the result of applying the function to the numbers
- elif choice == '0':
- print("\n Exiting... GoodBye!") # Print an exit message
- line() # Print a separator line
- break
- else:
- print("Invalid choice. Please try again.") # Print an error message for invalid choices
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement