Things I didn't know about Python, part 1

My favourite scripting language by far is Python. I’m always finding cool things in the language that I didn’t know were there. Even though I’ve been writing scripts in it for years, today I discovered that you can use maths-style ranges in comparisons.

Whereas in most languages to check a value x is within a range (say, 5 or more but less than 20), you might do:

// In C:
if (x >= 5 && x < 20) { ... code ... }
# In Python (without using the cool thing)
if x >= 5 and x < 20: # code

In Python, you can write the more mathsy:

if 5 <= x < 20: # code

Just a little thing I never realised.

Filed under: Coding
Posted at 12:40:00 GMT on 30th October 2007.

About Matt Godbolt

Matt Godbolt is a C++ developer living in Chicago. He works for Hudson River Trading on super fun but secret things. He is one half of the Two's Complement podcast. Follow him on Mastodon or Bluesky.

Copyright 2007-2025 Matt Godbolt. Unless otherwise stated, all content is licensed under the Creative Commons Attribution-Noncommercial 3.0 Unported License. This blog is powered by the MalcBlogSystem by Malcolm Rowe. Note: This is my personal website. The views expressed on these pages are mine alone and not those of my employer.

AltStyle によって変換されたページ (->オリジナル) /