---
title: "Python: Programming Fundamentals & Best Practices"
description: "Test your knowledge of Python fundamentals with this comprehensive quiz covering data types, functions, loops, conditionals, list comprehensions, classes, exception handling, and Python programming best practices."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/quizzes/post/python-programming-fundamentals-quiz
---

# Python: Programming Fundamentals & Best Practices

Welcome to the Python Basics Quiz! This quiz is designed to test your understanding of fundamental Python concepts, syntax, and programming best practices. Each question is multiple-choice, and you'll find hints to help you along the way. Good luck!

## Questions

### 1. How do you define a function in Python?

- `func my_function():`
  - "func" is common in Swift and Go; Python uses the shorter "def" keyword.
- **`def my_function():`** ✅
  - Python uses the "def" keyword followed by the function name and a colon.
- `function my_func():`
  - "function" is used in JavaScript; Python requires "def" for standard definitions.
- `define my_func():`
  - While "def" is short for define, the full word "define" is not a valid Python keyword.

**Hint:** Short for "Define".

### 2. What is the correct way to create a list in Python?

- `my_list = {1, 2, 3}`
  - Curly braces define a Set or a Dictionary, which handle data differently than a list.
- **`my_list = [1, 2, 3]`** ✅
  - Square brackets define a list, which is an ordered and mutable collection of items.
- `my_list = (1, 2, 3)`
  - Parentheses define a Tuple. Tuples are immutable and cannot be changed after creation.
- `my_list = <1, 2, 3>`
  - Angle brackets are not used for collection initialization in standard Python syntax.

**Hint:** Uses square brackets.

### 3. How do you insert a comment in Python code?

- `// This is a comment`
  - Double slashes are used in C-style languages; in Python, // is the floor division operator.
- **`# This is a comment`** ✅
  - The hash symbol (#) instructs the interpreter to ignore the remainder of the line.
- `-- This is a comment`
  - Double dashes are used for comments in SQL and Lua, but they result in an error in Python.
- `/* This is a comment */`
  - This is C++/CSS syntax; Python uses triple quotes for multi-line documentation blocks.

**Hint:** The hash character.

### 4. Which data type is used to store Key-Value pairs?

- List
  - Lists store individual items indexed by their integer position starting at zero.
- **Dictionary** ✅
  - Dictionaries (dict) map unique keys to specific values for efficient data retrieval.
- Collection
  - "Collection" is a general category of data types, but "Dictionary" is the specific type for key-values.
- Sequence
  - Sequences like strings and lists are indexed by position, not by custom keys.

**Hint:** Think of a "Dictionary".

### 5. What is the result of 10 // 3 in Python?

- `3.33`
  - A single slash (/) performs float division, which would result in a decimal value.
- **`3`** ✅
  - The double slash (//) performs floor division, rounding down to the nearest whole integer.
- `1`
  - The number 1 is the result of the modulo operator (10 % 3), which returns the remainder.
- `0`
  - 0 would be the result if 10 were perfectly divisible by the divisor, which is not the case here.

**Hint:** This is "Floor Division".

### 6. How do you start a "for" loop in Python?

- `for (i=0; i<10; i++)`
  - This is C-style syntax; Python iterates directly over members of a sequence or range.
- **`for x in range(10):`** ✅
  - Python loops use the "in" keyword to iterate over an iterable object like a range.
- `foreach x in list:`
  - "foreach" is used in PHP and C#, but Python simply uses the "for...in" syntax.
- `for x through range(10):`
  - Python requires the specific "in" keyword to define the source of the loop iteration.

**Hint:** for item in collection:

### 7. What does the "len()" function do?

- Calculates the sum of all values
  - Summing numerical items is handled by the sum() function, not the len() function.
- **Returns the total count of items** ✅
  - The len() function returns the number of elements in strings, lists, or dictionaries.
- Finds the largest value in a list
  - Identifying the maximum value is the responsibility of the built-in max() function.
- Determines the data type of an object
  - Determining the type of a variable is handled by the type() or isinstance() functions.

**Hint:** Short for "Length".

### 8. How do you check if "a" is equal to "b"?

- `a = b`
  - A single equals sign is for variable assignment, not for checking equality.
- **`a == b`** ✅
  - The double equals (==) is the equality operator that evaluates to True or False.
- `a === b`
  - Triple equals is used for strict equality in JavaScript; Python does not use this syntax.
- `a.equals(b)`
  - While common in Java, Python uses the == operator for standard value comparison.

**Hint:** Comparison requires two symbols.

### 9. What is "PEP 8"?

- A tool for installing packages
  - The package installer for Python is called "pip", not PEP 8.
- **A style guide for Python code** ✅
  - PEP 8 provides conventions for formatting Python code to improve its readability.
- The latest version of the core
  - Python versions use decimal numbering (e.g., 3.12); PEPs are enhancement proposals.
- A library for scientific data
  - Scientific libraries include NumPy and Pandas; PEP 8 is a documentation standard.

**Hint:** It is about how code looks.

### 10. Which keyword is used to handle exceptions?

- `catch`
  - "catch" is the standard keyword in Java and C++; Python uses "except" instead.
- **`try...except`** ✅
  - The try block contains the code to attempt, while the except block catches any errors.
- `on_error...resume`
  - This syntax is found in older languages like Visual Basic and is not supported in Python.
- `try...handle`
  - Although "handle" describes the action, the specific Python keyword required is "except".

**Hint:** Try to run code, then catch the error.

### 11. What is the "self" parameter in a class method?

- It hides the method from users
  - Privacy in Python is suggested by underscores, not by the use of the self parameter.
- **It represents the class instance** ✅
  - Self allows instance methods to access the specific attributes and data of that unique object.
- It creates a new class duplicate
  - Duplicating objects requires the "copy" module rather than the self parameter.
- It is a keyword used to end a class
  - Python uses indentation to signify the end of blocks; there is no "end" keyword.

**Hint:** It refers to the specific object being used.

### 12. How do you convert a string "10" to an integer?

- `str.to_int("10")`
  - Python uses built-in constructor functions like int() rather than string methods for this.
- **`int("10")`** ✅
  - The int() function parses a string or float and returns its integer representation.
- `convert.int("10")`
  - There is no global "convert" module for basic types; int() is globally available.
- `(int)"10"`
  - This is C-style type casting; Python requires function-call syntax with parentheses.

**Hint:** int()

### 13. What does "immutable" mean?

- The object is globally accessible
  - Global accessibility refers to variable scope, not to the mutability of the data.
- **The object state cannot be changed** ✅
  - Immutable objects, such as strings and tuples, cannot be modified after they are created.
- The object is deleted after usage
  - Deletion is a function of the garbage collector, not the mutability of the object.
- The object can hold multiple types
  - The ability to hold multiple types describes a container or dynamic typing, not immutability.

**Hint:** Once it is made, it cannot be changed.

### 14. Which method adds an item to the end of a list?

- `add()`
  - The .add() method is used for Sets; lists require the .append() method.
- **`append()`** ✅
  - The .append() method adds a single element to the very end of an existing list.
- `push()`
  - While used in JavaScript and stacks, .push() is not a standard method for Python lists.
- `insert()`
  - The .insert() method requires a specific index; .append() is preferred for adding to the end.

**Hint:** Think "Attach".

### 15. What is a "Lambda" function?

- A function used for async tasks
  - Asynchronous tasks use the "async def" syntax, whereas Lambdas are for simple logic.
- **An anonymous, one-line function** ✅
  - Lambdas are small functions defined without a name, typically used for short-lived operations.
- A tool for managing memory leaks
  - Memory management is handled by the Python interpreter, not by lambda functions.
- A method for importing packages
  - Packages are loaded into a script using the "import" keyword, not lambda expressions.

**Hint:** A tiny, one-line function.

### 16. How do you check the data type of a variable "x"?

- `x.get_type()`
  - Type checking is done via global functions like type() rather than instance methods.
- **`type(x)`** ✅
  - The type() function returns the class name of the object, such as int, str, or list.
- `typeof(x)`
  - "typeof" is an operator in JavaScript; Python uses the type() function instead.
- `check_type(x)`
  - This is not a built-in function; Python uses type() or isinstance() for this purpose.

**Hint:** type()

### 17. Which keyword brings in code from another module?

- `include`
  - "include" is the keyword for C and C++; Python uses "import" to load modules.
- **`import`** ✅
  - The import keyword allows a script to access functions and classes defined in other files.
- `require`
  - "require" is used in Ruby and Node.js but is not a valid keyword in Python.
- `using`
  - "using" is found in C# and C++ namespaces; Python strictly uses "import".

**Hint:** Bring it "in".

### 18. What is the correct syntax for a "while" loop?

- `while (x < 5):`
  - While parentheses are allowed, they are not required and are less "Pythonic" than the standard syntax.
- **`while x < 5:`** ✅
  - A while loop repeats a block of code as long as the specified condition remains True.
- `while x < 5 do:`
  - The "do" keyword is not part of Python loop syntax; a colon and indentation are sufficient.
- `while x < 5 { }`
  - Curly braces are used in Java and C++; Python uses colons and whitespace for blocks.

**Hint:** while condition:

### 19. What is the purpose of "range(5)"?

- It finds a random number
  - Randomization is handled by the random module, not the range() function.
- **It generates 0 through 4** ✅
  - The range(n) function generates a sequence of integers from 0 up to, but not including, n.
- It creates 5 empty lists
  - Range only generates a sequence of integers, not container objects like lists.
- It counts all characters
  - Counting characters in a string is done with the len() function, not range().

**Hint:** It generates a sequence.

### 20. What is a "docstring"?

- A file ending in .doc
  - Docstrings are internal parts of the source code, not external Word documents.
- **A string for documentation** ✅
  - Docstrings are strings placed at the start of functions or classes to explain their purpose.
- A string that is frozen
  - This refers to immutability; docstrings are simply standard strings used for help text.
- A string used in prints
  - Any string can be printed; docstrings are specifically used for metadata and help documentation.

**Hint:** Documentation inside a string.

### 21. How do you remove the last item from a list?

- `list.remove()`
  - The .remove() method deletes an item by its value, not by its position in the list.
- **`list.pop()`** ✅
  - The .pop() method removes and returns the item at the specified index, defaulting to the last.
- `list.delete()`
  - Python uses the "del" statement for generic deletion; .delete() is not a list method.
- `list.clear()`
  - The .clear() method removes every item from the list at once, not just the last one.

**Hint:** Think of "popping" a bubble.

### 22. What is "List Comprehension"?

- A way to summarize a list
  - Summarization is done with aggregate functions like sum() or mean().
- **A concise creation syntax** ✅
  - List comprehension provides a one-line way to create a new list by iterating over an existing sequence.
- A method for list sorting
  - Sorting is achieved via the .sort() method or the sorted() built-in function.
- A tool for list validation
  - Validation involves conditional logic; comprehension is specifically about resource creation.

**Hint:** Creating a list in a single line.

### 23. Which operator is used for exponentiation?

- `^`
  - In Python, the ^ symbol represents the bitwise XOR operation, not numerical power.
- **`**`** ✅
  - The double asterisk (**) is the exponentiation operator used to raise a number to a power.
- `pow`
  - While pow(x, y) is a built-in function, the question asks for the "operator" specifically.
- `exp`
  - exp() is a function found in the math module used for calculating natural exponentials.

**Hint:** Double multiplication.

### 24. What is the "None" object in Python?

- The integer value of 0
  - 0 is a numerical value; None is a special object used to signify the absence of any value.
- **A value representing null** ✅
  - None is used to define a null variable or a function that does not return a specific result.
- The boolean value False
  - While None evaluates to False in conditions, it is a distinct object from the boolean False.
- An empty string value ""
  - An empty string is a valid string object with zero length; None belongs to the NoneType class.

**Hint:** Represents nothing.

### 25. What does the "is" keyword check?

- If values are identical
  - Value comparison is handled by the == operator, not the "is" keyword.
- **If object memory matches** ✅
  - The "is" keyword checks for object identity, verifying if two variables point to the same location in memory.
- If the variable exists
  - Checking existence is done using try/except blocks or membership tests in name scopes.
- If types are identical
  - Type comparison is done using the type() function or the isinstance() check.

**Hint:** It checks identity, not equality.

### 26. What is the output of "bool(0)"?

- True
  - In Python, only non-zero integers are considered truthy when converted to a boolean.
- **False** ✅
  - The integer 0 is considered falsy, so bool(0) will always return the False object.
- Error
  - Boolean conversion is a standard Python operation and does not produce errors for integers.
- None
  - None is its own type; the bool() function must return either True or False.

**Hint:** Numbers have truthiness.

### 27. How do you open a file for reading?

- `file.open("data", "r")`
  - The open() function is a built-in global function, not a method of a "file" object.
- **`open("data", "r")`** ✅
  - Using open() with the "r" mode parameter opens a file for read-only access.
- `read("data", "r")`
  - You must first open the file to create a file object before you can call read() on it.
- `load("data", "r")`
  - The load() function is used in the json module; standard file opening uses open().

**Hint:** open(filename, mode)

### 28. What is a "Set" in Python?

- A frozen, immutable list
  - A frozen list is similar to a Tuple; Sets are unordered and specifically remove duplicates.
- **Unordered unique items** ✅
  - A Set is a collection that automatically ensures no two elements are the same and maintains no order.
- A list of map keys
  - While dictionary keys behave like sets, a Set is a standalone collection type.
- A sorted array of data
  - Sets are unordered by definition; if you need sorting, you would use a sorted list.

**Hint:** Unordered and unique.

### 29. Which keyword returns a function value?

- `send`
  - "send" is used in generator contexts; standard function results use "return".
- **`return`** ✅
  - The return keyword exits a function and passes the resulting object back to the caller.
- `yield`
  - "yield" is used to create generators; it pauses execution rather than fully exiting like "return".
- `print`
  - Printing displays a value to the console but does not pass a value back to the function caller.

**Hint:** Return.

### 30. What is the "if __name__ == '__main__'" block?

- Identifies script author
  - Author information is typically kept in comments or setup files, not in logic blocks.
- **Ensures direct execution** ✅
  - This block prevents code from running automatically when a script is imported as a module.
- Sets the application name
  - Application names are defined by the filename or project configuration, not by this conditional.
- Validates user permissions
  - Permission validation requires the os or sys modules; this block is for execution control.

**Hint:** It controls execution when a file is imported.
