Feeds
Real Python: Expression vs Statement in Python: What's the Difference?
After working with Python for a while, you’ll eventually come across two seemingly similar terms: expression and statement. When you browse the official documentation or dig through a Python-related thread on an online forum, you may get the impression that people use these terms interchangeably. That’s often true, but confusingly enough, there are cases when the expression vs statement distinction becomes important.
So, what’s the difference between expressions and statements in Python?
Get Your Code: Click here to download the free sample code you’ll use to learn about the difference between expressions and statements.
Take the Quiz: Test your knowledge with our interactive “Expression vs Statement in Python: What's the Difference?” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Expression vs Statement in Python: What's the Difference?In this quiz, you'll test your understanding of Python expressions vs statements. Knowing the difference between these two is crucial for writing efficient and readable Python code.
In Short: Expressions Have Values and Statements Cause Side EffectsWhen you open the Python glossary, you’ll find the following two definitions:
Expression: A piece of syntax which can be evaluated to some value. (…) (Source)
Statement: A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, (…) (Source)
Well, that isn’t particularly helpful, is it? Fortunately, you can summarize the most important facts about expressions and statements in as little as three points:
- All instructions in Python fall under the broad category of statements.
- By this definition, all expressions are also statements—sometimes called expression statements.
- Not every statement is an expression.
In a technical sense, every line or block of code is a statement in Python. That includes expressions, which represent a special kind of statement. What makes an expression special? You’ll find out now.
Expressions: Statements With ValuesEssentially, you can substitute all expressions in your code with the computed values, which they’d produce at runtime, without changing the overall behavior of your program. Statements, on the other hand, can’t be replaced with equivalent values unless they’re expressions.
Consider the following code snippet:
Python >>> x = 42 >>> y = x + 8 >>> print(y) 50 Copied!In this example, all three lines of code contain statements. The first two are assignment statements, while the third one is a call to the print() function.
When you look at each line more closely, you can start disassembling the corresponding statement into subcomponents. For example, the assignment operator (=) consists of the parts on the left and the right. The part to the left of the equal sign indicates the variable name, such as x or y, and the part on the right is the value assigned to that variable.
The word value is the key here. Notice that the variable x is assigned a literal value, 42, that’s baked right into your code. In contrast, the following line assigns an arithmetic expression, x + 8, to the variable y. Python must first calculate or evaluate such an expression to determine the final value for the variable when your program is running.
Arithmetic expressions are just one example of Python expressions. Others include logical expressions, conditional expressions, and more. What they all have in common is a value to which they evaluate, although each value will generally be different. As a result, you can safely substitute any expression with the corresponding value:
Python >>> x = 42 >>> y = 50 >>> print(y) 50 Copied!This short program gives the same result as before and is functionally identical to the previous one. You’ve calculated the arithmetic expression by hand and inserted the resulting value in its place.
Note that you can evaluate x + 8, but you can’t do the same with the assignment y = x + 8, even though it incorporates an expression. The whole line of code represents a pure statement with no intrinsic value. So, what’s the point of having such statements? It’s time to dive into Python statements and find out.
Statements: Instructions With Side EffectsStatements that aren’t expressions cause side effects, which change the state of your program or affect an external resource, such as a file on disk. For example, when you assign a value to a variable, you define or redefine that variable somewhere in Python’s memory. Similarly, when you call print(), you effectively write to the standard output stream (stdout), which, by default, displays text on the screen.
Note: While statements encompass expressions, most people use the word statement informally when they refer to pure statements or instructions with no value.
Okay. You’ve covered statements that are expressions and statements that aren’t expressions. From now on, you can refer to them as pure expressions and pure statements, respectively. But it turns out there’s a middle ground here.
Read the full article at https://realpython.com/python-expression-vs-statement/ »[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
Drupal life hack's: How can AI help in understanding regular expressions using Drupal examples?
The Drop Times: Axelerant’s IDMC Digital Overhaul Earns Splash Awards Asia Nomination
Bits from Debian: "Ceratopsian" will be the default theme for Debian 13
The theme "Ceratopsian" by Elise Couper has been selected as the default theme for Debian 13 "trixie". The theme is inspired by Trixie's (the fictional character from Toy Story) frill and is also influenced by a previously used theme called "futurePrototype" by Alex Makas.
After the Debian Desktop Team made the call for proposing themes, a total of six choices were submitted. The desktop artwork poll was open to the public, and we received 2817 responses ranking the different choices, of which Ceratopsian has been ranked as the winner among them.
We'd like to thank all the designers that have participated and have submitted their excellent work in the form of wallpapers and artwork for Debian 13.
Congratulations, Elise, and thank you very much for your contribution to Debian!
Ned Batchelder: Testing some tidbits
I posted a Python tidbit about checking if a string consists entirely of zeros and ones:
I got a bunch of replies suggesting other ways. I wanted to post those, but I also wanted to check if they were right. A classic testing structure would have required putting them all in functions, etc, which I didn’t want to bother with.
So I cobbled together a test harness for them (also in a gist if you want):
GOOD = ["",
"0",
"1",
"000000000000000000",
"111111111111111111",
"101000100011110101010000101010101001001010101",
]
BAD = [
"x",
"nedbat",
"x000000000000000000000000000000000000",
"111111111111111111111111111111111111x",
"".join(chr(i) for i in range(10000)),
]
TESTS = """
# The original checks
all(c in "01" for c in s)
set(s).issubset({"0", "1"})
set(s) <= {"0", "1"}
re.fullmatch(r"[01]*", s)
s.strip("01") == ""
not s.strip("01")
# Using min/max
"0" <= min(s or "0") <= max(s or "1") <= "1"
not s or (min(s) in "01" and max(s) in "01")
((ss := sorted(s or "0")) and ss[0] in "01" and ss[-1] in "01")
# Using counting
s.count("0") + s.count("1") == len(s)
(not (ctr := Counter(s)) or (ctr["0"] + ctr["1"] == len(s)))
# Using numeric tests
all(97*c - c*c > 2351 for c in s.encode())
max((abs(ord(c) - 48.5) for c in "0"+s)) < 1
all(map(lambda x: (ord(x) ^ 48) < 2, s))
# Removing all the 0 and 1
re.sub(r"[01]", "", s) == ""
len((s).translate(str.maketrans("", "", "01"))) == 0
len((s).replace("0", "").replace("1", "")) == 0
"".join(("1".join((s).split("0"))).split("1")) == ""
# A few more for good measure
set(s + "01") == set("01")
not (set(s) - set("01"))
not any(filter(lambda x: x not in {"0", "1"}, s))
all(map(lambda x: x in "01", s))
"""
import re
from collections import Counter
from inspect import cleandoc
g = {
"re": re,
"Counter": Counter,
}
for test in cleandoc(TESTS).splitlines():
test = test.partition("#")[0]
if not test:
continue
for ss, expected in [(GOOD, True), (BAD, False)]:
for s in ss:
result = eval(test, {"s": s} | g)
if bool(result) != expected:
print("OOPS:")
print(f" {s = }")
print(f" {test}")
print(f" {expected = }")
It’s a good thing I did this because a few of the suggestions needed adjusting, especially for dealing with the empty string. But now they all work, and are checked!
BTW, if you prefer Mastodon to BlueSky, the posts are there too: first and second.
LostCarPark Drupal Blog: Drupal Advent Calendar day 4 - Drupal.org
Today Tim Lehnen from the Drupal Association joins us to talk about some of the changes taking place on the Drupal.org website as part of Starshot.
For day 4 of the Drupal Advent calendar, it’s a familiar face: Drupal.org! When we say “Come for the code, stay for the community!” Drupal.org is where we welcome everyone to join us. Sure, you can find all the code, extensions, and documentation you need here, but Drupal.org is so much more. It’s the place where one of the greatest communities in open source gathers to communicate, collaborate, and celebrate.
Drupal.org is also a part of Drupal…
TagsDjango Weblog: Help us make it happen ❤️
And just like that, 2024 is almost over! If your finances allow, donate to the Django Software Foundation to support the long-term future of Django.
84%Of our US $200,000.00 goal for 2024, as of December 4th, 2024, we are at:
- 83.6% funded
- $167,272.85 donated
- Official merchandise store - Buy official t-shirts, accessories, and more to support Django.
- Sponsor Django via GitHub Sponsors.
- Benevity Workplace Giving Program - If your employer participates, you can make donations to the DSF via payroll deduction.
Our main focus is direct support of Django's developers. This means:
- Organizing and funding development sprints so that Django's developers can meet in person.
- Helping key developers attend these sprints and other community events by covering travel expenses to official Django events.
- Providing financial assistance to community development and outreach projects such as Django Girls.
- Providing financial assistance to individuals so they can attend major conferences and events.
- Funding the Django Fellowship program, which provides full-time staff to perform community management tasks in the Django community.
Still curious? See our Frequently Asked Questions about donations.
FSF Blogs: The Licensing and Compliance Team is fighting for freedom and we need your help
The Licensing and Compliance Team is fighting for freedom and we need your help
Kushal Das: Basedpyright and neovim
Basedpyright is a fork of pyright with various type checking improvements, improved vscode support and pylance features built into the language server. It has a list of benefits over Pyright.
In case you want to use that inside of neovim using Mason, you will have to remember to have the configuration inside of a settings key. The following is from my setup.
basedpyright = { settings = { basedpyright = { analysis = { diagnosticMode = 'openFilesOnly', typeCheckingMode = 'basic', capabilities = capabilities, useLibraryCodeForTypes = true, diagnosticSeverityOverrides = { autoSearchPaths = true, enableTypeIgnoreComments = false, reportGeneralTypeIssues = 'none', reportArgumentType = 'none', reportUnknownMemberType = 'none', reportAssignmentType = 'none', }, }, }, }, },Struggled for a few hours to fix this couple of days ago.
PyCoder’s Weekly: Issue #658 (Dec. 3, 2024)
#658 – DECEMBER 3, 2024
View in Browser »
Performance tuning in the context of Django applications is the practice of enhancing both the efficiency and effectiveness of your web project to optimize its runtime behavior. This article tells you a lot of what you need to know.
LOADFORGE.COM
Python’s pathlib module is the tool to use for working with file paths. This post contains pathlib quick reference tables and examples.
TREY HUNNER
ZenRows handles all anti-bot bypass for you, from rotating proxies and headless browsers to CAPTCHAs and AI. Get a complete web scraping toolkit to extract all the data you need with a single API call. Try ZenRows now for free →
ZENROWS sponsor
Learn how Python Poetry can help you start new projects, maintain existing ones, and master dependency management.
REAL PYTHON course
This annual tradition is a series of small programming puzzles that can be completed in any programming language.
ADVENTOFCODE.COM
With most software following agile methodologies, it’s essential to have robust DevOps systems in place to manage, maintain, and automate common tasks with a continually changing codebase. By using GitHub Actions, you can automate your workflows efficiently, especially for Python projects.
REAL PYTHON
Textual is a great Python package for creating a lightweight, powerful, text-based user interface. Debugging TUIs can be a challenge though as you no longer can use print() and the application may not even run in your IDE’s terminal interface. This post talks about how to debug a TUI.
MIKE DRISCOLL
What are common issues with using notebooks for Python development? How do you know the current state, share reproducible results, or create interactive applications? This week on the show, we speak with Akshay Agrawal about the open-source reactive marimo notebook for Python.
REAL PYTHON podcast
Python’s initial flexibility in packaging with the executable setup.py has meant that people have come to expect this power. In this post Armin argues that if constraints had been there in the first place we’d be in a better place now.
ARMIN RONACHER
Open Database Connectivity (ODBC) is used to connect to various databases. This article aims to help you understand ODBC better by implementing database communications from scratch only using Python.
PRESTON BLACKBURN • Shared by Preston Blackburn
In the past week Brett has had two different people tell him what the PSF Conduct Working Group did, and both were wrong. This post tries to correct what might be common misconceptions.
BRETT CANNON
Pyxel is a Rust based framework for building retro games that comes with a Python API wrapper. This step-by-step tutorial shows you how to do some basic sprite animation to get started.
MATHIEU LECARME
Formatting and concatenating query result columns on the PostgreSQL side and then parsing them in Python might sometimes be faster than fetching the columns as separate values.
ALIAKSEI YALETSKI • Shared by Tiendil
“Improve the performance of your Django application by understanding, testing, and implementing some common optimization techniques.”
SANKET RAI
Continuous Integration (CI) is key to rapid deployment of new features. This post gives you ten rules to consider when doing CI.
KRISTINA NIKOLOVA
CROCOFACTORY.DEV • Shared by Alexey
QodoAI Cover-Agent: AI Tool for Automated Test Generation Peek: Like print, but EasySALABIM.ORG • Shared by Ruud van der Ham
pyvista: 3D Plotting and Mesh Analysis python-fire: Automatically Generate Command Line Interfaces Events Weekly Real Python Office Hours Q&A (Virtual) December 4, 2024
REALPYTHON.COM
December 4 to December 6, 2024
PYCON.OR.TZ
December 4 to December 6, 2024
HAMPLUSTECH.COM
December 5, 2024
MEETUP.COM
December 5, 2024
SYPY.ORG
December 7, 2024
MEETUP.COM
Happy Pythoning!
This was PyCoder’s Weekly Issue #658.
View in Browser »
[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]
Python Insider: Python 3.13.1, 3.12.8, 3.11.11, 3.10.16 and 3.9.21 are now available
Another big release day! Python 3.13.1 and 3.12.8 were regularly scheduled releases, but they do contain a few security fixes. That makes it a nice time to release the security-fix-only versions too, so everything is as secure as we can make it.
Python 3.13.1Python 3.13’s first maintenance release. My child is all growed up now, I guess! Almost 400 bugfixes, build improvements and documentation changes went in since 3.13.0, making this the very best Python release to date.
https://www.python.org/downloads/release/python-3131/
Python 3.12.8Python 3.12 might be slowly reaching middle age, but still received over 250 bugfixes, build improvements and documentation changes since 3.12.7.
https://www.python.org/downloads/release/python-3128/Python 3.11.11
I know it’s probably hard to hear, but this is the second security-only release of Python 3.11. Yes, really! Oh yes, I know, I know, but it’s true! Only 11 commits went in since 3.11.10.
https://www.python.org/downloads/release/python-31111/Python 3.10.16
Python 3.10 received a total of 14 commits since 3.10.15. Why more than 3.11? Because it needed a little bit of extra attention to keep working with current GitHub practices, I guess.
https://www.python.org/downloads/release/python-31016/Python 3.9.21
Python 3.9 isn’t quite ready for pasture yet, as it’s set to receive security fixes for at least another 10 months. Very similarly to 3.10, it received 14 commits since 3.9.20.
https://www.python.org/downloads/release/python-3921/Stay safe and upgrade!
As always, upgrading is highly recommended to all users of affected versions.
Enjoy the new releasesThanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation.
Regards from your tireless, tireless release team,
Thomas Wouters
Ned Deily
Steve Dower
Pablo Galindo Salgado
Łukasz Langa
Driving Open Source forward: make your impact in 2025
Our work thrives because of a passionate community dedicated to Open Source values. From advancing initiatives like the Open Source AI Definition to addressing challenges in licensing and policy, collaboration has always been our driving force.
While 2024 brought significant progress, the challenges ahead demand even greater collective action. As we look to 2025, your support will be pivotal in scaling our efforts.
We’ll continue serving as the steward of the Open Source Definition, protecting the Open Source principles and maintaining a list of OSI Approved Licenses.
We’ll continue monitoring policy and standards setting organizations, supporting legislators and policy makers, educating them about the Open Source ecosystem, its role in innovation and its value for an open future.
We’ll continue leading the conversation on Open Source AI, as we’ll need to keep on driving the discussion around data and write position papers to educate legislators in the US, in the EU, and around the world.
And finally, we’ll continue supporting Open Source business practice, helping developers and entrepreneurs to unlock the permissionless innovation enabled by Open Source software.
Join us as a supporting member or, if your organization benefits from Open Source, consider becoming a sponsor. Together, we can protect and expand the freedoms that make Open Source possible—for everyone.
Stefano Maffulli
Executive Director, OSI
I hold weekly office hours on Fridays with OSI members: book time if you want to chat about OSI’s activities, if you want to volunteer or have suggestions.
News from the OSI Celebrating 5 years at the Open Source Initiative: a journey of growth, challenges, and community engagementNick Vidal, community manager at the OSI, shares his story about working at the organization. This isn’t just a story about his career—it’s about the evolution of Open Source, the incredible people he worked with, and the values they’ve championed.
Other highlights:
- Improving Open Source security with the new GitHub Secure Open Source Fund
- Highlights from the Digital Public Goods Alliance Annual Members Meeting 2024
- Open Data and Open Source AI: Charting a course to get more of both
- The Open Source Initiative and the Eclipse Foundation to Collaborate on Shaping Open Source AI (OSAI) Public Policy
- ClearlyDefined v2.0 adds support for LicenseRefs
Article from Time Magazine
The distinction between ‘open’ and ‘closed’ AI models is not as simple as it might appear. While Meta describes its Llama models as open-source, it doesn’t meet the new definition published last month by the Open Source Initiative, which has historically set the industry standard for what constitutes open source.
Other highlights:
- Ai2 releases new language models competitive with Meta’s Llama (TechCrunch)
- AI2 closes the gap between closed-source and open-source post-training (VentureBeat)
- Women leading the charge in open source AI (Capacity Media)
- A battle is raging over the definition of open-source AI (The Economist)
- The best open-source AI models: All your free-to-use options explained (ZDNet)
- Read all press mentions from this past month
News from OSI affiliates:
- Eclipse Foundation: The Open Source Initiative and the Eclipse Foundation to Collaborate on Shaping Open Source AI (OSAI) Public Policy
- DPGA, ITU: Advancing Open Source AI: Definitions, Standards, and Global Implementation for a Sustainable Future
- Apache Software Foundation: The Apache Software Foundation Welcomes a New President
- Linux Foundation: Jim Zemlin, ‘head janitor of open source,’ marks 20 years at Linux Foundation
- Mozilla Foundation: Firefox 1.0 Released 20 Years Ago
- DPGA: Open source key to exchanging best practices in digital government
The State of Open Source Survey
In collaboration with the Eclipse Foundation and Open Source Initiative (OSI).
JobsLead OSI’s public policy agenda and education.
EventsUpcoming events:
- Open Source Experience (December 4-5 – Paris)
- KubeCon + CloudNativeCon India (December 11-12, 2024 – Delhi)
- Deep Dive into the Open Source AI Definition v1.0 (December 12, 2024 – online)
- EU Open Source Policy Summit (January 31, 2025 – Brussels)
- FOSDEM (February 1-2, 2025 – Brussels)
CFPs:
- PyCon US 2025: the Python Software Foundation kicks off Website, CfP, and Sponsorship!
- Automattic
- Sentry
- Cisco
- GitHub
Interested in sponsoring, or partnering with, the OSI? Please see our Sponsorship Prospectus and our Annual Report. We also have a dedicated prospectus for the Deep Dive: Defining Open Source AI. Please contact the OSI to find out more about how your company can promote open source development, communities and software.
Get to vote for the OSI Board by becoming a memberLet’s build a world where knowledge is freely shared, ideas are nurtured, and innovation knows no bounds!
FSF Blogs: Free Software Supporter -- Issue 200, December 2024
Free Software Supporter -- Issue 200, December 2024
FSF Blogs: November GNU spotlight with Amin Bandali
November GNU spotlight with Amin Bandali
Freelock Blog: Automatically show this month and next month in a perpetual calendar
One of our clients is Programming Librarian, a site for librarians to plan educational programs. Programs, like many events, are often seasonal, oriented around holidays and seasonal activities.
The site has a block for each month of the year, containing content for that month. It has a custom field for the month number.
Matt Glaman: The Web APIs powering the Drupal CMS trial experience
This blog expands on my DrupalCon Barcelona talk, which I managed to squeeze into a twenty-minute session slot. You can download a copy of my slides. Unfortunately, I could not dedicate enough time to the project and stepped down as the trial track lead. The Drupal CMS trial is no longer based on my WebAssembly work, and an ongoing process is being conducted to provide an official demo.
Real Python: Handling or Preventing Errors in Python: LBYL vs EAFP
Dealing with errors and exceptional situations is a common requirement in programming. You can either prevent errors before they happen or handle errors after they’ve happened. In general, you’ll have two coding styles matching these strategies: look before you leap (LBYL), and easier to ask forgiveness than permission (EAFP), respectively. In this video course, you’ll dive into the questions and considerations surrounding LBYL vs EAFP in Python.
By learning about Python’s LBYL and EAFP coding styles, you’ll be able to decide which strategy and coding style to use when you’re dealing with errors in your code.
In this video course, you’ll learn how to:
- Use the LBYL and EAFP styles in your Python code
- Understand the pros and cons of LBYL vs EAFP
- Decide when to use either LBYL or EAFP
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]