GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Books
  • Mini
  • Tips
  • Tags
  • About
  • learnbyexample

This view

  • Original page
  • New address

GeezerVison is showing learnbyexample.github.io — Python tip 3: expression and result with f-string

In case you haven't yet discovered this awesome f-string feature, you can add = after an expression to get both the expression and the result in the output.

>>> num1 = 42
>>> num2 = 7

>>> f'{num1 + num2 = }'
'num1 + num2 = 49'
>>> f'{num1 + (num2 * 10) = }'
'num1 + (num2 * 10) = 112'

I use it often to quickly test a function:

>>> def isodd(n):
...     return bool(n % 2)
... 
>>> print(f'{isodd(42) = }')
isodd(42) = False
>>> print(f'{isodd(123) = }')
isodd(123) = True

info See docs.python: Format String Syntax, docs.python: Formatted string literals and fstring.help for documentation and examples.

Video demo:


info See my 100 Page Python Intro ebook for a short, introductory guide for the Python programming language.

#python#tip

← Python tip 4: comparison chaining

Python tip 2: membership operator →


📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.