- LPU MCA Semester 1
- CAB106
- Unit 6
CAB106 · Unit 6: Application development using OOP
Menu-driven applications, best coding practices and code documentation
11 practice questions
Key points
- Menu loops read a choice, act, and repeat until quit
- PEP 8: snake_case, CapWords and UPPER_CASE
- A docstring is the first string in a body and fills __doc__
- Type hints are not enforced at run time
A menu-driven application shows options in a loop, reads a choice with input(), runs the matching action and repeats until the user chooses to quit (break). Unknown choices should be handled, not crash the program. A dictionary that maps choices to functions, such as {"+": add, "-": sub}, is cleaner than a long if/elif chain, and dict.get(key, default) supplies a fallback for missing keys. Validate input with try/except ValueError plus extra range checks, and prefer a class (for example Cart) to hold the program's state.
Best practices follow PEP 8: snake_case for functions and variables, CapWords for classes, UPPER_CASE for constants, four-space indentation and meaningful names. Keep functions small and focused, avoid magic numbers by using named constants, and handle expected errors with exceptions. Type hints (a: int) document intent but are not enforced at run time.
Documentation: a string literal placed as the first statement of a function, class or module is its docstring, stored in __doc__ and shown by help(). A string placed after other statements is not a docstring. Comments with # explain why, and should not repeat what the code says.
Exam trap: type hints do not stop wrong types, and a docstring must be the first statement of the body.
Try two questions
Where must a docstring be placed so that it becomes the function's documentation?
- On the line above def, written as a # comment
- At the end of the function, after its last statement
- In a separate text file that has the same name
- As the first statement inside the function body
Show the answer
D. Only a string literal that is the very first statement of the body is stored as __doc__.
Why not A: A comment is ignored and never becomes __doc__.
Why not B: A string after other statements is just an unused expression.
Why not C: Python does not read documentation from a separate file.
Which practice best supports readable code?
- Short one-letter names so that every line stays compact
- Meaningful names and small functions that each do one thing
- One long function that handles the whole menu at once
- Comments that repeat each line of code in plain words
Show the answer
B. Clear names and focused functions make code easier to read, test and change.
Why not A: Meaningless names hide the purpose of the code.
Why not C: A long function is hard to test and understand.
Why not D: Repeating the code in comments adds noise and goes out of date.