![]() |
|
[Tut] Python One Line If Not None - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python One Line If Not None (/thread-97198.html) |
[Tut] Python One Line If Not None - xSicKxBot - 09-11-2020 Python One Line If Not None To assign the result of a function Code: get_value()Code: xCode: NoneCode: if tmp := get_value(): x = tmpCode: tmpCode: xProblem: How to assign a value to a variable if it is not equal to Code: NoneExample: Say, you want to assign the return value of a function get_value(), but only if it doesn’t return None. Otherwise, you want to leave the value as it is. Here’s a code example: Code: import random def get_value(): if random.random()>0.5: return None return 1 # Naive approach:
x = 42
tmp = get_value()
if tmp != None: x = tmp
print(tmp)While this works, you need to execute the function Code: get_value()Code: get_value()Code: x = 42
temp = get_value()
if temp != None: x = temp
print(x)However, this seems clunky and ineffective. Is there a better way? Let’s have an overview of the one-liners that conditionally assign a value to a given variable: https://repl.it/@finxter/CrookedLivelyLocks?lite=true Exercise: Run the code. Does it always generate the same result? Method 1: Ternary Operator + Semicolon The most basic ternary operator Code: x if c else yCode: xCode: cCode: yCode: xCode: cCode: TrueCode: cCode: FalseCode: yYou can use the ternary operator to solve this problem in combination with the semicolon to write multiple lines of codeas a Python one-liner. Code: # Method 1
tmp = get_value(); x = tmp if tmp else xYou cannot run the Code: get_value()Code: TrueCode: xTherefore, the following code would be a blunt mistake: Code: x = get_value() if get_value() else xThe variable Code: xCode: NoneRelated articles: Method 2: Walrus + One-Line-If A beautiful extension of Python 3.8 is the Walrus operator. The Walrus operator Code: :=Code: # Method 2
if tmp := get_value(): x = tmpThis is a very clean, readable, and Pythonic way. Also, you don’t have the redundant identity assignment in case the if condition is not fulfilled. Related Article: The Walrus Operator in Python 3.8 Python One-Liners Book Python programmers will improve their computer science skills with these useful one-liners. ![]() Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert. The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to: • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line. Get your Python One-Liners Now!! |