Feeds

Real Python: Expression vs Statement in Python: What's the Difference?

Planet Python - Wed, 2024-12-04 09:00

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 Effects

When 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:

  1. All instructions in Python fall under the broad category of statements.
  2. By this definition, all expressions are also statements—sometimes called expression statements.
  3. 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 Values

Essentially, 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 Effects

Statements 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 ]

Categories: FLOSS Project Planets

Drupal life hack's: How can AI help in understanding regular expressions using Drupal examples?

Planet Drupal - Wed, 2024-12-04 08:54
How can AI help in understanding regular expressions using Drupal examples? admin Wed, 12/04/2024 - 15:54
Categories: FLOSS Project Planets

The Drop Times: Axelerant’s IDMC Digital Overhaul Earns Splash Awards Asia Nomination

Planet Drupal - Wed, 2024-12-04 08:00
In the second episode of The DropTimes' "Splash Award Finalists" series, explore how Axelerant’s innovative work for the Internal Displacement Monitoring Centre (IDMC) has transformed its digital platform. Learn how this project tackles global displacement challenges and why it’s a contender for the 'Not-for-Profit' category at the Splash Awards Asia.
Categories: FLOSS Project Planets

Bits from Debian: "Ceratopsian" will be the default theme for Debian 13

Planet Debian - Wed, 2024-12-04 07:30

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!

Categories: FLOSS Project Planets

Ned Batchelder: Testing some tidbits

Planet Python - Wed, 2024-12-04 07:03

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.

Categories: FLOSS Project Planets

LostCarPark Drupal Blog: Drupal Advent Calendar day 4 - Drupal.org

Planet Drupal - Wed, 2024-12-04 04:00
Drupal Advent Calendar day 4 - Drupal.org james Wed, 12/04/2024 - 09:00

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…

Tags
Categories: FLOSS Project Planets

Django Weblog: Help us make it happen ❤️

Planet Python - Wed, 2024-12-04 03:53

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

Donate to support Django

Other ways to give Why give to the Django Software Foundation?

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.

Categories: FLOSS Project Planets

FSF Blogs: The Licensing and Compliance Team is fighting for freedom and we need your help

GNU Planet! - Tue, 2024-12-03 17:25
The Licensing and Compliance Lab has been diligently serving the free software community.
Categories: FLOSS Project Planets

The Licensing and Compliance Team is fighting for freedom and we need your help

FSF Blogs - Tue, 2024-12-03 17:24
The Licensing and Compliance Lab has been diligently serving the free software community.
Categories: FLOSS Project Planets

Kushal Das: Basedpyright and neovim

Planet Python - Tue, 2024-12-03 15:50

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.

Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #658 (Dec. 3, 2024)

Planet Python - Tue, 2024-12-03 14:30

#658 – DECEMBER 3, 2024
View in Browser »

Django Performance: Scaling and Optimization

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

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

Python Developers: Scrape Any Website Without Getting Blocked

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

Managing Dependencies With Python Poetry

Learn how Python Poetry can help you start new projects, maintain existing ones, and master dependency management.
REAL PYTHON course

Nuitka Release 2.5

NUITKA.NET

Quiz: NumPy Practical Examples: Useful Techniques

REAL PYTHON

Quiz: Interacting With Python

REAL PYTHON

Discussions Add Optional if break: Suite to for/while

PYTHON.ORG

Articles & Tutorials Advent of Code 2024

This annual tradition is a series of small programming puzzles that can be completed in any programming language.
ADVENTOFCODE.COM

CI/CD for Python With GitHub Actions

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

How to Debug Your Textual Application

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

Reactive Notebooks and Deployable Web Apps in Python

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

Constraints Are Good: Python’s Metadata Dilemma

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

Demystifying ODBC With Python

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

What the PSF Conduct WG Does

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

Introduction to Retrogame Programming With Pyxel

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

Speeding Up Data Retrieval From PostgreSQL With Psycopg

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

Django Application Performance Optimization Checklist

“Improve the performance of your Django application by understanding, testing, and implementing some common optimization techniques.”
SANKET RAI

Top 10 Rules of Continuous Integration

Continuous Integration (CI) is key to rapid deployment of new features. This post gives you ten rules to consider when doing CI.
KRISTINA NIKOLOVA

Projects & Code Sensei: Simplifying API Client Generation

CROCOFACTORY.DEV • Shared by Alexey

QodoAI Cover-Agent: AI Tool for Automated Test Generation

GITHUB.COM/CODIUM-AI

Peek: Like print, but Easy

SALABIM.ORG • Shared by Ruud van der Ham

pyvista: 3D Plotting and Mesh Analysis

GITHUB.COM/PYVISTA

python-fire: Automatically Generate Command Line Interfaces

GITHUB.COM/GOOGLE

Events Weekly Real Python Office Hours Q&A (Virtual)

December 4, 2024
REALPYTHON.COM

PyCon Tanzania 2024

December 4 to December 6, 2024
PYCON.OR.TZ

DELSU Tech Invasion 2.0

December 4 to December 6, 2024
HAMPLUSTECH.COM

Canberra Python Meetup

December 5, 2024
MEETUP.COM

Sydney Python User Group (SyPy)

December 5, 2024
SYPY.ORG

PyLadies Amsterdam: Introduction to Data Storytelling

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 ]

Categories: FLOSS Project Planets

Python Insider: Python 3.13.1, 3.12.8, 3.11.11, 3.10.16 and 3.9.21 are now available

Planet Python - Tue, 2024-12-03 14:01

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.1

Python 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.8

Python 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 releases

Thanks 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 

Categories: FLOSS Project Planets

Driving Open Source forward: make your impact in 2025

Open Source Initiative - Tue, 2024-12-03 13:51
Members Newsletter – December 2024

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 engagement

Nick 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:

OSI in the news The Gap Between Open and Closed AI Models Might Be Shrinking. Here’s Why That Matters

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:

Other news

News from OSI affiliates:

Surveys

The State of Open Source Survey

In collaboration with the Eclipse Foundation and Open Source Initiative (OSI).

Jobs

OSI US Policy Manager

Lead OSI’s public policy agenda and education.

Events

Upcoming events:

CFPs:

  • PyCon US 2025: the Python Software Foundation kicks off Website, CfP, and Sponsorship!
Thanks to our sponsors New sponsors and renewals
  • Automattic
  • Sentry
  • Google
  • 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 member

Let’s build a world where knowledge is freely shared, ideas are nurtured, and innovation knows no bounds! 

Join the Open Source Initiative!

Categories: FLOSS Research

FSF Blogs: Free Software Supporter -- Issue 200, December 2024

GNU Planet! - Tue, 2024-12-03 10:40
Welcome to the Free Software Supporter, the Free Software Foundation's (FSF) monthly news digest and action update -- being read by you and 231,349 other activists.
Categories: FLOSS Project Planets

Free Software Supporter -- Issue 200, December 2024

FSF Blogs - Tue, 2024-12-03 10:40
Welcome to the Free Software Supporter, the Free Software Foundation's (FSF) monthly news digest and action update -- being read by you and 231,349 other activists.
Categories: FLOSS Project Planets

FSF Blogs: November GNU spotlight with Amin Bandali

GNU Planet! - Tue, 2024-12-03 10:39
Eleven new GNU releases in the last month (as of November 29, 2024):
Categories: FLOSS Project Planets

November GNU spotlight with Amin Bandali

FSF Blogs - Tue, 2024-12-03 10:39
Eleven new GNU releases in the last month (as of November 29, 2024):
Categories: FLOSS Project Planets

Freelock Blog: Automatically show this month and next month in a perpetual calendar

Planet Drupal - Tue, 2024-12-03 10:00
Automatically show this month and next month in a perpetual calendar Anonymous (not verified) Tue, 12/03/2024 - 07:00 Tags Drupal CMS Website management ECA Drupal Planet

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.

Categories: FLOSS Project Planets

Matt Glaman: The Web APIs powering the Drupal CMS trial experience

Planet Drupal - Tue, 2024-12-03 09:00

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.

Categories: FLOSS Project Planets

Real Python: Handling or Preventing Errors in Python: LBYL vs EAFP

Planet Python - Tue, 2024-12-03 09:00

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 ]

Categories: FLOSS Project Planets

Pages