Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import namedtuple
- import numpy as np
- # read more about numpy
- # sentinel
- # read more about the use of it
- # https://python-patterns.guide/python/sentinel-object/
- EXIT = object()
- TERM = object()
- def main():
- # main loop
- while True:
- result = menu()
- if result is EXIT:
- # here he exits
- print('Exit!')
- break
- elif result is TERM:
- # same here
- # just to show that you can handle different
- # sentinel objects
- print('TERM!')
- break
- # no exit
- print_result(result)
- # still in loop
- def print_result(result):
- print()
- print('=======')
- print('Result:')
- print(result)
- print()
- def get_option(last_index):
- while True:
- try:
- option = int(input("Please choose and option: "))
- except ValueError:
- print('Invalid value.')
- continue
- if not (1 <= option <= last_index):
- print('Value is not in menu')
- continue
- return option
- def menu():
- """
- This is not the best implementation.
- """
- for index, entry in enumerate(option_mapping, start=1):
- print(f'{index:<2d}. {entry.text}')
- # using index, which is the last value
- # yes, for-loops leaks
- last_index = index
- # hint, Python indicies starts with 0
- option = get_option(last_index) - 1
- # print('Option:', option)
- entry = option_mapping[option]
- if entry.function is EXIT:
- return EXIT
- elif entry.function is TERM:
- return TERM
- return entry.function()
- def array_2by2():
- """
- I was too lazy to find a better function
- to create a 2by2 matrix.
- 2x2 matricies are used for 2d graphics
- 3x3 for 3d
- 4x4 for translation matrix in 3d space
- https://en.wikipedia.org/wiki/Rotation_matrix
- """
- # to create an array with zeros with a 2 by 2 shape
- # np.zeros((2, 2))
- # np.ones((2,2))
- return np.arange(1, 5).reshape((2,2))
- def square_value():
- # numpy arrays support broadcast multiplication
- # you can do also matrix multiplacation
- # dot product, cross product, etc.
- return array_2by2() ** 2
- def add_3():
- """
- Functions should have alsways a doctstring
- Here array_2by2 is called and 3 is added to the result.
- The result returns
- """
- return array_2by2() + 3
- def multiply_by5():
- return array_2by2() * 5
- # mapping must be defined after the functions has been created
- # if you change the order, you get a NameError
- menu_entry = namedtuple("Entry", "function text")
- option_mapping = (
- menu_entry(array_2by2, "Create a 2-by-2 Array"),
- menu_entry(square_value, "Square Value"),
- menu_entry(add_3, "Add 3 to Elements"),
- menu_entry(multiply_by5, "Multiply Elements"),
- menu_entry(EXIT, "Exit"),
- menu_entry(TERM, "Terminate"),
- )
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement