Unlock hundreds more features
Save your Quiz to the Dashboard
View and Export Results
Use AI to Create Quizzes and Analyse Results

Sign inSign in with Facebook
Sign inSign in with Google

Take the Python Fundamentals Quiz Now

Quickly assess core programming principles in Python

Difficulty: Moderate
Questions: 20
Learning OutcomesStudy Material
Colorful paper art displaying a trivia quiz on Python Fundamentals

Pondering if you've mastered core Python concepts? This Python fundamentals quiz offers a concise way to evaluate your grasp of syntax, variables, and control flow. Programming enthusiasts and students alike will gain confidence as they identify strengths and uncover areas for improvement. Feel free to customize this assessment in our editor to tailor questions to your learning goals. Explore more Python Programming Practice Quiz or challenge yourself with a Python Variables Basics Quiz, then discover other quizzes to keep sharpening your skills.

How do you print "Hello, World!" to the console in Python 3?
print("Hello, World!")
System.out.println("Hello, World!")
echo "Hello, World!"
printf("Hello, World!")
In Python 3, the built-in print() function is used to display output to the console. The other options represent syntax from different languages or are invalid in Python.
Which of the following Python data types is mutable?
list
tuple
frozenset
str
Lists are mutable, meaning you can change their content after creation. Tuples, strings, and frozensets are immutable types that cannot be altered once created.
Which of these is a valid variable name in Python?
my-var
class
_value
2nd_var
Variable names must start with a letter or underscore and can contain letters, digits, or underscores. '_value' follows these rules, while '2nd_var' starts with a digit, 'my-var' contains a hyphen, and 'class' is a reserved keyword.
How do you write a single-line comment in Python?
// comment
/* comment */
# comment
Python uses the hash symbol '#' to denote single-line comments. Other options represent comment syntax from different languages or are invalid in Python.
What data type is returned by the expression 3 > 2 in Python?
bool
int
str
NoneType
Comparison operators in Python return a Boolean result, so '3 > 2' evaluates to True, which is of type bool. 'int', 'str', and 'NoneType' do not describe Boolean values.
Which function returns the number of items in a list?
len(list)
count(list)
size(list)
list.length()
The len() function is a built-in Python function that returns the number of items in a sequence, such as lists, tuples, or strings. The other options are not valid built-in functions for obtaining length.
Given my_list = [1, 2, 3], which method adds the element 4 to the end of the list?
my_list.append(4)
my_list.extend(4)
my_list.insert_end(4)
my_list.add(4)
The append() method adds a single element to the end of a list. Methods like add() or insert_end() do not exist, and extend() expects an iterable to add multiple elements.
What is the output of the following code? if 5 > 3: print("A") elif 5 > 1: print("B") else: print("C")
B
A
C
AB
The if statement checks '5 > 3' first, which is True, so it executes the first print and skips the elif and else blocks. Only 'A' is printed.
What is the result of the list comprehension [x * 2 for x in range(3)]?
[1, 2, 3]
[0, 1, 2]
[2, 4, 6]
[0, 2, 4]
The list comprehension multiplies each x in range(3) (i.e., 0, 1, 2) by 2, resulting in [0, 2, 4]. The other lists do not match this transformation.
How do you open a file named "data.txt" for reading?
open("data.txt")
open("data.txt", "r")
open("data.txt", "w")
file("data.txt", "r")
open("data.txt", "r") opens the file explicitly in read mode. Opening with "w" would open it for writing, and file() is not a built-in in Python 3.
Which exception is raised when referencing an undefined variable?
AttributeError
ValueError
NameError
TypeError
Referencing a variable that has not been defined raises a NameError in Python. The other exceptions are raised in different situations.
What is the correct syntax to catch exceptions in Python?
do/while
try/except
try/catch
catch/except
Python uses try and except blocks to catch and handle exceptions. The syntax try/catch is common in other languages but not in Python.
Given d = {'a': 1, 'b': 2}, which method returns a view of the dictionary's keys?
d.get()
d.values()
d.keys()
keys(d)
The keys() method returns a view object containing the dictionary's keys. The get() method retrieves values, and values() returns its values.
How do you convert the string "123" to an integer in Python?
int("123")
toInt("123")
float("123")
str(123)
The int() constructor converts a string of digits into an integer. functions like float() convert to floating-point, and str() converts to string.
Which is the correct way to define a function that returns the sum of two parameters a and b?
add = lambda a, b: a + b
def add(a, b): return a + b
def add a, b: return a + b
function add(a, b): return a + b
function definitions in Python begin with the 'def' keyword followed by the function name and parameters. The 'lambda' expression is valid but not used with the def syntax in this form.
What is the output of the following code? add = lambda x, y: x + y print(add(3, 4))
'7'
Error
lambda x, y: x + y
7
A lambda expression creates an anonymous function, and calling add(3, 4) returns the integer 7. The result is printed as an integer, not a string.
What type of object is produced by the expression (x * 2 for x in range(3))?
list
generator
iterator
tuple
Parentheses with an expression inside produce a generator object in Python, which generates items on demand. It is not a list or tuple.
How do you apply a decorator named my_decorator to a function func?
@my_decorator def func(): pass
def @my_decorator func(): pass
decorator @my_decorator func()
my_decorator(func)
Decorators in Python are applied using the '@' symbol placed directly above the function definition. The other options are not valid decorator syntax.
Which keyword allows you to modify a global variable inside a function?
global
nonlocal
extern
static
The global keyword allows functions to modify variables defined at the module level. nonlocal applies to enclosing function scopes, and static or extern are not Python keywords.
What exception is raised when dividing by zero in Python?
ValueError
ZeroDivisionError
ArithmeticError
OverflowError
Dividing by zero in Python raises a ZeroDivisionError. While ArithmeticError is a base class for numeric errors, Python specifically raises ZeroDivisionError.
0
{"name":"How do you print \"Hello, World!\" to the console in Python 3?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"How do you print \"Hello, World!\" to the console in Python 3?, Which of the following Python data types is mutable?, Which of these is a valid variable name in Python?","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Learning Outcomes

  1. Analyze Python syntax and structure patterns
  2. Identify correct use of variables and data types
  3. Apply control flow statements in sample scenarios
  4. Demonstrate function creation and invocation in Python
  5. Evaluate common error messages and debugging techniques

Cheat Sheet

  1. Master Python's Indentation Rules - Python uses indentation instead of braces to define code blocks, so keeping your spaces or tabs consistent is like giving Python a clear roadmap. Even a single extra space can trigger an IndentationError and derail your script. Stay neat and watch your code flow smoothly. Python Syntax | GeeksforGeeks
  2. Understand Python's Dynamic Typing - Variables in Python are like shape-shifters - they take on the type of the value you assign without explicit declarations. Assign x = 10 and Python treats x as an integer, then y = "Hello" makes y a string at runtime. Embrace this flexibility, but remember to keep track of your types to avoid unexpected surprises. Python Syntax | GeeksforGeeks
  3. Utilize Control Flow Statements Effectively - Direct your program's storyline using if-else, for loops, and while loops to handle different scenarios. For example, a for loop with for i in range(5) repeats tasks effortlessly without manual repetition. Mastering these statements makes your code logical, dynamic, and fun to read. Python Syntax | GeeksforGeeks
  4. Define and Call Functions Properly - Think of functions as mini-program characters that perform specific tasks, keeping your code organized and reusable. You define them with def greet(name): then call greet("Alice") when you need a friendly hello. Good function etiquette means clear names and consistent parameters for smooth teamwork. Python Syntax | GeeksforGeeks
  5. Recognize Common Syntax Errors - Syntax errors are like forgetting the secret handshake: Python refuses to play ball if you miss a colon or parentheses. For example, omitting the colon in if x > 0 will lead to a SyntaxError before your code even runs. Learn to spot these misspellings and mismatches early to keep your debugging time minimal. Debugging - How to Think Like a Computer Scientist: Learning with Python 3
  6. Handle Exceptions Gracefully - Wrap risky operations in try-except blocks like wearing crash helmets for your code to prevent it from crashing on unexpected inputs. For example, dividing by zero inside a try block will be caught by except ZeroDivisionError, allowing you to print a friendly error message instead of a full-blown traceback. Mastering exception handling turns your scripts into robust applications. Python Debugging Handbook - How to Debug Your Python Code
  7. Use Print Statements for Debugging - Sprinkle print statements throughout your code to reveal variable values and program flow in real time. It's like leaving breadcrumbs to find out where your script might be wandering off course. While not a final solution, print debugging is a quick trick to diagnose issues in a flash. Python Debugging Handbook - How to Debug Your Python Code
  8. Leverage Python's Built-in Debugger (PDB) - Meet PDB, your interactive detective tool for setting breakpoints and stepping through code line by line. Insert import pdb; pdb.set_trace() to pause execution and inspect variables in the console. If print debugging feels like a flashlight, PDB is a full CSI kit for your code. Python Debugging Handbook - How to Debug Your Python Code
  9. Be Aware of Common Bugs - Typos in variable names, missing parentheses, or wrong indentation can sneakily cause unexpected errors. For example, leaving out a closing parenthesis in print("Hello, World!") will throw a SyntaxError and halt execution. Familiarize yourself with these typical pitfalls to squash bugs before they bug you. Debugging :: BYU CS 111
  10. Practice Writing Clean and Readable Code - Consistent naming conventions, clear comments, and modular functions turn your scripts into maintainable masterpieces. For example, a function named calculate_area(width, height) is self-explanatory and easy to test. Adopt best practices early to make collaboration and future updates a breeze. Python Syntax | GeeksforGeeks
Powered by: Quiz Maker