This entry is based on Python3.11 documentation and lists Python syntax less familiar to a Java developer. It only covers up to chapter 4 (https://docs.python.org/3/tutorial/controlflow.html).
Control Flow Tools
The control flow tools only in Python (not in Java)
- match
- pass
Pass
The pass
statement does nothing.
Here is how it can be used:
- It can be used when a statement is required syntactically but the program requires no action. For example:
- This is commonly used for creating minimal classes.
- Another place
pass
can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. Thepass
is silently ignored.
while True: pass # Busy-wait for keyboard interrupt (Ctrl+C) class MyEmptyClass: pass def initlog(*args): pass # Remember to implement this!
Match
A match
statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell.
There are several ways to use match
- The simplest form compares a subject value against one or more literals
- You can combine several literals in a single pattern using
|
(“or”) - Patterns can look like unpacking assignments, and can be used to bind variables:
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case 401 | 403 | 404: return "Not allowed" case _: return "Something's wrong with the internet" def match_point(point): # point is an (x, y) tuple match point: case (0, 0): print("Origin") case (0, y): print(f"Y={y}") case (x, 0): print(f"X={x}") case (x, y): print(f"X={x}, Y={y}") case _: raise ValueError("Not a point")
Special Parameters
https://docs.python.org/3/tutorial/controlflow.html#special-parameters
positional-only and keyword-only arguments
Add “/” before all positional arguments and “*” before all keyword arguments
def standard_arg(arg): print(arg) def pos_only_arg(arg, /): print(arg) def kwd_only_arg(*, arg): print(arg) def combined_example(pos_only, /, standard, *, kwd_only): print(pos_only, standard, kwd_only)
A method that takes any number of additional keyword arguments (using **kwds)
def foo(name, **kwds): return 'name' in kwds result = foo("Alice", age=25, city="New York", name="Alice") print(result) # Output: True
The foo method can not be called as followed, however, because of conviction.
foo(1, **{'name': 2}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() got multiple values for argument 'name' >>>
To avoid the collision and allow the argument “name” as a keyword argument, we can add “/”.
This function foo2 uses “/” to signify a positional-only argument follows by keyword-only argument(s).
def foo(name, /, **kwds): return 'name' in kwds foo2(1, **{'name': 2}) True
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
Better Python Style
(from https://docs.python.org/3/tutorial/controlflow.html#intermezzo-coding-style)
- Use 4-space indentation and no tabs.4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion and are best left out.
- Wrap lines so that they don’t exceed 79 characters.This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
- Use blank lines to separate functions and classes, and larger blocks of code inside functions.
- When possible, put comments on a line of their own.
- Use docstrings.
-
def my_function(): """Do nothing, but document it. No, really, it doesn't do anything. """ pass
-
- Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
. - Name your classes and functions consistently; the convention is to use
UpperCamelCase
for classes andlowercase_with_underscores
for functions and methods. Always useself
as the name for the first method argument (see A First Look at Classes for more on classes and methods). - Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.
- Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.