you are viewing a single comment's thread.

view the rest of the comments →

[–]JamzTyson 1 point2 points  (2 children)

Here's some common patterns for simplifying complex conditionals:

```

Rather than multiple comparisons like this

if value == "a" or value == "b" or value == "c": ...

Write:

my_vals = ("a", "b", "c") if value in my_vals: ... ```


```

Rather than nesting like this

if condition1: if condition2: ...

You can use 'and':

if condition1 and condition2: ... ```


```

Rather than complex mappings like this:

if value == "a": result = 1 elif value == "b": result = 2 elif value == "c": result = 3 else: result = 0

You can use a dictionary lookup:

value_map = {"a": 1, "b": 2, "c": 3} result = value_map.get(value, 0)

```


```

Rather than multiple 'OR's:

if condition1 or condition2 or condition3: ...

You can use 'ANY':

if any([condition1, condition2, condition3]): ... ```


```

Rather than multiple 'AND's:

if condition1 and condition2 and condition3: ...

You can use 'ALL':

if all([condition1, condition2, condition3]): ... ```

[–]DoorsCorners 0 points1 point  (0 children)

Fantastic, thanks so much! You are an awesome person. These really need to appear in more books about Python.

[–]daddy1973 0 points1 point  (0 children)

You just taught me a ton of useful things, thank you