computer science coding Flashcards
What is a variable in Python?
A variable stores data that can be used and changed in a program. Example: x = 5
How do you create a list in Python?
Use square brackets. Example: my_list = [1, 2, 3, 4]
What is a function in Python?
A function is a block of code that performs a specific task. Example:
python
CopyEdit
def greet():
print(“Hello!”)
How do you write a loop that counts from 1 to 5?
python
CopyEdit
for i in range(1, 6):
print(i)
What is an if statement used for in Python?
To make decisions in code. Example:
python
CopyEdit
if x > 10:
print(“x is greater than 10”)
How do you write a comment in Python?
Use the # symbol. Example: # This is a comment
What is a dictionary in Python?
A collection of key-value pairs. Example:
python
CopyEdit
my_dict = {“name”: “Aarav”, “age”: 16}
What does the input() function do?
It gets user input as a string. Example:
python
CopyEdit
name = input(“Enter your name: “)
How do you handle errors in Python?
Use try and except blocks. Example:
python
CopyEdit
try:
print(10 / 0)
except ZeroDivisionError:
print(“Cannot divide by zero!”)
What does the len() function do?
It returns the length of a list, string, or other iterable. Example:
python
CopyEdit
len(“Hello”) # Output: 5
How do you open and read a file in Python?
python
CopyEdit
with open(“file.txt”, “r”) as file:
content = file.read()
What is a loop, and what types are there in Python?
Loops repeat code. Python has for loops and while loops.
How do you define a class in Python?
python
CopyEdit
class Student:
def __init__(self, name):
self.name = name