{"text": "### Instruction: Write a Python function to calculate the factorial of a number.\n### Response: def factorial(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n - 1)"} {"text": "### Instruction: Explain the difference between lists and tuples in Python.\n### Response: Lists are mutable (can be changed) and use square brackets [], while tuples are immutable (cannot be changed) and use parentheses (). Lists are better for data that changes, tuples for fixed data."} {"text": "### Instruction: Write a function to check if a number is prime.\n### Response: def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True"} {"text": "### Instruction: How do you reverse a string in Python?\n### Response: You can reverse a string using slicing: text[::-1]. For example, 'hello'[::-1] returns 'olleh'. You can also use ''.join(reversed(text)) or text[::-1]."} {"text": "### Instruction: Write a Python function to find the maximum element in a list.\n### Response: def find_max(lst):\n if not lst:\n return None\n max_val = lst[0]\n for item in lst[1:]:\n if item > max_val:\n max_val = item\n return max_val"} {"text": "### Instruction: Explain what is recursion with an example.\n### Response: Recursion is when a function calls itself. It needs a base case to stop. Example: def countdown(n): if n <= 0: print('Done!') else: print(n); countdown(n-1). This prints numbers from n down to 1."} {"text": "### Instruction: Write a function to calculate Fibonacci sequence.\n### Response: def fibonacci(n):\n if n <= 1:\n return n\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n# More efficient version:\ndef fib_iterative(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b\n return a"} {"text": "### Instruction: How to handle exceptions in Python?\n### Response: Use try-except blocks:\ntry:\n result = 10 / 0\nexcept ZeroDivisionError:\n print('Cannot divide by zero')\nexcept Exception as e:\n print(f'An error occurred: {e}')\nfinally:\n print('This always runs')"} {"text": "### Instruction: Write a function to sort a list without using built-in sort.\n### Response: def bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr"} {"text": "### Instruction: Explain the concept of object-oriented programming.\n### Response: OOP is a programming paradigm based on objects that contain data (attributes) and code (methods). Key principles: 1) Encapsulation - bundling data and methods, 2) Inheritance - creating new classes from existing ones, 3) Polymorphism - same interface for different types, 4) Abstraction - hiding complex implementation details."}