πŸŽ“ Velnov

🐍 Python · Topic 2 of 20

Variables & Operators β€” Python Questions with Answers

Start with the study notes on Variables & Operators (definitions, examples and a quick revision), then work through 30 practice questions, each with the correct answer and a clear explanation of why it is right. When you are ready, take this topic as an interactive quiz to test yourself.

16 easy Β· 10 medium Β· 4 hard Β· Part of Python: Master Python from basics to advanced - 20 topics.

Topic overview

Variables and Operators – storing values and calculating

1. Variables

A variable is a name that refers to a value. You create one with = (assignment). Python is dynamically typed: a name can later refer to a value of a different type.

x = 5
print(x)
x = "hello"      # now x refers to a string
print(x)
Output5
hello

Naming rules

Example: Valid: _total, count2, user_name. Invalid: 2count, my-var, class.

2. Multiple assignment and swapping

You can assign several names at once. Swapping two variables needs no temporary variable.

a, b = 1, 2
a, b = b, a        # swap
print(a, b)
x = y = z = 7
print(x, y, z)
Output2 1
7 7 7

3. Arithmetic operators

print(7 / 2)
print(10 / 5)
print(7 // 2)
print(7 % 2)
print(2 ** 3)
print(-7 // 2)     # rounds DOWN, not toward zero
Output3.5
2.0
3
1
8
-4

Remember: n % 2 == 0 is the standard test for an even number.

4. Order of operations

Python follows maths rules: ** first, then * / // %, then + -. Parentheses come before everything. ** groups from right to left.

print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)   # 2 ** (3 ** 2) = 2 ** 9
Output14
20
512

5. Augmented assignment

x += 3 is a shortcut for x = x + 3. The same works for -=, *=, /=, //=, %= and **=.

x = 10
x += 3
x *= 2
print(x)
Output26

6. Comparison operators

Comparisons give True or False: == equal, != not equal, <, >, <=, >=. Python also allows chained comparisons.

print(5 == 5, 5 != 3)
age = 25
print(18 <= age < 60)   # chained comparison
OutputTrue True
True

Remember: = stores a value; == compares two values.

7. Logical operators: and, or, not

They short-circuit: Python stops as soon as the answer is known. or returns the first truthy value, which is handy for defaults.

print(True and False)
print(not (5 > 3))
print(0 or "hello")
name = ""
print(name or "Guest")
OutputFalse
False
hello
Guest

8. Useful built-in functions

print(abs(-5))
print(min(4, 7, 1), max(4, 7, 1))
print(divmod(7, 2))          # (quotient, remainder)
print(round(2.5), round(3.5))  # halves round to the EVEN number
Output5
1 7
(3, 1)
2 4

Remember: round() uses banker's rounding: an exact half goes to the nearest even number.

9. Common misconceptions

MisconceptionCorrect understanding
10 / 5 gives 2./ always gives a float: 10 / 5 is 2.0. Use // for a whole-number result.
-7 // 2 is -3.// rounds down (towards negative infinity), so -7 // 2 is -4.
= and == mean the same.= assigns a value; == compares two values.
2 ** 3 ** 2 is 64.** groups right to left: 2 ** (3 ** 2) = 512.
round(2.5) is 3.Python rounds halves to the even number, so round(2.5) is 2.

10. Quick revision

Variable
A name that refers to a value.
Dynamic typing
A name can refer to any type at any time.
/
Division; always returns a float.
//
Floor division; rounds down.
%
Modulo; the remainder.
**
Power (exponent).
==
Compares two values.
Short-circuit
and/or stop as soon as the result is known.

11. Test your understanding

  1. What does 7 // 2 give?

    Show answer

    3

  2. What does 7 % 2 give?

    Show answer

    1 (the remainder).

  3. What type does 10 / 5 return?

    Show answer

    A float: 2.0.

  4. How do you swap a and b in one line?

    Show answer

    a, b = b, a

  5. What is 2 + 3 * 4?

    Show answer

    14 (multiplication first).

  6. What does 0 or "hello" return?

    Show answer

    "hello", the first truthy value.

  7. Is 2count a valid variable name?

    Show answer

    No: names cannot start with a digit.

  8. What does 18 <= 25 < 60 give?

    Show answer

    True (a chained comparison).

Key takeaway: Variables are names for values; remember that / gives a float, // rounds down, % gives the remainder, and = assigns while == compares.

Notes written by Velnov. Every code example with an output was run in Python 3 to check that the output shown is exactly what Python prints.

Key concepts in this topic

KeywordsIdentifiersAssignmentReferencesCase sensitivityNameErrorlambdaUnpackingTuplesSwappingAugmented assignmentOperatorsFloor divisionDivisionModuloEven/odd checkExponentiationpow()Numeric typesOperator precedenceBODMASParenthesesComparison operatorsLogical operators

Jump to: Easy Β· Medium Β· Hard

Easy questions (16)

Q1. easy

Which of the following is a valid variable name in Python?

_total = 100      # valid
count2 = 5        # valid
# 2count = 5      # SyntaxError
# class = 'math'  # SyntaxError: keyword
  1. A 2count
  2. B my-var
  3. C _total
  4. D class

Answer: C β€” _total

Variable names must start with a letter or underscore, cannot contain hyphens, and cannot be reserved keywords. "_total" is valid. "2count" starts with a digit, "my-var" contains a hyphen, and "class" is a keyword.

  • By convention, use snake_case: student_name, total_marks.

KeywordsIdentifiers

Q2. easy

What is the output of: x = 5 y = x x = 10 print(y)

x = 5
y = x     # y refers to 5
x = 10    # only x changes
print(y)  # 5
  1. A 10
  2. B 5
  3. C Error
  4. D None

Answer: B β€” 5

y = x makes y refer to the value 5. Reassigning x to 10 later does not change y - numbers are immutable, and y still points to 5.

AssignmentReferences

Q3. easy

Are total and Total the same variable in Python?

  1. A Yes, capitalization doesn't matter
  2. B No - Python is case-sensitive, they are two different variables
  3. C Only inside functions
  4. D Only if declared with var

Answer: B β€” No - Python is case-sensitive, they are two different variables

Python is case-sensitive: total, Total and TOTAL are three separate variables. Using the wrong capitalization gives a NameError.

Case sensitivityNameError

Q4. easy

Which of these words CANNOT be used as a variable name?

import keyword
print(keyword.kwlist)   # shows all 35+ reserved words
  1. A value
  2. B lambda
  3. C data
  4. D result

Answer: B β€” lambda

lambda is a reserved keyword (it creates anonymous functions), so it cannot be a variable name. Other keywords include if, for, class, def, return, True, False, None.

Keywordslambda

Q5. easy

What does this multiple assignment do? a, b = 1, 2

a, b = 1, 2
x, y, z = "do", "re", "mi"
  1. A Error - only one variable per line
  2. B a becomes 1 and b becomes 2
  3. C Both a and b become (1, 2)
  4. D a becomes 2 and b becomes 1

Answer: B β€” a becomes 1 and b becomes 2

Python unpacks the values left to right: a gets 1, b gets 2. This is called tuple unpacking and works with any matching number of values.

UnpackingTuples

Q8. easy

What does x += 3 mean?

x = 10
x += 3    # x is now 13
x *= 2    # x is now 26
  1. A x = x + 3
  2. B x = 3
  3. C Compare x with 3
  4. D x = x * 3

Answer: A β€” x = x + 3

+= is an augmented assignment operator: it adds 3 to the current value of x. Similar shortcuts: -=, *=, /=, //=, %=, **=.

Augmented assignmentOperators

Q9. easy

What is the output of: print(7 // 2)

print(7 / 2)    # 3.5
print(7 // 2)   # 3
  1. A 3.5
  2. B 3
  3. C 4
  4. D 3.0

Answer: B β€” 3

// is floor division - it divides and rounds DOWN to a whole number: 7 // 2 = 3. Regular division 7 / 2 would give 3.5.

Floor divisionDivision

Q10. easy

What is the output of: print(7 % 2)

print(10 % 3)   # 1
print(8 % 2)    # 0  (even numbers % 2 == 0)
  1. A 3
  2. B 3.5
  3. C 1
  4. D 0

Answer: C β€” 1

% is the modulo operator - it gives the REMAINDER after division. 7 divided by 2 is 3 remainder 1, so 7 % 2 = 1.

  • n % 2 == 0 is the standard test for even numbers.

ModuloEven/odd check

Q11. easy

What is the output of: print(2 ** 3)

print(2 ** 3)    # 8
print(5 ** 2)    # 25
print(9 ** 0.5)  # 3.0 (square root!)
  1. A 6
  2. B 8
  3. C 9
  4. D 23

Answer: B β€” 8

** is the power (exponent) operator: 2 ** 3 = 2 x 2 x 2 = 8. It is not multiplication (2 * 3 = 6).

Exponentiationpow()

Q13. easy

What is the output of: print(2 + 3 * 4)

print(2 + 3 * 4)     # 14
print((2 + 3) * 4)   # 20 - parentheses first
  1. A 20
  2. B 14
  3. C 24
  4. D 9

Answer: B β€” 14

Multiplication happens before addition (standard math precedence): 3 * 4 = 12, then 2 + 12 = 14.

Operator precedenceBODMAS

Q14. easy

How do you force the addition to happen first in 2 + 3 * 4?

  1. A Write it as (2 + 3) * 4
  2. B Use the keyword 'first'
  3. C Put it on a separate line
  4. D You cannot change the order

Answer: A β€” Write it as (2 + 3) * 4

Parentheses have the highest precedence - anything inside them is evaluated first: (2 + 3) * 4 = 5 * 4 = 20.

Operator precedenceParentheses

Q15. easy

What is the difference between = and == ?

x = 5          # assignment
print(x == 5)  # True (comparison)
print(x == 7)  # False
  1. A No difference
  2. B = assigns a value; == compares two values
  3. C == assigns a value; = compares
  4. D == is only for strings

Answer: B β€” = assigns a value; == compares two values

One equals sign stores a value in a variable (x = 5). Two equals signs ask a question - are these equal? - and give True or False (x == 5).

  • Writing if x = 5: instead of if x == 5: is a SyntaxError in Python.

AssignmentComparison operators

Q16. easy

Which operator means NOT EQUAL in Python?

print(5 != 3)   # True
print(5 != 5)   # False
  1. A <>
  2. B !=
  3. C =/=
  4. D not=

Answer: B β€” !=

!= tests inequality: 5 != 3 is True. (The old <> form existed in Python 2 but was removed in Python 3.)

Comparison operators

Q17. easy

What is the output of: print(True and False)

print(True and True)    # True
print(True and False)   # False
print(True or False)    # True
  1. A True
  2. B False
  3. C 1
  4. D Error

Answer: B β€” False

and is True only when BOTH sides are True. True and False -> False. Compare: or is True when AT LEAST ONE side is True.

Logical operatorsTruth tables

Q23. easy

By convention, how are constants written in Python?

PI = 3.14159
MAX_USERS = 100
  1. A ALL_CAPS_WITH_UNDERSCORES
  2. B camelCase
  3. C with the const keyword
  4. D prefixed with $

Answer: A β€” ALL_CAPS_WITH_UNDERSCORES

Python has no true const keyword - instead, ALL_CAPS names like MAX_SPEED = 120 signal 'please don't change this'. It's a convention, not enforced by the language.

Naming conventionsPEP 8

Q29. easy

What is the output of: print(abs(-5))

print(abs(-5))    # 5
print(abs(3.7))   # 3.7
  1. A -5
  2. B 5
  3. C 0
  4. D Error

Answer: B β€” 5

abs() returns the absolute value - the distance from zero, always positive: abs(-5) = 5, abs(5) = 5.

Built-in functionsNumbers

Medium questions (10)

Q6. medium

What is the output of: a, b = 5, 10 a, b = b, a print(a, b)

a, b = 5, 10
a, b = b, a     # swap!
print(a, b)     # 10 5
  1. A 5 10
  2. B 10 5
  3. C 10 10
  4. D Error

Answer: B β€” 10 5

a, b = b, a swaps the two variables in one line - the right side (10, 5) is built first, then unpacked. Most languages need a temporary third variable for this.

  • This one-line swap is a favorite Python interview question.

UnpackingSwapping

Q7. medium

After: x = y = z = 7 - what are the values?

x = y = z = 7
print(x, y, z)   # 7 7 7
  1. A Only z is 7; x and y are undefined
  2. B x, y and z are all 7
  3. C Error - chained assignment is not allowed
  4. D x is 7, y and z are None

Answer: B β€” x, y and z are all 7

Chained assignment gives the same value to every name in the chain: all three variables now refer to 7.

  • Careful with mutable objects: x = y = [] makes BOTH names share ONE list.

AssignmentReferences

Q12. medium

What is the result type of: 10 / 5

print(10 / 5)    # 2.0
print(10 // 5)   # 2
  1. A int (2)
  2. B float (2.0)
  3. C str ('2')
  4. D Error

Answer: B β€” float (2.0)

In Python 3, / ALWAYS returns a float - even when the division is exact: 10 / 5 gives 2.0, not 2. Use // if you need an integer result.

DivisionNumeric types

Q18. medium

What is the output of: print(not (5 > 3))

print(not True)      # False
print(not (5 > 3))   # False
  1. A True
  2. B False
  3. C 5
  4. D Error

Answer: B β€” False

5 > 3 is True, and not flips it to False. not simply reverses a boolean value.

not operatorBooleans

Q19. medium

What is the output of: print(1 < 2 < 3)

age = 25
print(18 <= age < 60)   # True - very readable!
  1. A True
  2. B False
  3. C Error
  4. D 3

Answer: A β€” True

Python allows chained comparisons: 1 < 2 < 3 means (1 < 2) and (2 < 3) - both are True, so the result is True. Most languages don't support this.

Chained comparisonComparison operators

Q22. medium

What does divmod(7, 2) return?

q, r = divmod(7, 2)
print(q, r)   # 3 1
  1. A 3.5
  2. B (3, 1) - the quotient and remainder
  3. C [3, 1]
  4. D 1

Answer: B β€” (3, 1) - the quotient and remainder

divmod(a, b) returns the tuple (a // b, a % b) - the whole-number quotient and the remainder in one call.

Floor divisionModuloTuples

Q24. medium

What happens after: x = 10 del x print(x)

x = 10
del x
# print(x)   # NameError: name 'x' is not defined
  1. A Prints 10
  2. B Prints None
  3. C NameError - x is not defined
  4. D Prints 0

Answer: C β€” NameError - x is not defined

del removes the name x entirely. Using it afterwards raises NameError, exactly as if x had never existed.

del statementNameError

Q25. medium

What does this show about Python? x = 5 x = "hello" print(x)

x = 5          # int
x = "hello"    # now str - perfectly legal
print(type(x))  # <class 'str'>
  1. A Error - x is locked to numbers
  2. B Prints hello - variables can be rebound to any type (dynamic typing)
  3. C Prints 5
  4. D Prints 5hello

Answer: B β€” Prints hello - variables can be rebound to any type (dynamic typing)

Python is dynamically typed: a variable is just a name and can point to a value of any type at any time. x pointed to an int, now it points to a string.

  • Convenient, but it means type errors appear at runtime, not before.

Dynamic typingtype()

Q26. medium

What does the global keyword do inside a function?

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1
  1. A Creates a new local variable
  2. B Lets the function modify a variable defined at module level
  3. C Makes the variable visible to other files
  4. D Declares a constant

Answer: B β€” Lets the function modify a variable defined at module level

Assigning inside a function normally creates a LOCAL variable. global tells Python the name refers to the module-level variable, so the function modifies the global one.

  • Prefer return values over globals - easier to test and debug.

ScopeLEGB rule

Q30. medium

What is the output of: print(min(4, 7, 1), max(4, 7, 1))

print(min(4, 7, 1))   # 1
print(max(4, 7, 1))   # 7
print(sum([4, 7, 1])) # 12
  1. A 1 7
  2. B 4 1
  3. C 7 1
  4. D 1 4

Answer: A β€” 1 7

min() returns the smallest of its arguments (1) and max() the largest (7). They also work on lists: min([4, 7, 1]).

Built-in functionssum()

Hard questions (4)

Q20. hard

What is the output of: result = 0 or "hello" print(result)

print(0 or "hello")    # hello
print("hi" or "bye")   # hi (first truthy wins)
print(0 and "hello")   # 0 (and stops at first falsy)
  1. A 0
  2. B True
  3. C hello
  4. D Error

Answer: C β€” hello

or returns the FIRST truthy value (not just True/False!). 0 is falsy, so or moves on and returns "hello" itself. This is called short-circuit evaluation.

  • Common use: name = user_input or "Guest" (default value).

Short-circuit evaluationTruthiness

Q21. hard

What is the output of: print(-7 // 2)

print(7 // 2)    # 3
print(-7 // 2)   # -4  (not -3!)
  1. A -3
  2. B -3.5
  3. C -4
  4. D 4

Answer: C β€” -4

Floor division rounds DOWN (toward negative infinity), not toward zero. -7 / 2 = -3.5, and rounding DOWN gives -4. This surprises people from C/Java where -7/2 truncates to -3.

Floor divisionNegative numbers

Q27. hard

What is the difference between == and is?

a = [1, 2]
b = [1, 2]
print(a == b)   # True  - same values
print(a is b)   # False - two separate lists
print(a is None) # False - the correct use of is
  1. A They are identical
  2. B == compares values; is checks if both names point to the SAME object in memory
  3. C is compares values; == checks memory
  4. D is only works with numbers

Answer: B β€” == compares values; is checks if both names point to the SAME object in memory

== asks 'do these have equal values?'. is asks 'are these literally the same object?'. Two equal lists are == but not is. Use is only for None checks.

  • Always write: if x is None: (not == None).

Identityid()None

Q28. hard

What is the output of: print(round(2.5), round(3.5))

print(round(2.5))   # 2
print(round(3.5))   # 4
print(round(2.6))   # 3 (normal rounding)
  1. A 3 4
  2. B 2 4
  3. C 3 3
  4. D 2 3

Answer: B β€” 2 4

Python uses banker's rounding: exact halves round to the nearest EVEN number. round(2.5) -> 2, round(3.5) -> 4. This reduces bias when rounding many values.

RoundingFloating point

Practice β€œVariables & Operators” as a quiz