Dataset Viewer
Auto-converted to Parquet Duplicate
instruction
stringlengths
26
149
input
stringclasses
14 values
Response
stringlengths
33
582
Explain why this expression uses floor division and show the result. (practice variation 15)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Create a small Python program to write a function that counts words in a sentence.
null
def word_count(sentence): return len(sentence.split()) print(word_count('Python is readable and practical'))
Demonstrate the difference between `break` and `continue`. (practice variation 29)
for number in range(1, 6): if number == 2: continue if number == 5: break print(number)
`continue` skips the rest of the current iteration; `break` terminates the loop.
Show how to make a shallow copy of a list and explain why it matters. (practice variation 33)
original = [[1], [2]] copy = original.copy() copy[0].append(9) print(original)
A shallow copy creates a new outer list but retains references to nested objects. Mutating a nested list is visible through both lists.
Explain and demonstrate how Python can check whether the text contains the substring cat.
null
Example: text = "education" result = text.__contains__("cat") print(result) The expression uses string indexing or a string method to produce the requested result.
Provide code and a short explanation for how to write a function with a default argument.
null
def greet(name, greeting='Hello'): return f'{greeting}, {name}!' print(greet('Aylin')) print(greet('Murad', 'Welcome'))
Give a short explanation and code example for how to assign a letter grade based on a numeric score.
null
score = 86 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' elif score >= 60: grade = 'D' else: grade = 'F' print(grade)
Write code to safely convert a string to a float and handle invalid input. (practice variation 11)
raw = '3.14' try: value = float(raw) except ValueError: print('Invalid number') else: print(value)
Catch ValueError for text that cannot be converted to a float.
Write a runnable Python solution to check whether all values in a list are positive.
null
values = [2, 4, 1, 9] print(all(value > 0 for value in values))
Provide code and a short explanation for how to implement linear search.
null
def linear_search(values, target): for index, value in enumerate(values): if value == target: return index return -1 print(linear_search(['a', 'b', 'c'], 'b'))
Write Python code to measure elapsed time for a block of work.
null
from time import perf_counter start = perf_counter() result = sum(range(1_000_000)) elapsed = perf_counter() - start print(result, elapsed)
Explain what this slice returns. (practice variation 19)
values = [10, 20, 30, 40, 50] print(values[1:4])
The slice includes index 1 and excludes index 4, so it prints `[20, 30, 40]`.
Provide code and a short explanation for how to use defaultdict to group items.
null
from collections import defaultdict items = [('fruit', 'apple'), ('tool', 'hammer'), ('fruit', 'pear')] groups = defaultdict(list) for category, item in items: groups[category].append(item) print(dict(groups))
Implement the following task in Python: list all Python files in a directory.
null
from pathlib import Path for path in Path('.').glob('*.py'): print(path.name)
Show how to make a shallow copy of a list and explain why it matters. (practice variation 3)
original = [[1], [2]] copy = original.copy() copy[0].append(9) print(original)
A shallow copy creates a new outer list but retains references to nested objects. Mutating a nested list is visible through both lists.
Show a clear Python example that can write a function that converts Celsius to Fahrenheit.
null
def celsius_to_fahrenheit(celsius): return celsius * 9 / 5 + 32 print(celsius_to_fahrenheit(20))
Explain why this expression uses floor division and show the result. (practice variation 13)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Describe the relevant list or tuple operation and show working code to create a reversed copy without changing the original list.
null
numbers = [1, 2, 3, 4] reversed_numbers = numbers[::-1] print(reversed_numbers) print(numbers) Use zero-based indexing for list positions. Methods such as append(), remove(), and sort() modify a list in place.
Show how to iterate over a dictionary in sorted key order. (practice variation 9)
scores = {'Murad': 80, 'Aylin': 95, 'Leyla': 88} for name in sorted(scores): print(name, scores[name])
sorted(scores) returns the dictionary keys in sorted order, which can then be used to retrieve values.
Show a clear Python example that can calculate the median of a numeric list.
null
from statistics import median values = [8, 2, 5, 1, 9] print(median(values))
Implement the following task in Python: calculate the distance between two 2D points.
null
from math import hypot x1, y1 = 1, 2 x2, y2 = 4, 6 print(hypot(x2 - x1, y2 - y1))
Write code to safely convert a string to a float and handle invalid input. (practice variation 16)
raw = '3.14' try: value = float(raw) except ValueError: print('Invalid number') else: print(value)
Catch ValueError for text that cannot be converted to a float.
Implement the following task in Python: normalize a string for case-insensitive comparison.
null
def normalize(text): return ' '.join(text.casefold().split()) print(normalize(' PYTHON Programming '))
Create a small Python program to write a function that returns the square of a number.
null
def square(number): return number * number print(square(6))
Create a small Python program to print integers from 1 through 10.
null
for number in range(1, 11): print(number)
Show a clear Python example that can write a function that checks whether a string is a palindrome.
null
def is_palindrome(text): normalized = ''.join(ch.lower() for ch in text if ch.isalnum()) return normalized == normalized[::-1] print(is_palindrome('Never odd or even'))
Write a runnable Python solution to list all Python files in a directory.
null
from pathlib import Path for path in Path('.').glob('*.py'): print(path.name)
Write a runnable Python solution to calculate the average score from records.
null
students = [{"name": "Aylin", "score": 90}, {"name": "Murad", "score": 76}] average = sum(s["score"] for s in students) / len(students) print(average)
Implement the following task in Python: create a matrix of zeros.
null
rows, columns = 3, 4 matrix = [[0 for _ in range(columns)] for _ in range(rows)] print(matrix)
Show how to make a shallow copy of a list and explain why it matters. (practice variation 14)
original = [[1], [2]] copy = original.copy() copy[0].append(9) print(original)
A shallow copy creates a new outer list but retains references to nested objects. Mutating a nested list is visible through both lists.
Implement the following task in Python: print a multiplication table for a number.
null
number = 7 for multiplier in range(1, 11): print(f'{number} x {multiplier} = {number * multiplier}')
Show how to iterate over a dictionary in sorted key order. (practice variation 35)
scores = {'Murad': 80, 'Aylin': 95, 'Leyla': 88} for name in sorted(scores): print(name, scores[name])
sorted(scores) returns the dictionary keys in sorted order, which can then be used to retrieve values.
Explain why `list.sort()` and `sorted()` differ. (practice variation 17)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Show a clear Python example that can write a recursive function for the factorial of a non-negative integer.
null
def factorial(n): if n < 0: raise ValueError('n must be non-negative') if n < 2: return 1 return n * factorial(n - 1) print(factorial(5))
Show how to iterate over a dictionary in sorted key order. (practice variation 33)
scores = {'Murad': 80, 'Aylin': 95, 'Leyla': 88} for name in sorted(scores): print(name, scores[name])
sorted(scores) returns the dictionary keys in sorted order, which can then be used to retrieve values.
Write a runnable Python solution to avoid shared nested lists when creating a matrix.
null
matrix = [[0] * 3 for _ in range(2)] matrix[0][0] = 1 print(matrix)
Show a clear Python example that can append a line to a text file.
null
with open('log.txt', 'a', encoding='utf-8') as file: file.write('Program started\n')
Explain why this expression uses floor division and show the result. (practice variation 8)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Describe the relevant list or tuple operation and show working code to use slicing to select the middle three elements.
null
numbers = [10, 20, 30, 40, 50] print(numbers[1:4]) Use zero-based indexing for list positions. Methods such as append(), remove(), and sort() modify a list in place.
Show a clear Python example that can write a context manager using contextlib.
null
from contextlib import contextmanager @contextmanager def managed_message(): print('start') try: yield finally: print('finish') with managed_message(): print('working')
Write a Python example that can unpack a tuple into three variables.
null
student = ("Aylin", 20, "CS") name, age, major = student print(name, age, major)
Write Python code to write a unit test for a square function using unittest.
null
import unittest def square(n): return n * n class SquareTests(unittest.TestCase): def test_positive_number(self): self.assertEqual(square(4), 16) def test_zero(self): self.assertEqual(square(0), 0) if __name__ == '__main__': unittest.main()
Show how to iterate over a dictionary in sorted key order. (practice variation 14)
scores = {'Murad': 80, 'Aylin': 95, 'Leyla': 88} for name in sorted(scores): print(name, scores[name])
sorted(scores) returns the dictionary keys in sorted order, which can then be used to retrieve values.
Provide a short explanation and code sample to measure elapsed time for a block of work.
null
from time import perf_counter start = perf_counter() result = sum(range(1_000_000)) elapsed = perf_counter() - start print(result, elapsed)
Show a clear Python example that can write a function that returns the square of a number.
null
def square(number): return number * number print(square(6))
Explain why `list.sort()` and `sorted()` differ. (practice variation 16)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Write Python code to create an infinite counter generator.
null
def counter(start=0): value = start while True: yield value value += 1 numbers = counter(10) print(next(numbers), next(numbers), next(numbers))
Write Python code to read all text from a UTF-8 file.
null
from pathlib import Path text = Path('message.txt').read_text(encoding='utf-8') print(text)
Explain why `list.sort()` and `sorted()` differ. (practice variation 10)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Explain the approach and provide a complete Python implementation to write a function that checks whether a string is a palindrome.
null
def is_palindrome(text): normalized = ''.join(ch.lower() for ch in text if ch.isalnum()) return normalized == normalized[::-1] print(is_palindrome('Never odd or even'))
Provide code and a short explanation for how to write a context manager using contextlib.
null
from contextlib import contextmanager @contextmanager def managed_message(): print('start') try: yield finally: print('finish') with managed_message(): print('working')
Explain why `list.sort()` and `sorted()` differ. (practice variation 38)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Write Python code to store a dictionary of a student's details. Print the value and its type.
null
student = {"name": "Aylin", "age": 20} print(student) print(type(student).__name__)
Explain the algorithm briefly and provide a working implementation to implement linear search.
null
def linear_search(values, target): for index, value in enumerate(values): if value == target: return index return -1 print(linear_search(['a', 'b', 'c'], 'b'))
Write a runnable Python solution to use defaultdict to group items.
null
from collections import defaultdict items = [('fruit', 'apple'), ('tool', 'hammer'), ('fruit', 'pear')] groups = defaultdict(list) for category, item in items: groups[category].append(item) print(dict(groups))
Write a runnable Python solution to read all text from a UTF-8 file.
null
from pathlib import Path text = Path('message.txt').read_text(encoding='utf-8') print(text)
Show how to make a shallow copy of a list and explain why it matters. (practice variation 1)
original = [[1], [2]] copy = original.copy() copy[0].append(9) print(original)
A shallow copy creates a new outer list but retains references to nested objects. Mutating a nested list is visible through both lists.
Explain why `input()` returns a string and convert the value to an integer. (practice variation 13)
raw = input('Enter an integer: ') number = int(raw) print(number + 1)
The built-in input() returns text. Convert it with int() when an integer is required; handle ValueError if the input may be invalid.
Give a concise explanation with an example: What is a dictionary comprehension?
null
A dictionary comprehension builds a dictionary from an expression and an iterable. Example: `{n: n*n for n in range(1, 4)}` produces `{1: 1, 2: 4, 3: 9}`.
Show a clear Python example that can write text to a UTF-8 file.
null
from pathlib import Path Path('message.txt').write_text('Hello from Python\n', encoding='utf-8')
Show a clear Python example that can find common elements of two lists without duplicates.
null
a = [1, 2, 2, 3, 4] b = [2, 4, 4, 6] common = sorted(set(a) & set(b)) print(common)
Explain the key idea and provide a runnable implementation to calculate the population standard deviation.
null
from statistics import pstdev values = [2, 4, 4, 4, 5, 5, 7, 9] print(pstdev(values))
Provide code and a short explanation for how to find all even numbers in a list.
null
numbers = [3, 8, 11, 14, 20] even_numbers = [n for n in numbers if n % 2 == 0] print(even_numbers)
Show a clear Python example that can parse an ISO-formatted date string.
null
from datetime import date value = date.fromisoformat('2026-10-18') print(value.year, value.month, value.day)
Write a runnable Python solution to create a matrix of zeros.
null
rows, columns = 3, 4 matrix = [[0 for _ in range(columns)] for _ in range(rows)] print(matrix)
Demonstrate the difference between `break` and `continue`. (practice variation 27)
for number in range(1, 6): if number == 2: continue if number == 5: break print(number)
`continue` skips the rest of the current iteration; `break` terminates the loop.
Write a runnable Python solution to calculate the median of a numeric list.
null
from statistics import median values = [8, 2, 5, 1, 9] print(median(values))
Write Python code to store a list of programming languages. Print the value and its type.
null
languages = ["Python", "C#", "Java"] print(languages) print(type(languages).__name__)
Fix this function so it returns a value rather than printing it.
def double(number): print(number * 2)
def double(number): return number * 2 # Explanation: return sends a result back to the caller; print only displays a value.
Explain how to update the variable used to store a student's name, then show a short example.
null
student_name = "Aylin" print(student_name) # Assign a new value to the same variable. # Example: # student_name = "Aylin" # student_name = ... # replace with the new value print(student_name)
Write Python code to get the final character.
null
text = "Python 3" print(text[-1])
Write Python code to read a comma-separated list of integers safely.
null
raw = input('Enter integers separated by commas: ') try: numbers = [int(part.strip()) for part in raw.split(',') if part.strip()] except ValueError: print('Input contains a non-integer value.') else: print(numbers)
Provide code and a short explanation for how to write a function that returns both minimum and maximum values.
null
def min_max(values): if not values: raise ValueError('values must not be empty') return min(values), max(values) low, high = min_max([8, 2, 11, 4]) print(low, high)
Explain the main idea and implement: use a stack to reverse a sequence.
null
items = [1, 2, 3, 4] stack = [] for item in items: stack.append(item) reversed_items = [] while stack: reversed_items.append(stack.pop()) print(reversed_items)
Show a clear Python example that can write a function that counts words in a sentence.
null
def word_count(sentence): return len(sentence.split()) print(word_count('Python is readable and practical'))
Explain why this expression uses floor division and show the result. (practice variation 30)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Explain what this slice returns. (practice variation 7)
values = [10, 20, 30, 40, 50] print(values[1:4])
The slice includes index 1 and excludes index 4, so it prints `[20, 30, 40]`.
Explain why `input()` returns a string and convert the value to an integer. (practice variation 29)
raw = input('Enter an integer: ') number = int(raw) print(number + 1)
The built-in input() returns text. Convert it with int() when an integer is required; handle ValueError if the input may be invalid.
Write Python code to check whether an integer is even or odd.
null
number = 17 if number % 2 == 0: print('even') else: print('odd')
Demonstrate the difference between `break` and `continue`. (practice variation 31)
for number in range(1, 6): if number == 2: continue if number == 5: break print(number)
`continue` skips the rest of the current iteration; `break` terminates the loop.
Explain why this expression uses floor division and show the result. (practice variation 17)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Provide code and a short explanation for how to write a function that counts words in a sentence.
null
def word_count(sentence): return len(sentence.split()) print(word_count('Python is readable and practical'))
Describe the purpose of a generator or iterator and demonstrate how to make a custom iterable over a list in reverse.
null
class ReverseList: def __init__(self, items): self.items = list(items) def __iter__(self): return iter(self.items[::-1]) print(list(ReverseList([1, 2, 3])))
Show how to make a shallow copy of a list and explain why it matters. (practice variation 23)
original = [[1], [2]] copy = original.copy() copy[0].append(9) print(original)
A shallow copy creates a new outer list but retains references to nested objects. Mutating a nested list is visible through both lists.
Fix the off-by-one error so the loop prints 1 through 5.
for number in range(1, 5): print(number)
for number in range(1, 6): print(number) # Explanation: The stop value in range() is exclusive, so use 6 to include 5.
Explain why `list.sort()` and `sorted()` differ. (practice variation 13)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Explain why `list.sort()` and `sorted()` differ. (practice variation 31)
values = [3, 1, 2] result = sorted(values) print(result) print(values)
sorted() returns a new sorted list and leaves the original iterable unchanged. list.sort() sorts a list in place and returns None.
Give a complete example and explain how to format a price with two decimal places.
null
price = 125.5 print(f'${price:.2f}')
Provide code and a short explanation for how to find the second largest distinct number.
null
def second_largest(values): distinct = sorted(set(values)) if len(distinct) < 2: raise ValueError('At least two distinct values are required') return distinct[-2] print(second_largest([4, 8, 8, 2, 6]))
Write Python code to convert the text to lowercase.
null
text = "LEARNING PYTHON" result = text.lower() print(result)
Write code to safely convert a string to a float and handle invalid input. (practice variation 4)
raw = '3.14' try: value = float(raw) except ValueError: print('Invalid number') else: print(value)
Catch ValueError for text that cannot be converted to a float.
What is the difference between a list and a tuple?
null
A list is mutable, so its elements can be changed after creation. A tuple is immutable, so its item references cannot be reassigned. Use a list for a changing collection and a tuple for a fixed record. Example: values = [1, 2] values.append(3) point = (4, 5)
Write a runnable Python solution to write a context manager using contextlib.
null
from contextlib import contextmanager @contextmanager def managed_message(): print('start') try: yield finally: print('finish') with managed_message(): print('working')
Provide code and a short explanation for how to check whether a number is prime.
null
def is_prime(n): if n < 2: return False divisor = 2 while divisor * divisor <= n: if n % divisor == 0: return False divisor += 1 return True print(is_prime(29))
Write Python code to get the first and last characters.
null
text = "Python" print(text[0]) print(text[-1])
Explain why this expression uses floor division and show the result. (practice variation 34)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
Provide code and a short explanation for how to create a temporary file for a test.
null
from tempfile import TemporaryDirectory from pathlib import Path with TemporaryDirectory() as directory: path = Path(directory) / 'sample.txt' path.write_text('temporary data', encoding='utf-8') print(path.read_text(encoding='utf-8'))
Create a small Python program to read JSON data from a file.
null
import json with open('settings.json', encoding='utf-8') as file: settings = json.load(file) print(settings)
Write Python code to calculate the population standard deviation.
null
from statistics import pstdev values = [2, 4, 4, 4, 5, 5, 7, 9] print(pstdev(values))
Explain why this expression uses floor division and show the result. (practice variation 24)
print(7 // 2)
The `//` operator performs floor division. For positive operands, `7 // 2` evaluates to `3`.
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
42