PromptBase
Upgrade
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
(r1)
Token size
255
Example input
[e.g. Python]: Python [e.g. 3.11]: 3.11 [Insert your code here]: def add_contact(name, number, contact_list = {}): if not name or not number: print("Name and number cannot be empty") return contact_list{name} = number return contact_list def get_contact(name, contact_list): if name in contact_list: return contact_list{name} else: return "Contact not found" def main(): my_contacts = add_contact("Alice", "12345") add_contact("Bob", "", my_contacts) add_contact("", "54321", my_contacts) print(get_contact("Alice", my_contacts)) print(get_contact("Charlie", my_contacts)) main()
Example output
### Code Review for Python 3.11 #### 1. **Summary** The code implements a simple contact management system with functions to add and retrieve contacts. Key operations: - `add_contact`: Adds a name/number pair to a dictionary (with validation). - `get_contact`: Retrieves a contact by name or returns a "not found" message. - `main`: Demonstrates usage by adding valid/invalid contacts and querying results. --- #### 2. **Language Context** Python 3.11-specific considerations: - Default mutable arguments (e.g., `contact_list={}`) are dangerous due to shared state. - Dictionary operations use `[]` for access/assignment (curly braces `{}` are invalid syntax). - Type hints (PEP 484) are recommended for clarity in modern Python. --- #### 3. **Detected Issues** **Issue 1: Syntax Error in Dictionary Operations** - **Lines 4 & 9**: `contact_list{name}` - **Problem**: Invalid dictionary syntax. Python uses `[]` for item access/assignment, not `{}`. - **Risk**: Code fails at runtime with `SyntaxError`. **Issue 2: Mutable Default Argument** - **Line 1**: `contact_list = {}` in `add_contact` - **Problem**: Default mutable arguments persist across calls, causing unintended shared state. For example: ```python a = add_contact("Alice", "123") # Works b = add_contact("Bob", "456") # Mutates the same default dict as `a`! ``` - **Risk**: Data corruption when the default is used. **Issue 3: No Guard for Script Execution** - **Line 16**: `main()` - **Problem**: Executes `main()` unconditionally, running the script on import. - **Risk**: Unintended side effects if this module is imported elsewhere. **Issue 4: Error Handling Limitations** - **Line 3**: Empty checks (`if not name or not number`) - **Problem**: Accepts non-string inputs (e.g., `None`, `0`) and whitespace-only strings. - **Risk**: Invalid data may propagate silently (e.g., `add_contact(" ", "123")`). --- #### 4. **Suggestions** 1. **Fix Dictionary Syntax**: - Use `contact_list[name]` for assignment/access. 2. **Replace Mutable Default Argument**: - Use `None` as the default and initialize a new dict inside the function. 3. **Improve Input Validation**: - Explicitly check for empty/whitespace strings using `str.strip()`. - Add type checks if needed (e.g., ensure `name` and `number` are strings). 4. **Add `if __name__ == "__main__"` Guard**: - Prevents execution on import. 5. **Consider Returning Errors**: - Instead of printing, return success/error codes or raise exceptions. 6. **Add Type Hints (Optional)**: - Enhances readability and IDE support (e.g., `def add_contact(name: str, number: str, contact_list: dict | None = None) -> dict:`). --- #### 5. **Refactored Code** ```python def add_contact(name: str, number: str, contact_list: dict | None = None) -> dict: """Adds a contact to a dictionary. Returns the updated dictionary.""" if contact_list is None: contact_list = {} # Validate inputs: non-empty strings without whitespace if not isinstance(name, str) or not isinstance(number, str): print("Name and number must be strings.") return contact_list name_clean = name.strip() number_clean = number.strip() if not name_clean or not number_clean: print("Name and number cannot be empty or whitespace.") return contact_list contact_list[name_clean] = number_clean return contact_list def get_contact(name: str, contact_list: dict) -> str: """Returns a contact's number or 'not found'.""" name_clean = name.strip() return contact_list.get(name_clean, "Contact not found") def main() -> None: my_contacts = add_contact("Alice", "12345") add_contact("Bob", "", my_contacts) # Fails (empty number) add_contact("", "54321", my_contacts) # Fails (empty name) print(get_contact("Alice", my_contacts)) # "12345" print(get_contact("Charlie", my_contacts)) # "Contact not found" if __name__ == "__main__": main() ``` --- #### 6. **Notes** - **Assumptions**: - Contact names are unique keys. - Printing errors is sufficient (vs. exceptions). - **Edge Cases Addressed**: - Stripped whitespace from inputs. - Rejected non-string inputs. - **Version-Specific Nuances**: - Used `dict.get()` (Python 3.11) for safe key lookup. - Union type `dict | None` requires Python 3.10+. - **Further Improvements**: - Consider case-insensitive names (e.g., normalize to `lower()`). - Validate number format (e.g., digits only). - Use a class to encapsulate contact logic.
🐋 DeepSeek

Code Analysis Suggestions

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
R1
Tested icon
Guide icon
4 examples icon
Free credits icon
Real-world code reviews for any language. Catch issues early, reduce QA headaches, and get smart, version-aware fixes—keeping your code clean and your deploys on schedule.
...more
Added over 1 month ago
Report
Browse Marketplace