Fundamentals 28 min read

Uncovering Python’s Oddities: Why Indentation, No Switch, and More

This article explains the most frequently asked Python design questions, covering why indentation groups statements, the quirks of floating‑point arithmetic, immutable strings, the absence of a switch statement, memory management, and many other language‑specific decisions that shape Python’s elegant yet unconventional syntax.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Uncovering Python’s Oddities: Why Indentation, No Switch, and More

01. Why use indentation to group statements?

Guido van Rossum believes that using indentation for grouping is elegant and greatly improves the readability of ordinary Python programs. Because Python lacks explicit start/end brackets, the parser’s view of grouping never diverges from a human reader’s expectation.

if (x <= y):
    x++
    y--
z++

If the condition is true, only the indented statements are executed, which matches the programmer’s intuition.

02. Why do simple arithmetic operations sometimes give strange results?

See the next question.

03. Why is floating‑point arithmetic inaccurate?

Python’s float type stores values as C double with fixed precision (typically 53 bits). The underlying hardware determines the actual result, so Python behaves like many other languages such as C and Java.

>> 1.2 - 1.0
0.19999999999999996

Numbers that look simple in decimal cannot be represented exactly in binary. For example, the decimal 1.2 is stored as the binary fraction 1.0011001100110011001100110011001100110011001100110011, which corresponds to the decimal 1.1999999999999999555910790149937383830547332763671875. This gives about 15‑16 decimal digits of precision.

04. Why are Python strings immutable?

Immutability brings performance benefits because the memory layout can be fixed at creation time, and it also allows strings to be used as dictionary keys.

05. Why must “self” be explicit in method definitions and calls?

Explicit self makes it clear that an attribute belongs to an instance rather than a local variable, and it simplifies method resolution in inheritance hierarchies.

06. Why can’t assignment appear inside expressions?

Allowing assignment in expressions leads to subtle bugs (e.g., mistaking = for ==). Python forces assignments to be statements to avoid these errors. The idiomatic way is to use a for loop or an explicit while loop.

for line in f:
    # do something with line

07. Why are some operations methods (e.g., list.index() ) while others are functions (e.g., len(list) )?

Prefix notation is often more readable for operations that naturally read like functions (e.g., len(x)), while methods are used when the operation is tightly bound to the object’s type.

08. Why is join() a string method rather than a list method?

join()

is a method of the separator string because it tells the separator to interleave itself between the elements of an iterable.

", ".join(['1', '2', '4', '8', '16'])
"1, 2, 4, 8, 16"

09. How fast are exceptions?

If no exception is raised, a try/except block has negligible overhead. Raising and catching an exception is comparatively expensive, so use if key in dict when missing keys are expected.

if key in mydict:
    value = mydict[key]
else:
    value = mydict[key] = getvalue(key)

10. Why doesn’t Python have a switch or case statement?

Python uses if…elif…else chains. A dictionary mapping keys to callables can emulate a switch.

functions = {'a': function_1, 'b': function_2, 'c': self.method_1}
func = functions[value]
func()

11. Can the interpreter simulate threads without OS‑specific threads?

Standard CPython pushes at least one C stack frame per Python frame, so true thread simulation requires C‑level thread support. Stackless Python provides a redesigned interpreter loop that avoids the C stack.

12. Why can’t lambda expressions contain statements?

Python’s syntax does not allow statements inside expressions. Lambdas are merely shorthand for simple functions.

13. Can Python be compiled to machine code or another language?

Cython compiles Python with optional type annotations to C extensions; Nuitka compiles to C++; VOC can target Java.

14. How does Python manage memory?

CPython uses reference counting plus a cyclic‑garbage collector ( gc module). Other implementations (e.g., Jython, PyPy) use different strategies.

15. Why doesn’t CPython use a traditional garbage‑collector?

Traditional GC libraries are not portable across all platforms, and embedding Python in other applications may require custom memory allocators.

16. Why doesn’t CPython free all memory on exit?

Objects referenced from the global namespace may not be released, especially those involved in reference cycles. Use the atexit module to perform explicit cleanup.

17. Why are there separate tuple and list types?

Tuples are immutable collections suitable for fixed‑size records (e.g., coordinates), while lists are mutable arrays for homogeneous collections.

18. How are lists implemented in CPython?

Lists are mutable arrays of object references with over‑allocation to make appends amortized O(1). Indexing is O(1) because the underlying storage is contiguous.

19. How are dictionaries implemented in CPython?

Dictionaries are resizable hash tables. The built‑in hash() function computes a hash code for each key, which determines the slot in the internal array, giving average O(1) look‑ups.

20. Why must dictionary keys be immutable?

Mutable objects can change their hash value, breaking the hash‑table invariants. Only immutable objects (e.g., tuples) can safely serve as keys.

21. Why are there separate tuple and list data types?

Tuples are immutable and can be used as dictionary keys; lists are mutable and cannot.

22. How can you specify and enforce interface specifications in Python?

Python 2.6 introduced the abc module for abstract base classes. Use isinstance() and issubclass() to check compliance. The collections.abc module provides common ABCs such as Iterable, Container, and MutableMapping. Testing frameworks like doctest and unittest help enforce behavior.

23. Why doesn’t Python have goto ?

Python can simulate a goto using exceptions, but jumping into the middle of a loop is discouraged and considered misuse.

class label(Exception):
    pass

try:
    # ...
    if condition:
        raise label()
except label:
    pass

24. Why can raw strings not end with a backslash?

Raw strings cannot end with an odd number of backslashes because the final backslash would escape the closing quote, leaving the string unterminated.

25. Why doesn’t Python have a “with” statement for attribute assignment?

Python’s dynamic typing makes it ambiguous whether a name refers to a local variable, a global, or an attribute, so an attribute‑assignment context would be unclear.

26. Why do if , while , def , and class statements require a colon?

The colon improves readability and helps editors determine where indentation should increase.

27. Why does Python allow a trailing comma in list, tuple, and dict literals?

Trailing commas make it easier to add, reorder, or comment out elements without worrying about missing commas, and they prevent subtle bugs caused by omitted commas.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Language DesignFAQSyntax
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.