Python Practice Test — Questions and Answers
Question 1: What is Python?
- General-purpose interpreted, interactive language, object-oriented and high-level programming language (Correct answer)
- General-purpose interpreted language
- General-purpose interpreted and interactive language
- General-purpose interpreted, interactive language and object-oriented language
Correct answer: General-purpose interpreted, interactive language, object-oriented and high-level programming language
Python is accurately described as a general-purpose, high-level programming language. It is interpreted, meaning code is executed line by line rather than compiled, and interactive, allowing for direct execution of commands. Furthermore, Python supports multiple programming paradigms, including object-oriented programming, making it versatile for various applications.
Question 2: Which license does the Python source code fall under?
- MIT
- GPL (Correct answer)
- EPL
- Apache
Correct answer: GPL
The Python source code is licensed under the Python Software Foundation License (PSF License), which is an OSI-approved, free software license. While not strictly the GNU General Public License (GPL) itself, the PSF License is explicitly designed to be compatible with the GPL. This compatibility allows Python to be freely used, modified, and distributed, including in projects that are licensed under the GPL.
Question 3: Who created Phyton?
- Guido van Rossum (Correct answer)
- Brendan Eich
- Rasmus Lerdorf
- Larry Wall
Correct answer: Guido van Rossum
Python was created by Guido van Rossum in the late 1980s, with its first public release in 1991. He served as Python's 'Benevolent Dictator For Life' (BDFL) until 2018, overseeing its development and direction. His vision and leadership shaped Python into the popular and versatile language it is today.
Question 4: Which of the following is a Python environment variable that isn't valid?
- PYTHONSTARTUP
- PYTHONLIBRARY (Correct answer)
- PYTHONPATH
- PYTHONCASEOK
Correct answer: PYTHONLIBRARY
Python uses several environment variables to configure its behavior, such as `PYTHONSTARTUP` (for an initialization script), `PYTHONPATH` (for module search paths), and `PYTHONCASEOK` (on Windows, for case-insensitive imports). `PYTHONLIBRARY` is not a standard or recognized environment variable used by the Python interpreter for its configuration or operation.
Question 5: What specifically is PYTHONPATH?
- It tells the Python compiler where to locate the module files imported into a program
- It tells the Python interpreter where to locate the module files imported into a program (Correct answer)
- It is used for installation of Python
- None of these
Correct answer: It tells the Python interpreter where to locate the module files imported into a program
The `PYTHONPATH` environment variable is crucial for the Python interpreter. It specifies a list of directories that the interpreter should search for module files when an `import` statement is encountered. This allows users to extend Python's default search path and include custom modules or packages located in non-standard directories.
Question 6: What is the meaning of PYTHONHOME?
- It is used in Windows to instruct Python to find the first case-insensitive match in an import statement
- It is an alternative module search path (Correct answer)
- It contains the path of an initialization file containing Python source code
- None of these
Correct answer: It is an alternative module search path
The `PYTHONHOME` environment variable is used to specify an alternative Python installation root directory. When set, it tells the Python interpreter where to find its standard library modules and other core files, effectively acting as an alternative base for the module search path. This is particularly useful for embedding Python or managing multiple Python installations.
Question 7: What is the purpose of PYTHONSTARTUP?
- It is needed while booting of a particular process
- It is executed every time you start the compiler
- It is executed every time you start the interpreter (Correct answer)
- None of these
Correct answer: It is executed every time you start the interpreter
PYTHONSTARTUP is an environment variable that points to a Python script. When the Python interpreter starts in interactive mode, it automatically executes the commands in the script specified by this variable. This allows users to define custom functions, import modules, or set up a specific environment that is available every time they enter the interactive interpreter.
Question 8: What does the -d command line option do?
- It provides debug output (Correct answer)
- It generates optimized bytecode
- It provides debug input
- None of the above
Correct answer: It provides debug output
The `-d` command-line option for the Python interpreter enables debug output. Specifically, it turns on debugging output for the parser, which can be useful for understanding how Python processes its source code. This option helps developers diagnose issues related to parsing or compilation by providing more verbose information about the interpreter's internal operations.
Question 9: What is PYTHONCASEOK, and how does it work?
- It is used to find the first case-insensitive match in an import statement (Correct answer)
- It is used to find the first case-insensitive match in a package statement
- It is used to find the first case-sensitive match in an import statement
- None of these
Correct answer: It is used to find the first case-insensitive match in an import statement
PYTHONCASEOK is an environment variable that influences how Python handles module imports on case-insensitive file systems, like Windows. When set, Python will attempt to find a module even if its filename's casing doesn't exactly match the import statement. It allows for a case-insensitive search for the module file, importing the first match it finds.
Question 10: Which of these naming conventions for Python identifiers is incorrect?
- An identifier can start with a number (Correct answer)
- An identifier can start with lowercase letter
- An identifier can start with underscore(_)
- An identifier can start with uppercase letter
Correct answer: An identifier can start with a number
In Python, identifiers (like variable names, function names, class names) must start with a letter (a-z, A-Z) or an underscore (_). They cannot begin with a number. While numbers can be part of an identifier after the first character, starting with a digit is a syntax error.
Question 11: What does the following code provide as an output? <br> for x in range(0.5, 5.5, 0.5): <br> print(x)
- The Program executed with errors (Correct answer)
- [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5]
- [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
Correct answer: The Program executed with errors
The `range()` function in Python only accepts integer arguments for its start, stop, and step parameters. Providing floating-point numbers like 0.5 or 5.5 will raise a `TypeError`. Therefore, this code will result in an error during execution because `range()` cannot handle non-integer values.
Question 12: What does the following code output? <br> var = "James" * 2 * 3 <br> print(var)
- Error: invalid syntax
- JamesJamesJamesJamesJamesJames (Correct answer)
- JamesJamesJamesJamesJames
Correct answer: JamesJamesJamesJamesJamesJames
In Python, the `*` operator can be used to repeat a string. The expression `"James" * 2` evaluates to "JamesJames". This result is then multiplied by 3, meaning "JamesJames" is repeated three times, leading to the final string "JamesJamesJamesJamesJamesJames".
Question 13: Is it possible to utilize the "else" clause in loops? <br> as an example: <br> for i in range(1, 5): <br> print(i) <br> else: <br> print("this is else block statement" )
- A) Yes (Correct answer)
- B) No
Correct answer: A) Yes
Python allows an `else` clause to be used with `for` and `while` loops. The code inside the `else` block is executed if the loop completes normally (i.e., without being terminated by a `break` statement). In this example, the loop finishes iterating through all numbers from 1 to 4, so the `else` block will execute and print its statement.
Question 14: What is the output of the code below? <br> listOne = [20, 40, 60, 80] <br> listTwo = [20, 40, 60, 80] <br> print(listOne == listTwo) <br> print(listOne is listTwo)
- False True
- True True
- True False (Correct answer)
Correct answer: True False
The `==` operator checks for value equality, meaning it compares the contents of the two lists. Since `listOne` and `listTwo` contain the same elements, `listOne == listTwo` is `True`. The `is` operator, however, checks for identity, meaning if two variables refer to the exact same object in memory. Since `listOne` and `listTwo` are distinct list objects, `listOne is listTwo` is `False`.
Question 15: In Python, is a string immutable? <br> Whenever we modify the string, Python Always creates a new String and assigns a new string to that variable.
- A) False
- B) True
Strings in Python are immutable data types. This means that once a string object is created, its content cannot be changed. Any operation that appears to "modify" a string, such as concatenation or slicing, actually results in the creation of a brand new string object with the desired changes, and the variable is then reassigned to point to this new object.
Question 16: What does the following code output? sampleList = ["Jon", "Kelly", "Jessa"] <br> sampleList.append(2, "Scott") <br> print(sampleList)
- [‘Jon’, ‘Kelly’, ‘Jessa’, ‘Scott’]
- [‘Jon’, ‘Scott’, ‘Kelly’, ‘Jessa’]
- The program executed with errors (Correct answer)
- [‘Jon’, ‘Kelly’, ‘Scott’, ‘Jessa’]
Correct answer: The program executed with errors
The `append()` method for Python lists takes exactly one argument: the item to be added to the end of the list. In this code, `sampleList.append(2, "Scott")` attempts to pass two arguments. This will raise a `TypeError` because `append()` was called with an incorrect number of arguments.
Question 17: What does the following code output? <br> var1 = 1 <br> var2 = 2 <br> var3 = "3" <br> print(var + var2 + var3)
- 3
- 9
- Error. Mixing operators between numbers and strings are not supported
- 126
Python does not allow direct concatenation or addition of different data types like integers and strings using the `+` operator. The expression `var1 + var2` (1 + 2) would evaluate to 3, but then attempting to add this integer result to `var3` (which is the string "3") will raise a `TypeError`. To combine them, `var3` would need to be converted to an integer or the numbers converted to strings.
Question 18: What does following code output? <br> str = "pynative" <br> print (str[1:3])
- pyn
- py
- yna
- yn (Correct answer)
Correct answer: yn
Python string slicing uses the syntax `[start:end]`, where `start` is the inclusive starting index and `end` is the exclusive ending index. In "pynative", 'p' is at index 0, 'y' at index 1, 'n' at index 2, and 'a' at index 3. Therefore, `str[1:3]` extracts characters from index 1 up to (but not including) index 3, resulting in 'y' and 'n'.
Question 19: What does the following code output? <br> def calculate (num1, num2=4): <br> res = num1 * num2 <br> print(res) <br> calculate(5, 6)
- The program executed with errors
- 30 (Correct answer)
- 20
Correct answer: 30
The `calculate` function is defined with a default argument `num2=4`. However, when `calculate(5, 6)` is called, the value `6` is explicitly passed for `num2`, overriding the default. So, `num1` becomes 5 and `num2` becomes 6. The function then calculates `res = 5 * 6`, which is 30, and prints this result.
Question 20: What does the following code output? <br> sampleSet = {"Jodi", "Eric", "Garry"} <br> sampleSet.add(1, "Vicki") <br> print(sampleSet)
- The program executed with error (Correct answer)
- {‘Vicki’, ‘Jodi’, ‘Garry’, ‘Eric’}
- {‘Jodi’, ‘Vicki’, ‘Garry’, ‘Eric’}
Correct answer: The program executed with error
The `add()` method for Python sets takes exactly one argument: the element to be added to the set. Sets are unordered collections of unique elements. In this code, `sampleSet.add(1, "Vicki")` attempts to pass two arguments. This will raise a `TypeError` because the `add()` method was called with an incorrect number of arguments.
Question 21: What does the following code output? <br> for i in range(10, 15, 1): <br> print( i, end=', ')
- A) 10, 11, 12, 13, 14, 15,
- B) 10, 11, 12, 13, 14, (Correct answer)
Correct answer: B) 10, 11, 12, 13, 14,
The `range(start, stop, step)` function generates a sequence of numbers starting from `start` (inclusive) up to `stop` (exclusive), incrementing by `step`. Here, `range(10, 15, 1)` will produce numbers 10, 11, 12, 13, and 14. The `print()` function's `end=', '` argument ensures that each number is followed by a comma and a space, rather than a newline.
Question 22: What does the following code output? <br> valueOne = 5 ** 2 <br> valueTwo = 5 ** 3 <br> print(valueOne) <br> print(valueTwo)
- Error: invalid syntax
- 10 15
- 25 125 (Correct answer)
Correct answer: 25 125
The `**` operator in Python denotes exponentiation. `5 ** 2` calculates 5 raised to the power of 2, which is 5 * 5 = 25. Similarly, `5 ** 3` calculates 5 raised to the power of 3, which is 5 * 5 * 5 = 125. The code then prints these two results on separate lines.
Question 23: What does the following code output? <br> print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j))
- False True True True (Correct answer)
- False True False True
- C)True True False True
- True True False True
Correct answer: False True True True
The `bool()` function converts a value to its boolean equivalent. In Python, zero (0), empty sequences/collections, and `None` are considered "falsy". All other numbers (including non-zero integers, floats, and complex numbers) are considered "truthy". Therefore, `bool(0)` is `False`, while `bool(3.14159)`, `bool(-3)`, and `bool(1.0+1j)` are all `True`.
Question 24: What is print(type(0xFF)data )'s type?
- hexint
- number
- int (Correct answer)
- hex
Correct answer: int
The literal `0xFF` represents a hexadecimal number. In Python, hexadecimal literals (prefixed with `0x` or `0X`) are interpreted as integers. Therefore, `type(0xFF)` will return `<class 'int'>`, indicating that it is an integer data type.
Question 25: What data type does the following have? <br> aTuple = (1, 'Jhon', 1+3j) <br> print(type(aTuple[2:3]))
- tuple (Correct answer)
- list
- complex
Correct answer: tuple
Slicing a tuple, even if the slice contains only one element, always returns a new tuple. `aTuple[2:3]` extracts the element at index 2 (which is `1+3j`) as a slice. Because it's a slice of a tuple, the result is a new tuple containing that single element, not the element itself. Therefore, `type(aTuple[2:3])` will be `<class 'tuple'>`.
What is Python?