You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(.)". Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(.) function. Read the following article to learn how to compress multiple lines of code into a single line! But this doesn’t prevent us from doing it, right? Nested Indentation Blocks While you can discuss if this makes sense or not-given that the syntax is not ambiguous here-it doesn’t change the fact: nested block cannot be one-linerized in a straightforward way. If you write this in a single line, Python throws a syntax error: However, if you have nested indentation blocks, this doesn’t work anymore.Ĭonsider the following example: for i in range(3): This works beautifully and Python understands what you are trying to do. You try the following one-liner using the semicolon as a separator between the two statements in the block for i in range(10): c = i ** 2 print(c) Here’s an example of such a block: for i in range(10): While this works beautifully, if all statements are not indented-does it still work if you have an indentation block that starts with the colon : symbol after if, elif, else, for, while, or try/except statements? Python One-Liners Book: Master the Single Line First!.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |