Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line With Statement

#1
Python One Line With Statement



The with statement replaces former try...finally blocks in Python. It ensures that clean-up code is executed. For example, it closes open files before leaving the block. Consider this code example (assuming this code is stored in a file named 'code.py'):

with open('code.py') as code: print(code.read())

The output of this code would be the code itself (for nerds: a piece of code that generates itself is called a Quine):

''' OUTPUT
with open('code.py') as code: print(code.read()) '''

No matter what goes wrong inside the with block, Python will close the open file before moving on in the code. This way, you don’t need to enclose the code with a try...except statement.

Single Expression ‘With’ Statement in One Line


Python One Line With Statementhttps://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" />

Problem: Can you write the with statement in a single line of code?

Solution: Yes, you can write the with statement in a single line of code if the loop body consists only of one statement:

with open('code.py') as code: print(code.read())

In general, you can write any indentation block (like if statements, with environments, or while loops) in a single line of code if the body consists of only one statement.

Exercise: The following interactive code throws an error if you run it. Fix the bug and run the correct code!

Multi Expression ‘With’ Statement in One Line


If the body consists of multiple statements, you can use a semicolon between the different statements:

with open('code.py') as code: print('The code:') print(code.read())

The previous code block becomes:

with open('code.py') as code: print('The code:'); print(code.read())

Note that in this particular instance, the semantics actually change because the code reads its own source file! But in all other cases, the semantics remain the same.

As soon as you have nested blocks like a for loop inside a with block, you cannot use this approach anymore because the code would become ambiguous. Believe it or not but the indentation serves a real purpose in Python! ?

Nested Indentation Blocks in a One-Line ‘With’ Statement


If you know the Finxter tutorials, you also know that I seldomly conclude with such a statement “XYZ is impossible” because in most cases, it isn’t. If you’re in doubt whether you can compress an algorithm into a single line of code—don’t. You can compress all algorithms into a single line!

In most cases, you can avoid nested blocks by using list comprehension (rather than a for loop) or the ternary operator (rather than an if block).

Consider the following example with a for loop inside a with block:

with open('code.py') as code: for i in range(10): print(code.read())

Problem: One-Linerize a nested with block!

Wrong Solution: Write it into a single line:

Syntax Error With Statement Single Linehttps://blog.finxter.com/wp-content/uplo...00x110.png 300w, https://blog.finxter.com/wp-content/uplo...68x282.png 768w, https://blog.finxter.com/wp-content/uplo...150x55.png 150w" sizes="(max-width: 641px) 100vw, 641px" />

Correct Solution: Replace the inner for loop with a list comprehension statement!

with open('code.py') as code: [print(code.read()) for i in range(10)]

While this code runs and solves the problem, please note that the chosen example does not make a lot of sense. The file is read only once—even if you place it into a for loop. The reason is that the file reader is done reading the file after the first iteration. In subsequent iterations it only reads the remaining characters (there aren’t any) so the output is not 10x only 1x the file contents.

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Python One-Liners Book


Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will 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!!



https://www.sickgaming.net/blog/2020/07/...statement/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 4 Yesterday, 04:15 PM
Last Post: xSicKxBot
  [Tut] Python Unicode Encode Error xSicKxBot 0 3 09-19-2020, 03:25 PM
Last Post: xSicKxBot
  [Tut] How to Solve Python “TypeError: ‘int’ object is not iterable”? xSicKxBot 0 5 09-18-2020, 01:49 PM
Last Post: xSicKxBot
  [Tut] Python One Line Generator xSicKxBot 0 3 09-18-2020, 12:29 AM
Last Post: xSicKxBot
  [Tut] Python Keyboard Errors xSicKxBot 0 9 09-14-2020, 08:39 PM
Last Post: xSicKxBot
  [Tut] Replacements For Switch Statement In Python? xSicKxBot 0 11 09-13-2020, 04:31 PM
Last Post: xSicKxBot
  [Tut] Python raw_input() vs input() xSicKxBot 0 15 09-13-2020, 03:48 AM
Last Post: xSicKxBot
  [Tut] What Is Python Output Buffering and How to Disable It? xSicKxBot 0 10 09-12-2020, 02:00 PM
Last Post: xSicKxBot
  [Tut] Python One Line If Not None xSicKxBot 0 15 09-12-2020, 12:45 AM
Last Post: xSicKxBot
  [Tut] Python One Line HTTP Get xSicKxBot 0 12 09-11-2020, 10:06 AM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
AppleInsider - Duelling mini LED supplie...
Last Post: xSicKxBot
Today 12:09 PM
» Replies: 0
» Views: 1
News - Monster Hunter Stories Is The Bes...
Last Post: xSicKxBot
Today 12:08 PM
» Replies: 0
» Views: 1
News - Nintendo Currently Has “No Plans”...
Last Post: xSicKxBot
Today 12:08 PM
» Replies: 0
» Views: 1
News - Pokemon Go Adds A New Mega Evolut...
Last Post: xSicKxBot
Today 12:08 PM
» Replies: 0
» Views: 1
(Indie Deal) FREE Desert Law | Elite Dan...
Last Post: xSicKxBot
Today 05:53 AM
» Replies: 0
» Views: 2
News - Review: Georifters – An Ultimatel...
Last Post: xSicKxBot
Today 05:50 AM
» Replies: 0
» Views: 1
How to Install Fallout 4 Mods Xbox One
Last Post: Mark Morar
Today 05:49 AM
» Replies: 2
» Views: 1988
Xbox Wire - Xbox Insider Release Notes –...
Last Post: xSicKxBot
Today 05:49 AM
» Replies: 0
» Views: 1
News - Blog: Rules for a future-proof 2D...
Last Post: xSicKxBot
Today 05:49 AM
» Replies: 0
» Views: 1
News - Among Us PS4, Xbox One Port More ...
Last Post: xSicKxBot
Today 05:49 AM
» Replies: 0
» Views: 2

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020