3 Flashcards
Task
Answer and Rules
Create a variable with your name and print it.
{‘name = “Your Name”\nprint(name)’, ‘Use meaningful variable names and print to display the output.’}
Write a function that returns the square of a number.
{‘def square(number):\n return number**2’, ‘Define a function with one parameter and return the squared value.’}
Create a list of your favorite fruits and print the third item.
{‘fruits = [“apple”, “banana”, “cherry”]\nprint(fruits[2])’, ‘Use list indexing to access elements.’}
Write a program to check if a number is even or odd.
{‘number = 5\nif number % 2 == 0:\n print(“Even”)\nelse:\n print(“Odd”)’, ‘Use if-else statement to check conditions.’}
Create a dictionary with keys as fruits and values as their colors.
{‘fruit_colors = {“apple”: “red”, “banana”: “yellow”, “cherry”: “red”}’, ‘Create and use dictionaries for key-value pairs.’}
Write a program that reads a file and prints its contents.
{‘with open(“file.txt”, “r”) as file:\n content = file.read()\n print(content)’, ‘Use with statement for file handling.’}
Create a class called ‘Animal’ with a method that prints ‘I am an animal’.
{‘class Animal:\n def speak(self):\n print(“I am an animal”)’, ‘Define a class and a method.’}
Write a function that takes a list and returns a new list with unique elements.
{‘def unique_elements(lst):\n return list(set(lst))’, ‘Convert list to set and back to list to remove duplicates.’}
Write a program to handle division by zero using try/except.
{‘try:\n result = 10 / 0\nexcept ZeroDivisionError:\n print(“Cannot divide by zero”)’, ‘Use try/except to handle exceptions.’}
Create a virtual environment and install a package in it.
{‘python -m venv myenv\nsource myenv/bin/activate\npip install package_name’, ‘Use virtual environments to manage dependencies.’}
Write a unit test for a function that adds two numbers.
{‘import unittest\ndef add(a, b):\n return a + b\nclass TestAddFunction(unittest.TestCase):\n def test_add(self):\n self.assertEqual(add(2, 3), 5)’, ‘Write unit tests to verify code correctness.’}
Format a string to include your name and age using f-strings.
{‘name = “John”\nage = 30\nprint(f”My name is {name} and I am {age} years old.”)’, ‘Use f-strings for string formatting.’}
Write a program that counts the occurrences of each word in a given text.
{‘text = “hello world”\nword_counts = {}\nfor word in text.split():\n word_counts[word] = word_counts.get(word, 0) + 1’, ‘Use dictionary to count word occurrences.’}
Use a set to remove duplicates from a list.
{‘numbers = [1, 2, 2, 3, 4, 4]\nunique_numbers = list(set(numbers))’, ‘Use set to remove duplicates from a list.’}