messages
listlengths
2
2
[ { "content": "def read_and_process_file(filename):\n results = []\n with open(filename, 'r') as file:\n for line in file:\n cleaned = line.strip()\n if cleaned:\n length = len(cleaned)\n results.append((cleaned, length))\n with open('summary.tx...
[ { "content": "def remove_item(items, item_to_remove):\n print(\"Original list:\", items)\n if item_to_remove in items:\n items.remove(item_to_remove)\n print(\"Removed:\", item_to_remove)\n else:\n print(\"Item not found:\", item_to_remove)\n print(\"Updated list:\", items)\n ...
[ { "content": "print(\"Hello, world!\")\nmessage = \"Learning Python is fun!\"\nprint(message)", "role": "user" }, { "content": "This code first prints the phrase \"Hello, world!\" to the screen. Then it stores a sentence inside a variable called message and prints whatever is stored in that variable...
[ { "content": "def filter_numbers(nums):\n results = []\n for n in nums:\n is_even = (n % 2 == 0)\n is_large = (n > 50)\n is_negative = (n < 0)\n if (is_even or is_large) and not is_negative:\n results.append(n)\n elif not is_even and not is_large:\n ...
[ { "content": "numbers = []\nfor i in range(1, 21):\n text = \"Number: \" + str(i)\n numbers.append(text)\n\nfor idx in range(len(numbers)):\n if idx % 2 == 0:\n label = \"(even index) \"\n else:\n label = \"(odd index) \"\n print(label + numbers[idx])\n\nsummary = \"Total items: \" ...
[ { "content": "count = 0\nwhile count < 5:\n print(\"Count is\", count)\n count += 1", "role": "user" }, { "content": "This code starts by setting a variable named count to 0. The while statement tells the computer to keep repeating the block of code below it as long as count is less than 5. Ea...
[ { "content": "def manage_list(items, to_add, to_remove):\n items.append(to_add)\n if to_remove in items:\n items.remove(to_remove)\n return items\n\nmy_list = [1, 2, 3]\nresult = manage_list(my_list, 4, 2)\nprint(result)", "role": "user" }, { "content": "This code defines a function ...
[ { "content": "def clean_shopping_list(items, item_to_remove):\n print(\"Original list:\", items)\n if item_to_remove in items:\n items.remove(item_to_remove)\n print(f\"Removed '{item_to_remove}' using remove().\")\n else:\n print(f\"'{item_to_remove}' not found, nothing removed.\"...
[ { "content": "def remove_item(items, value):\n if value in items:\n index = items.index(value)\n del items[index]\n print(\"Removed:\", value)\n else:\n print(\"Value not found.\")\n return items\n\nmy_list = [3, 5, 7, 9]\nupdated = remove_item(my_list, 7)", "role": "use...
[ { "content": "def print_fun_facts(name, facts):\n print(\"Welcome to the Fun Fact Printer!\")\n print(\"Preparing fun facts about:\", name)\n print(\"Number of facts to print:\", len(facts))\n print(\"Starting...\")\n for i, fact in enumerate(facts, start=1):\n print(\"Fact\", i, \":\", fa...
[ { "content": "with open('notes.txt', 'w') as f:\n f.write('Learning Python is fun!')\n\nwith open('notes.txt', 'r') as f:\n content = f.read()\n print(content)", "role": "user" }, { "content": "This code uses the with keyword to open a file, write text into it, and then open it again to rea...
[ { "content": "def count_down(start):\n num = start\n while num > 0:\n print(\"Counting:\", num)\n num -= 1\n print(\"Liftoff!\")", "role": "user" }, { "content": "This function starts with a number and keeps counting down until it reaches zero. The while keyword makes the comp...
[ { "content": "def assess_temperature(temp):\n if temp < 0:\n return \"It's freezing outside! Wear heavy winter clothing.\"\n elif temp < 10:\n return \"It's very cold. A coat and gloves are recommended.\"\n elif temp < 20:\n return \"It's a bit chilly. A light jacket should be fine...
[ { "content": "def analyze_numbers(numbers):\n total = 0\n count_above_50 = 0\n doubled_values = []\n\n for n in numbers:\n total += n\n if n > 50:\n count_above_50 += 1\n doubled_values.append(n * 2)\n\n average = total / len(numbers) if numbers else 0\n\n for v...
[ { "content": "def check_access(age, has_permission):\n if age >= 16 or has_permission:\n if not (age < 16 and not has_permission):\n return \"Access granted\"\n return \"Access denied\"\n\nresult = check_access(15, False)\nprint(result)", "role": "user" }, { "content": "This ...
[ { "content": "def manage_inventory():\n inventory = {'apples': 10, 'bananas': 6, 'oranges': 4}\n print('Current items:', inventory.items())\n print('Item names:', inventory.keys())\n print('Item quantities:', inventory.values())\n\n new_stock = {'bananas': 10, 'grapes': 7}\n inventory.update(n...
[ { "content": "numbers = range(1, 6)\nfor n in numbers:\n print(str(n))", "role": "user" }, { "content": "This code creates a range of numbers from 1 to 5 and then loops through each number in that range. Inside the loop, it converts each number into a string using str() and prints it.\n\nYou can ...
[ { "content": "nums = [3, 1, 3]\ncopy_nums = nums.copy(); count_threes = nums.count(3)\nnums.extend([5, 2]); nums.sort(); nums.reverse()", "role": "user" }, { "content": "This code starts with a list of numbers, then makes a copy of it so the original can be changed without affecting the duplicate. I...
[ { "content": "def safe_divide(a, b):\n try:\n result = a / b\n return result\n except TypeError:\n return \"Both inputs must be numbers.\"\n except ValueError:\n return \"Invalid value provided.\"\n except ZeroDivisionError:\n return \"You cannot divide by zero.\"\...
[ { "content": "nums = [3, 8, 5, 8]\npos = nums.index(8)\nremoved = nums.pop(1)\nnums.insert(2, 10)", "role": "user" }, { "content": "This code starts with a list of numbers and finds the position of the first 8 using the index method. It then removes the item at position 1 with pop and finally insert...
[ { "content": "value = \"3.14\"\nnumber = float(value)\nresult = number * 2\nprint(result)", "role": "user" }, { "content": "This code takes the text value \"3.14\" and converts it into a floating‑point number using float(). Once it becomes a number, the code multiplies it by 2 and prints the result....
[ { "content": "numbers = [1, 2, 3, 4]\nsquares = list(map(lambda x: x * x, numbers))\nprint(\"Original numbers:\", numbers)\nprint(\"Squared numbers:\", squares)", "role": "user" }, { "content": "This code takes a list of numbers and uses the map function to apply a small anonymous function (a lambda...
[ { "content": "def compare_numbers(a, b):\n results = {}\n if a != b:\n results['not_equal'] = f\"{a} is not equal to {b}\"\n else:\n results['not_equal'] = f\"{a} is equal to {b}\"\n if a > b:\n results['greater_than'] = f\"{a} is greater than {b}\"\n if a >= b:\n resu...
[ { "content": "double = lambda x: x * 2\nnumbers = [1, 2, 3]\ndoubled_numbers = list(map(lambda n: n * 2, numbers))", "role": "user" }, { "content": "This code uses lambda functions to quickly create small, one-line functions. The first line makes a function called 'double' that takes a number and re...
[ { "content": "import math\n\ndef circle_area(radius):\n return math.pi * radius ** 2\n\ndef circle_circumference(radius):\n return 2 * math.pi * radius\n\nprint(circle_area(5))\nprint(circle_circumference(5))", "role": "user" }, { "content": "This code begins by importing the math module, whic...
[ { "content": "# This program adds two numbers\nnum1 = 5 # First number\nnum2 = 7 # Second number\nresult = num1 + num2 # Add the numbers\ntprint = result # Store the result", "role": "user" }, { "content": "This code creates two numbers, adds them together, and stores the result. Each line inclu...
[ { "content": "def describe_student():\n name = \"Alex\"\n age = 16\n grade = \"10th\"\n favorite_subject = \"Math\"\n gpa = 3.7\n summary = \"Student: \" + name + \", Age: \" + str(age)\n details = \"Grade: \" + grade + \", Favorite Subject: \" + favorite_subject\n report = summary + \" ...
[ { "content": "class Example:\n def __secret(self): print(\"Hidden!\")\n def reveal(self): self.__secret()", "role": "user" }, { "content": "This code creates a class with a private method named __secret, which can only be called from inside the class itself. The reveal method is public, and it...
[ { "content": "temperature = 75\nif temperature > 70:\n print(\"It's warm outside.\")\nelse:\n print(\"It's cool outside.\")", "role": "user" }, { "content": "This code checks the value stored in the variable temperature. If the temperature is greater than 70, the program prints that it's warm ...
[ { "content": "values = [42, \"hello\", 3.14, True]\nfor item in values:\n if isinstance(item, int):\n print(item, \"is an integer\")", "role": "user" }, { "content": "This code creates a list with different types of data, then loops through each item in the list. For each item, it checks w...
[ { "content": "print(\"Hello, world!\")\nname = \"Alex\"\nprint(\"Welcome,\", name)", "role": "user" }, { "content": "This code displays messages on the screen. The first line prints the phrase \"Hello, world!\", and the next two lines create a variable called name and then print a welcome message th...
[ { "content": "def analyze_lengths(data):\n total_items = len(data)\n lengths = []\n for item in data:\n lengths.append(len(item))\n longest = max(lengths)\n shortest = min(lengths)\n average = sum(lengths) / len(lengths)\n summary = {\n 'total_items': total_items,\n 'lo...
[ { "content": "x = 10\nprint(x != 5)\nprint(x > 7)\nprint(x >= 10)\nprint(x < 12)\nprint(x <= 9)", "role": "user" }, { "content": "This code compares the value stored in x (which is 10) to different numbers using comparison operators. Each print statement checks a condition such as whether x is not e...
[ { "content": "def process_scores(scores):\n highest = max(scores)\n lowest = min(scores)\n length = len(scores)\n summary = (highest, lowest, length)\n print(\"Summary tuple:\", summary)\n for value in summary:\n print(\"Value:\", value)\n return summary", "role": "user" }, {...
[ { "content": "def greet_user(name):\n message = \"Hello, \" + name + \"!\"\n print(message)\n print(\"Welcome to the program.\")\n print(\"We hope you enjoy learning Python!\")\n for i in range(3):\n print(\"This is message number\", i + 1)\n print(\"Goodbye!\")", "role": "user" }...
[ { "content": "import random\nnumbers = [random.randint(1, 10) for _ in range(5)]\nselected = random.choice(numbers)\nprint(\"List:\", numbers)\nprint(\"Random pick:\", selected)", "role": "user" }, { "content": "This code creates a list of five random integers between 1 and 10, then selects one rand...
[ { "content": "def create_variables():\n name = \"Alice\"\n age = 16\n height_cm = 165\n is_student = True\n favorite_subject = \"Math\"\n score = 92.5\n message = \"Student record created\"\n total_points = score + age\n return message, total_points", "role": "user" }, { "...
[ { "content": "fruits = [\"apple\", \"banana\", \"cherry\"]\nif \"banana\" in fruits:\n print(\"Banana is in the list!\")", "role": "user" }, { "content": "This code creates a list of fruits and then checks whether the word \"banana\" is inside that list. If it finds \"banana\", it prints a messag...
[ { "content": "message = \"Hello, world!\"\nupper_message = message.upper()\nprint(message)\nprint(upper_message)", "role": "user" }, { "content": "This code creates a string called message and then makes a second version of that string in all uppercase letters using the upper() function. After that,...
[ { "content": "def countdown_timer(start):\n number = start\n attempts = 0\n while number > 0:\n print('Countdown:', number)\n number -= 1\n attempts += 1\n if attempts > 20:\n print('Too many steps, stopping early.')\n break\n if number == 0:\n ...
[ { "content": "with open('notes.txt', 'r') as file:\n content = file.read()\nprint(content)", "role": "user" }, { "content": "This code opens a file named 'notes.txt' and reads everything inside it. Python's with keyword makes sure the file is opened safely, and once the reading is done, the file ...
[ { "content": "def manage_list(items):\n my_list = []\n for item in items:\n my_list.append(item)\n if len(my_list) > 0:\n to_remove = my_list[0]\n my_list.remove(to_remove)\n return my_list\n\nresult = manage_list([\"apple\", \"banana\", \"cherry\"])", "role": "user" }, ...
[ { "content": "nums = [3, 1, 2, 1]\ncopy_nums = nums.copy(); count_ones = nums.count(1)\nnums.extend([4, 5]); nums.sort()", "role": "user" }, { "content": "This code starts with a list of numbers, makes a separate copy of that list, counts how many times the number 1 appears, then adds two more numbe...
[ { "content": "with open('notes.txt', 'w') as file:\n file.write('Hello, world!')\n file.write('\\nLearning Python is fun!')", "role": "user" }, { "content": "This code opens a file called notes.txt and allows the program to write text into it. The with keyword makes sure the file is opened pro...
[ { "content": "def create_variables():\n name = \"Alex\"\n age = 16\n height_cm = 170\n is_student = True\n favorite_subject = \"Math\"\n score = 92.5\n total_points = score + age\n message = \"Student: \" + name\n return message, total_points", "role": "user" }, { "content...
[ { "content": "def print_report(title, items):\n print(\"==== \" + title + \" ====\")\n print(\"Number of items:\", len(items))\n print(\"Listing items...\")\n\n for i, item in enumerate(items, start=1):\n print(f\"{i}. {item}\")\n\n longest = max(items, key=len) if items else \"\"\n pri...
[ { "content": "message = \"Hello, World!\"\nupper_message = message.upper()\nprint(\"Original:\", message)\nprint(\"Uppercase:\", upper_message)", "role": "user" }, { "content": "This code creates a string that says \"Hello, World!\" and stores it in a variable called message. It then makes a new ver...
[ { "content": "import time\nstart = time.time()\ntime.sleep(2)\nend = time.time()\nprint(\"Elapsed time:\", end - start, \"seconds\")", "role": "user" }, { "content": "This code measures how long a short pause lasts. It records the current time, waits for two seconds using the sleep function, then re...
[ { "content": "name = \"aLiCe\"\nlower_name = name.lower()\nupper_name = name.upper()\nproper_name = name.title()", "role": "user" }, { "content": "This code takes a name written with mixed uppercase and lowercase letters and transforms it in different ways. The .lower() method turns all letters into...
[ { "content": "class Example:\n def __method(self):\n return \"secret\"\n def reveal(self):\n return self.__method()", "role": "user" }, { "content": "This code shows how Python uses double underscores to create private methods. The method named __method can only be accessed from ...
[ { "content": "fruits = ['apple', 'banana', 'cherry']\ndel fruits[1]\nprint(fruits)", "role": "user" }, { "content": "This code creates a list of fruits, then uses the del statement to remove the item at index 1, which is 'banana'. After deleting it, the code prints the updated list so you can see th...
[ { "content": "words = [\"apple\", \"banana\", \"cherry\"]\ncount = len(words)\ntext = \"Hello, world!\"\ntext_length = len(text)\nprint(count, text_length)", "role": "user" }, { "content": "This code uses the len() function to find how many items are in a list and how many characters are in a string...
[ { "content": "student_scores = {\n \"Alice\": 88,\n \"Bob\": 92,\n \"Charlie\": 79\n}\n\nnames_to_check = [\"Alice\", \"David\", \"Charlie\", \"Eva\"]\n\nfor name in names_to_check:\n score = student_scores.get(name, \"No score available\")\n message = \"Student: {} | Score: {}\".format(name, sco...
[ { "content": "def process_numbers(num_list):\n results = []\n for item in num_list:\n try:\n number = int(item)\n if number % 2 == 0:\n results.append((number, 'even'))\n else:\n results.append((number, 'odd'))\n except ValueErro...
[ { "content": "def process_scores(file_path):\n results = []\n with open(file_path, 'r') as f:\n for line in f:\n parts = line.strip().split(',')\n name = parts[0]\n scores = [int(x) for x in parts[1:]]\n with open('log.txt', 'a') as log:\n ...
[ { "content": "def compare_numbers(a, b):\n if a > b:\n return \"a is greater than b\"\n elif a >= b:\n return \"a is greater than or equal to b\"\n elif a < b:\n return \"a is less than b\"\n elif a <= b:\n return \"a is less than or equal to b\"\n elif a != b:\n ...
[ { "content": "def calculate_student_average(grades):\n total = 0\n for score in grades:\n total += score\n if len(grades) == 0:\n return 0\n return total / len(grades)\n\ndef compare_averages(avg1, avg2):\n if avg1 > avg2:\n return \"Student 1 has the higher average.\"\n e...
[ { "content": "def string_tools(text, word_list):\n position = text.find('example')\n swapped = text.swapcase()\n replaced = text.replace('bad', 'good')\n split_words = text.split()\n joined_words = '-'.join(word_list)\n result = []\n\n result.append('Position of \"example\": ' + str(positio...
[ { "content": "greetings = [\"Hello\", \"Hi\"]\nnames = [\"Alice\", \"Bob\"]\ncombined = greetings + names\nprint(combined)", "role": "user" }, { "content": "This code creates two lists of strings, one with greetings and one with names. It then uses the + operator to concatenate, or join, the two lis...
[ { "content": "def average_as_float(numbers):\n total = 0\n for n in numbers:\n total += float(n)\n count = float(len(numbers))\n if count == 0:\n return 0.0\n avg = total / count\n return avg", "role": "user" }, { "content": "This function takes a list of numbers, con...
[ { "content": "message = \"Hello, World!\"\nname = \"Alex\"\ngreeting = message + \" My name is \" + name\nprint(greeting)\nprint(\"Your name has\", len(name), \"letters.\")", "role": "user" }, { "content": "This code works with strings by creating a message, combining it with a name, and printing th...
[ { "content": "def divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divide by zero!\")\n return a / b", "role": "user" }, { "content": "This code defines a function that divides one number by another. Before doing the division, it checks if the second number is zero. If it is, the ...
[ { "content": "# This line sets the starting value\ncount = 0\n# This line increases the value by 1\ncount += 1", "role": "user" }, { "content": "This code shows how comments work in Python. The lines starting with # are ignored by the computer and are there only to explain what the code is doing. In...
[ { "content": "def show_current_time():\n import time\n current = time.localtime()\n hour = current.tm_hour\n minute = current.tm_min\n second = current.tm_sec\n formatted = f\"Current time: {hour}:{minute}:{second}\"\n return formatted\n\nprint(show_current_time())", "role": "user" },...
[ { "content": "def process_scores(file_path):\n total = 0\n count = 0\n highest = None\n lowest = None\n # Use 'with' to open the file safely\n with open(file_path, 'r') as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n ...
[ { "content": "age = 16\nhas_permission = False\ncan_enter = age >= 18 or has_permission\nis_restricted = not has_permission\nallowed = can_enter and not is_restricted", "role": "user" }, { "content": "This code uses Python's logical operators to decide whether someone is allowed to enter a place. It...
[ { "content": "words1 = [\"Hello\", \"world\"]\nwords2 = [\"Python\", \"rocks\"]\ncombined = words1 + words2\nsentence = \" \".join(combined)\nprint(sentence)", "role": "user" }, { "content": "This code creates two separate lists of words and then joins them together into one larger list. After combi...
[ { "content": "def convert_to_int(value):\n try:\n num = int(value)\n print(\"Conversion successful:\", num)\n return num\n except ValueError:\n print(\"Conversion failed. Using 0 instead.\")\n return 0\n\nuser_input = \"42\"\nresult = convert_to_int(user_input)", "ro...
[ { "content": "fruits = [\"apple\", \"banana\", \"orange\"]\nif \"banana\" in fruits:\n print(\"Banana is in the list!\")", "role": "user" }, { "content": "This code creates a list of fruits and then checks whether the word \"banana\" is inside that list. If it finds \"banana\", it prints a messag...
[ { "content": "def divide(a, b):\n if b == 0:\n raise ValueError(\"Cannot divide by zero!\")\n return a / b\n\nprint(divide(10, 0))", "role": "user" }, { "content": "This code defines a function called divide that takes two numbers. Before it divides them, it checks whether the second nu...
[ { "content": "def sum_as_int(a, b):\n first = int(a)\n second = int(b)\n total = first + second\n print(\"First number:\", first)\n print(\"Second number:\", second)\n print(\"Sum:\", total)\n return total\n\nsum_as_int(\"12\", \"8\")", "role": "user" }, { "content": "This code ...
[ { "content": "import random\n\ndef pick_random_word(words):\n if not words:\n return None\n index = random.randint(0, len(words) - 1)\n return words[index]\n\nsample_list = ['apple', 'banana', 'cherry']\nprint(pick_random_word(sample_list))", "role": "user" }, { "content": "This code...
[ { "content": "nums = [10, 20, 30, 40]\npos = nums.index(30)\nremoved = nums.pop(pos)\nnums.insert(1, removed)", "role": "user" }, { "content": "This code creates a list of numbers, finds the position of the value 30, removes it using pop, and then inserts it back into the list at a new position. Eac...
[ { "content": "student_scores = {\n \"Alice\": 88,\n \"Bob\": 76,\n \"Charlie\": 93\n}\n\nnames_to_check = [\"Alice\", \"David\", \"Charlie\", \"Eve\"]\n\nfor name in names_to_check:\n score = student_scores.get(name, \"No score available\")\n message = \"Student: {} | Score: {}\".format(name, sco...
[ { "content": "with open('notes.txt', 'r') as file:\n content = file.read()\n print(content)", "role": "user" }, { "content": "This code opens a file named notes.txt and reads everything inside it. The with keyword makes sure the file is opened safely and then automatically closed when the read...
[ { "content": "def check_access(age, has_permission):\n is_adult = age >= 18\n if is_adult and has_permission:\n return True\n elif is_adult and not has_permission:\n return False\n else:\n return False", "role": "user" }, { "content": "This function checks two things...
[ { "content": "x = 10\nname = \"Alice\"\nis_student = True\ntemperature = 72.5\nx = x + 5\ngreeting = \"Hello, \" + name\nheight_cm = 170\nage = 16\nresult = age * 2\nmessage = greeting + \"! Your age doubled is \" + str(result)", "role": "user" }, { "content": "This code creates several variables, e...
[ { "content": "def count_vowels(text):\n # Define vowels we want to count\n vowels = \"aeiou\"\n # Start the counter at zero\n count = 0\n # Check each character in the text\n for char in text.lower():\n # Increase count if character is a vowel\n if char in vowels:\n co...
[ { "content": "message = \"Hello\\nWorld\"\nprint(message)\nprint(\"Line one\\nLine two\\nLine three\")", "role": "user" }, { "content": "This code creates strings that include the special character \\n, which tells Python to start a new line. When printed, the text after \\n appears on the next line...
[ { "content": "def check_temperature(temp):\n if temp > 30:\n return \"It's hot outside!\"\n elif temp > 20:\n return \"The weather is warm.\"\n elif temp > 10:\n return \"It's a bit cool.\"\n else:\n return \"It's cold outside!\"\n", "role": "user" }, { "conte...
[ { "content": "temperature = 75\nif temperature > 85:\n print(\"It's hot outside.\")\nelif temperature > 60:\n print(\"It's warm outside.\")\nelse:\n print(\"It's cool outside.\")", "role": "user" }, { "content": "This code checks the value of the variable temperature and decides which messa...
[ { "content": "def describe_student(info):\n name = info.get('name', 'Unknown')\n grade = info.get('grade', 'N/A')\n age = info.get('age', 'Unknown')\n message = \"Student {0} is in grade {1} and is {2} years old.\".format(name, grade, age)\n return message\n\nstudent_info = {'name': 'Alex', 'grad...
[ { "content": "def manage_tasks(task_list, tasks_to_add, tasks_to_remove):\n for task in tasks_to_add:\n task_list.append(task)\n for task in tasks_to_remove:\n if task in task_list:\n task_list.remove(task)\n cleaned_tasks = []\n for t in task_list:\n if len(t) > 0:\n...
[ { "content": "name = input(\"What is your name? \")\nage = input(\"How old are you? \")\nprint(\"Hello, \" + name + \"!\")\nprint(\"You are \" + age + \" years old.\")", "role": "user" }, { "content": "This code asks the user two questions: their name and their age. Whatever the user types is stored...
[ { "content": "from math import sqrt as square_root\nresult = square_root(25)", "role": "user" }, { "content": "This code imports the sqrt function from Python's math module and renames it to square_root using the word 'as'. Then it uses that renamed function to calculate the square root of 25.\nThin...
[ { "content": "def classify_temperature(temp):\n if temp < 0:\n return \"It's freezing outside!\"\n elif temp < 10:\n return \"It's very cold.\"\n elif temp < 20:\n return \"It's a bit chilly.\"\n elif temp < 30:\n return \"The temperature is comfortable.\"\n elif temp ...
[ { "content": "class Robot:\n def __move(self):\n print(\"Moving secretly...\")\n def start(self):\n self.__move()", "role": "user" }, { "content": "This code defines a Robot class with a private method called __move. The double underscores make it so that this method is hidden fr...
[ { "content": "nums = [10, 20, 30, 40]\npos = nums.index(30)\nnums.pop(pos)\nnums.insert(1, 25)", "role": "user" }, { "content": "This code finds where the number 30 is located in the list, removes it using that position, and then inserts the number 25 into the second spot in the list. It uses three ...
[ { "content": "try:\n result = int(\"hello\")\nexcept ValueError:\n print(\"You tried to convert something that isn't a number.\")\nexcept TypeError:\n print(\"You used the wrong type of value.\")", "role": "user" }, { "content": "This code tries to convert the word \"hello\" into an integer...
[ { "content": "class Example:\n def __secret(self):\n return \"hidden\"\n def reveal(self):\n return self.__secret()", "role": "user" }, { "content": "This code creates a class with a private method called __secret, which can only be used from inside the class. The reveal method c...
[ { "content": "import sys\n\ndef print_args_info():\n print(\"Python version:\", sys.version)\n print(\"Executable path:\", sys.executable)\n print(\"Number of arguments:\", len(sys.argv))\n print(\"Arguments passed:\")\n for arg in sys.argv:\n print(\" -\", arg)\n\nprint_args_info()", ...
[ { "content": "def manage_task_list(tasks):\n task_list = []\n\n for task in tasks:\n if task not in task_list:\n task_list.append(task)\n else:\n print(\"Task already exists:\", task)\n\n print(\"Initial list:\", task_list)\n\n for task in tasks:\n if len(t...
[ { "content": "def modify_list(items):\n numbers = []\n for item in items:\n numbers.append(item)\n if 3 in numbers:\n numbers.remove(3)\n numbers.append(10)\n return numbers", "role": "user" }, { "content": "This function takes a list called items and adds each of its va...
[ { "content": "def show_poem():\n title = \"My Short Poem\"\n line1 = \"Roses are red\"\n line2 = \"Violets are blue\"\n line3 = \"I like using newline characters\"\n poem = title + \"\\n\" + line1 + \"\\n\" + line2 + \"\\n\" + line3\n print(poem)\n\nshow_poem()", "role": "user" }, { ...
[ { "content": "def count_vowels(text):\n vowels = \"aeiouAEIOU\"\n count = 0\n for char in text:\n if char in vowels:\n count += 1\n return count\n\nresult = count_vowels(\"Hello World\")\nprint(result)", "role": "user" }, { "content": "This code defines a function that ...
[ { "content": "numbers = [1, 2, 3, 4]\nsquares = list(map(lambda x: x * x, numbers))\nprint(squares)", "role": "user" }, { "content": "This code takes a list of numbers and uses the map function to create a new list where each number is replaced by its square. The lambda function tells Python how to ...
[ { "content": "text = \"hello world\"\nprint(text.upper())\nprint(text.title())\nprint(text.capitalize())", "role": "user" }, { "content": "This code takes a string and shows how different string methods can change its appearance. The upper method turns all letters into uppercase, title capitalizes t...
[ { "content": "def format_string(text):\n lower_text = text.lower()\n upper_text = text.upper()\n title_text = text.title()\n capitalized_text = text.capitalize()\n print(\"Lower:\", lower_text)\n print(\"Upper:\", upper_text)\n print(\"Title:\", title_text)\n print(\"Capitalized:\", capi...
[ { "content": "class BankAccount:\n def __init__(self, owner, balance):\n self.owner = owner\n self.__balance = balance\n\n def deposit(self, amount):\n if amount > 0:\n self.__balance += amount\n\n def withdraw(self, amount):\n if 0 < amount <= self.__balance:\n ...
[ { "content": "names = [\"Ava\", \"Ben\", \"Mia\", \"Leo\"]\ncount = len(names)\nprint(\"Number of students:\", count)\ntext = \"Hello World\"\nprint(\"Length of the text:\", len(text))", "role": "user" }, { "content": "This code uses the len() function to find out how many items are in a list and ho...