Python makes it easy to write functions. For example, I can write: def hello(name): return f’Hello, {name}!’ I can then run the function with: hello(‘world’) which will then, not surprisingly, return the string ‘Hello, world’ Here’s a question that doesn’t come up much: How does Python assign the string argument ‘world’ to the parameter “name”?…
Whether you’re a newcomer to Python or an old hand, you’re probably writing lots of functions — functions that perform calculations, functions that parse files, functions that check passwords, and functions that contact remote APIs. But in Python, functions are more than just verbs. They’re also nouns: They’re objects that we can store in data…
A new cohort of Weekly Python Exercise A2 (“Functions for beginners”) starts tomorrow — Tuesday, May 5th. If you’ve been using Python for less than one year, and want to write better, more powerful, more idiomatic functions that do more with less code — then this is the course for you. WPE’s time-tested formula combines…
PyCon didn’t happen in Pittsburgh, as planned, thanks to the coronavirus and covid-19. But it did happen online, and I was delighted to be able to present a talk! Here’s the talk video: And here are the slides, which you can download and use: Please send comments via e-mail to reuven@lerner.co.il or on Twitter to…
If you’ve programmed in Python for even a short amount of time, then you’ve probably written a fair number of functions. But many newcomers to Python don’t understand just how useful and powerful functions can be: We can treat functions as nouns, not just as verbs — passing them as arguments, and storing them in…
One of the first things that anyone learns in Python is (of course) how to print the string, “Hello, world.” As you would expect, the code is straightforward and simple: print(‘Hello, world’) And indeed, Python’s “print” function is so easy and straightforward to use that we barely give it any thought. We assume that people…
Let’s define a simple Python function: In [1]: def foo(x): …: return x * x …: In [2]: foo(5) Out[2]: 25 In [3]: foo(10) Out[3]: 100 As we can see, this function has a single parameter, “x”. In Python, parameters are local variables whose values are set by whoever is calling the function. So we…
One of Python’s mantras is “batteries included.” which means that even with a bare-bones installation, you can do quite a bit. You can (and should) install packages from PyPI, but many day-to-day tasks can be accomplished with just the built-in data structures, functions, and methods. What I’ve discovered over the years is that some of…
What happens when we define a function in Python? The “def” keyword does two things: It creates a function object, and then assigns a variable (our function name) to that function object. So when I say: def foo(): return “I’m foo!” Python creates a new function object. Inside of that object, we can see…