pytnbeginer Flashcards
What are the basic data types in Python?
The basic data types in Python are int, float, str, and bool.
How do you write an if statement in Python?
An if statement in Python is written as:
if condition:
# code to execute if condition is true
What is a function in Python?
A function in Python is a block of code that performs a specific task. It is defined using the ‘def’ keyword.
How do you create a list in Python?
A list in Python is created using square brackets, e.g., my_list = [1, 2, 3]
What is a dictionary in Python?
A dictionary in Python is a collection of key-value pairs, e.g., my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
How do you handle exceptions in Python?
Exceptions in Python are handled using try/except blocks. Code that may raise an exception is placed in the try block, and the code to handle the exception is placed in the except block.
What is a class in Python?
A class in Python is a blueprint for creating objects. It is defined using the ‘class’ keyword.
How do you create a tuple in Python?
A tuple in Python is created using parentheses, e.g., my_tuple = (1, 2, 3)
What is a set in Python?
A set in Python is an unordered collection of unique elements, e.g., my_set = {1, 2, 3}
How do you read a file in Python?
To read a file in Python, use the open() function with the ‘r’ mode, e.g., with open(‘file.txt’, ‘r’) as file: content = file.read()
How do you write to a file in Python?
To write to a file in Python, use the open() function with the ‘w’ mode, e.g., with open(‘file.txt’, ‘w’) as file: file.write(‘text’)
What is a module in Python?
A module in Python is a file containing Python code that can be imported and used in other Python programs.
How do you import a module in Python?
To import a module in Python, use the import statement, e.g., import module_name
What is a package in Python?
A package in Python is a collection of modules organized in directories.
How do you install a package in Python?
To install a package in Python, use pip, e.g., pip install package_name
What is a loop in Python?
A loop in Python is used to iterate over a sequence of elements.
How do you write a for loop in Python?
A for loop in Python is written as:
for element in sequence:
# code to execute for each element
How do you write a while loop in Python?
A while loop in Python is written as:
while condition:
# code to execute while condition is true
What is the difference between a list and a tuple?
A list is mutable (can be changed), whereas a tuple is immutable (cannot be changed).
How do you access elements in a list?
Elements in a list are accessed using their index, e.g., my_list[0]