6 Flashcards
How do you calculate the length of a string in Python?
def string_length(s):\n return len(s) @@@ Use the built-in len() function to get the length of a string.
How can you check if a number is prime in Python?
def is_prime(num):\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True @@@ Use a loop to check divisibility and determine primality.
How do you find the sum of all numbers in a list?
numbers = [1, 2, 3, 4, 5]\nsum_numbers = sum(numbers) @@@ Use the built-in sum() function to calculate the sum of a list.
How do you find the minimum value in a list?
def find_min(lst):\n return min(lst) @@@ Use the built-in min() function to find the minimum value in a list.
How do you reverse a list in Python?
lst = [1, 2, 3, 4, 5]\nreversed_lst = lst[::-1] @@@ Use slicing to reverse a list.
How do you iterate over keys and values in a dictionary?
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}\nfor key, value in my_dict.items():\n print(key, value) @@@ Iterate over dictionary keys and values using the items() method.
How do you concatenate two lists in Python?
def concatenate_lists(lst1, lst2):\n return lst1 + lst2 @@@ Use the + operator to concatenate two lists.
How do you print the first 10 natural numbers using a loop?
for i in range(1, 11):\n print(i) @@@ Use a for loop to print numbers in a range.
How do you check if a number is in a given range?
def is_in_range(num, start, end):\n return start <= num <= end @@@ Use comparison operators to check if a number is within a range.
How do you find the GCD of two numbers in Python?
def gcd(a, b):\n while b:\n a, b = b, a % b\n return a @@@ Use the Euclidean algorithm to find the greatest common divisor.
How do you calculate the area of a rectangle using a class?
class Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n def area(self):\n return self.width * self.height @@@ Define a class with an __init__ method and an area method.
How do you find the largest of three numbers?
def largest_of_three(a, b, c):\n return max(a, b, c) @@@ Use the built-in max() function to find the largest of three numbers.
How do you convert a list of integers into a single integer?
lst = [1, 2, 3, 4]\nnumber = int(‘‘.join(map(str, lst))) @@@ Use join() and map() to convert a list of integers to a single integer.
How do you check if a string is a pangram?
def is_pangram(s):\n alphabet = set(‘abcdefghijklmnopqrstuvwxyz’)\n return alphabet <= set(s.lower()) @@@ Check if all alphabet letters are present in the string.
How do you merge two sorted lists into a single sorted list?
def merge_sorted_lists(lst1, lst2):\n return sorted(lst1 + lst2) @@@ Use the sorted() function to merge and sort two lists.