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

Python Variables Basics Quiz Challenge

Assess Your Understanding of Python Variables Basics

Difficulty: Moderate
Questions: 20
Learning OutcomesStudy Material
Colorful paper art featuring Python Variables Basics Quiz questions and answers.

Testing your Python variable skills has never been easier. This interactive Python variables quiz dives into naming rules, assignment methods, and scope essentials to boost your coding fundamentals. Whether you're a complete beginner or brushing up on key concepts, you'll gain confidence and clarity with instant feedback and detailed explanations. Plus, you can tweak any question in our editor to suit your learning needs. When you're ready, try our Python Fundamentals Quiz or sharpen your practice with the Python Programming Practice Quiz, and don't forget to explore other quizzes for more challenges.

Which of the following is a valid Python variable name?
2ndVar
var_name2
_2name
var-name
Python variable names must start with a letter or underscore and can contain letters, digits, or underscores. They cannot start with a digit or include hyphens.
What will be the value of x after executing the statement x = 5?
5
error
 
"5"
The assignment operator sets x to the integer value 5. There is no error and it is not stored as a string.
After executing the code a = 10; a = a + 5, what is the new value of a?
10
5
15
error
The expression a + 5 adds 5 to the current value of a (which is 10) and then reassigns it, resulting in 15.
What is the output of type("hello") in Python?
str
"string"
The type() function returns the class of the object, and string literals are instances of the str class in Python.
Which of these is an example of a descriptive variable name according to best practices?
a
data
x
user_age
Best practices recommend using clear and descriptive names like user_age that convey the variable's purpose. Single-letter names are discouraged except in very limited scopes.
Given the code x = 3; y = x; x = 5, what is the value of y?
 
5
3
error
When y = x is executed, y gets a copy of the current value of x (3). Changing x afterward does not affect y.
Which function converts the string "123" to an integer?
str(123)
bool("123")
float("123")
int("123")
The int() function converts a numeric string into an integer type. The other functions produce different types or do not perform integer conversion.
What will be the type of the result of float(5)?
int
bool
float
str
Applying float() to an integer converts it to a floating-point number, so the resulting type is float.
Which of the following is NOT a valid variable name in Python?
variable2
foo_bar
def
myVar
def is a reserved keyword in Python for defining functions and cannot be used as a variable name. The other options follow naming rules.
After executing a, b, c = [1, 2, 3], what is the value of b?
error
1
2
3
Unpacking assigns the first list element to a, the second to b, and the third to c. Thus b receives the value 2.
What happens when you run this code? a = [1,2,3]; x, y = a; print(x)
2
1
ValueError
None
Unpacking requires the number of variables to match the number of list elements. Here there are 3 elements but only 2 variables, so a ValueError is raised.
What is a recommended practice for naming boolean variables in Python?
Prefix with is_ or has_
Include hyphens
Start with a number
Use all uppercase letters
Boolean variables are conventionally prefixed with is_ or has_ to make their purpose clear (e.g., is_active). The other options violate naming conventions.
What will this code output? x = 10; def func(): x = 5; print(x); func(); print(x)
5 then 5
5 then 10
10 then 5
10 then 10
Inside func(), x refers to a new local variable and prints 5. The global x remains 10, so the second print outputs 10.
Which built-in function would you use to check the data type of a variable x?
type(x)
len(x)
isinstance(x)
id(x)
The type() function returns the type of its argument. isinstance() checks membership in a type but does not directly return the variable's type.
Which of these statements correctly swaps the values of a and b in Python?
swap(a, b)
a, b = b, a
a = b; b = a
a = (b, a)
Python supports tuple unpacking to swap values without a temporary variable. a, b = b, a assigns the old b to a and the old a to b in one statement.
What keyword allows modification of a global variable inside a function?
global
static
nonlocal
modify
Using the global keyword inside a function tells Python to refer to the variable in the global scope. nonlocal is used for enclosing (non-global) scopes.
Given the code def outer(): x = 1; def inner(): nonlocal x; x = 2; inner(); print(x). What does calling outer() print?
Error
1
None
2
The nonlocal keyword in inner() allows modification of x defined in the outer function. After inner() runs, x becomes 2 and that value is printed.
What does the following code print? a = [1,2,3]; b = a; b[0] = 10; print(a[0])
10
None
1
Error
Lists are mutable and b is a reference to the same list as a. Modifying b[0] also changes a[0], so the printed value is 10.
What is the result of int(3.8) in Python?
3
Error
3.8
4
The int() function truncates the decimal portion of a float, converting 3.8 to the integer 3 rather than rounding. It does not raise an error in this case.
Given the unpacking a, *middle, b = [1,2,3,4,5], what is the value of middle?
Error
[3]
[1,2,3,4]
[2,3,4]
The starred expression *middle collects all items between the first and last in the list. Hence middle becomes [2,3,4].
0
{"name":"Which of the following is a valid Python variable name?", "url":"https://www.quiz-maker.com/QPREVIEW","txt":"Which of the following is a valid Python variable name?, What will be the value of x after executing the statement x = 5?, After executing the code a = 10; a = a + 5, what is the new value of a?","img":"https://www.quiz-maker.com/3012/images/ogquiz.png"}

Learning Outcomes

  1. Identify Python variable naming conventions and rules
  2. Demonstrate variable assignment and reassignment
  3. Apply data type inspection and type conversion
  4. Analyse variable scope within functions and modules
  5. Evaluate best practices for clear variable names
  6. Master multiple assignment and unpacking methods

Cheat Sheet

  1. Understand Python's Variable Naming Rules - Think of variable names as your code's little ID tags: they must start with a letter or underscore, can only contain letters, numbers, and underscores, and they're case-sensitive (so "age", "Age", and "AGE" are three distinct buddies!). Mastering these rules helps you avoid sneaky syntax errors and keeps your code looking sharp. d3schools.com
  2. Adopt Snake Case for Readability - In Python, snake_case is king: use lowercase letters and underscores to separate words (for example, "student_name" instead of "studentName"). This neat convention makes your code feel like a well-organized library where every book has its place. Following snake_case lets teammates (and future you!) dive into your code without a headache. geeksforgeeks.org
  3. Assign and Reassign Variables Confidently - Python's dynamic typing is like a shape-shifting superpower: you can do `x = 5` one moment and then `x = "hello"` the next, with no fuss or magic incantations required. This flexibility speeds up prototyping and experimentation, especially when you're tinkering on a weekend hackathon. Just keep track of your types, and you'll avoid any surprise plot twists! ipython.ai
  4. Inspect Data Types with the type() Function - When in doubt, call `type(your_variable)` to reveal its secret identity - whether it's an integer, string, list, or something more exotic. This handy check is your built-in debug tool, letting you catch type-related glitches before they sneak into production. It's like having X-ray vision for your code! ipython.ai
  5. Perform Type Conversion When Necessary - Converting data types is as easy as snapping your fingers with functions like `int()`, `float()`, and `str()`, so you can turn `"123"` into `123` or `3.14` into `"3.14"`. This ability to swap forms on the fly keeps your data flowing smoothly between calculations, text operations, and beyond. Just remember to handle errors gracefully when conversions can fail! ipython.ai
  6. Grasp Variable Scope in Functions and Modules - Variables declared inside a function live in their own cozy little world (local scope), while those defined outside float around globally. Knowing where your variables "live" prevents accidental mix-ups and mysterious bugs when you don't see the values you expected. It's like respecting personal boundaries - your code will thank you! coderivers.org
  7. Choose Descriptive Variable Names - Skip the cryptic "tp" or "x1" and go for names that tell the full story, like "total_price" or "user_email". Clear, descriptive names are like captions under your code's photos - they explain who's who and what's happening. This small habit pays big dividends when you revisit or share your work. coderivers.org
  8. Master Multiple Assignment for Efficiency - Save keystrokes and boost clarity by assigning multiple variables in one line: `a, b, c = 1, 2, 3`. This trick is perfect for unpacking configurations, swapping values, or handling function returns in style. It's like having a multi-slot rocket launcher for your code! ipython.ai
  9. Utilize Unpacking for Sequences - Take a list or tuple and instantly spread its items into variables: `x, y, z = (1, 2, 3)` feels almost magical. Unpacking keeps your code concise, prevents indexing mishaps, and makes data extraction look like elegant choreography. Give it a try next time you're dancing with data! ipython.ai
  10. Consistently Follow PEP 8 Guidelines - Python's official style guide, PEP 8, is your friendly neighborhood rulebook for writing clean, maintainable code. From naming conventions to indentation, sticking to PEP 8 means less "what's the style here?" debates and more time building cool features. Your future self and collaborators will thank you with fewer merge conflicts and happier commits! geeksforgeeks.org
Powered by: Quiz Maker