Lambda expressions

After getting familiar with Python functions, let us learn what lambda functions are in Python3! Lambda functions are extremely useful when it comes to writing complex code. The more you practice, the more acquainted you will become with this feature.

To simply put it, lambdas are a great way to create anonymous functions that aren’t bound to a name. What a simple function does in three to four lines of code, a Lambda expression can achieve in just one. Lambda expressions are exhaustive functions, which you won’t be using more than once or twice in a program. Without further delay, let’s see what they look like.

def circle_area(rad):
    print(3.14 * rad**2)

circle_area(7)

I’ve defined a new function called circle_area() that takes an integer argument rad. It is quite obvious that rad is, in fact, the circle’s radius. We multiple its square to the approximate value of pi i.e. 3.14. Finally, we’ve created a function call while passing 7 as the radius.

We’re now going to convert this function into a lambda expression step by step.

def circle_area(rad): print(3.14 * rad**2)

circle_area(7)

In the above piece of code, I’ve just written the print function exactly after the colon of circle_area() function. Remember, this changes nothing, except that it made the code less readable. However, worry not, we’ll try and keep our lambda expression as readable and comprehensible as possible.

area = lambda rad: 3.14 * rad**2

Moving forward, I’ve introduced the keyword lambda in my code followed by rad, which was the argument passed to the simple function till now. And the code that succeeds the colon manipulates on rad. Finally, we’ve assigned the variable area, the entire expression:lambda rad: 3.14 * rad**2

area = lambda rad: 3.14 * rad**2

print(area(9))

Now, the variable area can be used anywhere, anytime. Quite handy, right?!

To better understand lambda expressions, let us study its syntax:

lambda argument: statement operating on the argument

The keyword lambda is followed by an argument (most commonly a variable), which is the followed by a colon (just it would in a function) and the statement, which operates on the argument. It is common practice that the whole statement is in turn, assigned to a variable. Moving on, this variable can be extensively used in a program, to just simple print out the result of the lambda operation, or it can even be passed as an parameter in another function.

What is lambda good for?

In fact, we don’t absolutely need lambda, and we could very well construct readable code without using it. But there are certain situations where it makes writing code a lot easier, and the written code a more cleaner. Lamba expressions are generally used in situations when:

  • the function is fairly simple
  • it is going to be used only once

If a function doesn’t return a value, it isn’t an expression and can’t be put into a lambda.

I hope this tutorial helped you to get acquainted with lambda expressions. Of course, implementing them seamlessly requires more practice. Please let me know if you have any questions or if you spot any grammatical errors. I’d be grateful if you could write a single line of feedback, it will encourage me to do better.

Advertisements

Functions with Python3

Welcome everyone! In the last blog, we learned how to deal with text files in Python3. I it was helpful and easy to comprehend. You can find my last article here.

Today, we will study functions in Python3. Those who have previous experience with programming might know what they are, and what they do. But in this article, I’ll assume the reader does not have prior experience with other programming languages. So let’s stick to basics for now.


What are they?

To be honest, we could do just fine without functions. For instance, consider the below example:

first_name = 'Albert'
last_name = 'Einstein'
age = 22
major = 'physics'

print ("%s %s is %d years old, and his major is %s." % (first_name, last_name, age, major))

Now, this code will run just fine. But what if you wanted your program to show information for multiple students from your college? Repeating these five lines of code for each student doesn’t seem that thrilling, does it? This is exactly where functions come into picture. Functions allow us to reuse code without repeating ourselves. Consider a function to be a machine that takes input and produces desired result. And for starters, let’s just focus on the input and output.

A function is a collection of instructions you want your program to interpret. And this set of instructions or statements can be reused multiple times in the same program or a different one. Another important benefit of using functions is that they make a program more clean and readable.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler


Function Types

Functions can be categorised into two types:

  1. Built-in functions
  2. User-defined functions

The Python3 library has a number of functions that are built into it and are always available. Each of them performs a set of defined instructions on the arguments that are provided by the user. We shall study built-in types in future blogs. For now let us focus on working with user defined functions, how to define them, and call them.


User-defined Functions

A set of statements needs to be defined inside a function first, so that it can later be called to produce some output. The def keyword is used to define a new function. def is then followed by the function name, which, in turn is followed by a set of parentheses (()). The best way to learn is from an example, and we will do just that.

def hello_world():
    print ("Hello world")

hello_world()

Let us tread carefully. In the above code, I’ve defined a function hello_world(). The function definition visibly consists of the def keyword, function name, a set of parentheses, and a colon to wrap up. What comes next is the function body or block that has instructions, which are to be interpreted by our function. In this case, we have entered a single print statement. Notice the indent before the print statement? In Python, white spaces are used to denote blocks. If you have prior experience of programming in languages like Java, C, or C++, curly brackets ({ and }) are common.

Python is free from, well…

Therefore, when you indent a line of code, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

And finally, to call a function you just name it straight away (again) followed by a pair of parentheses. Now if you wanted to repeat the code, you’d only have to call out the function as many times. Convenient right?

Functions with arguments

At the beginning of this article, I wrote a program that displayed some information about a university student. What would you do if you were asked to print out such data for multiple students? Let’s write a function that takes in multiple data values and prints the output.

functions.py
def student_info(a, b, c, d):
    first_name = a
    last_name = b
    age = c
    major = d
    
    print ("%s %s is %d years old, and his major is %s." % (first_name, last_name, age, major))

student_info('Albert', 'Einstein', 22, 'physics')
student_info('Srinivasa', 'Ramanujan', 20, 'mathematics')
student_info('Charles', 'Darwin', 19, 'geology')

In functions.py, I’ve included a, b, c, and d as arguments (so that it’d look minimal and convenient) and later on assigned them to respective meaningful variables. After I concluded the function, it was called thrice with different arguments. This is a classic example of write once, run anywhere theory. Although the slogan was originally meant for Java, it undoubtedly describes the purpose of using functions.


Functions that return a value

So far, we’ve arrived at a conclusion that functions are super effective, convenient, and flexible. Did you know that functions can also return a value? A function can return a value of a result, which can then be stored as a variable or an input for a condition statement for instance.

Consider the below piece of code:

def check(x=-9):
    if x >= 0:
        return True
    else:
        return False


value = check()

if value == True:
    print('The number is positive')
else:
    print('Negative number')

Here we’ve defined a function check, and passed a parameter x directly to it. Inside the function, there are condition statements to check if the number passed as an argument is a positive one. What return statement does, is it returns the applicable Boolean value when the function check() is called. So, when we assign the check() function to the variable value, the Boolean value returned by the return statement is stored in the variable itself.

Later on we include another set of conditional statements to examine the value, and output a statement.


Python3 Best Practices

Concluding this article, it is absolutely essential that you strive to improve the readability of your code. Writing code that’s readable will not only make you a better programmer, but it’ll take you places in your career as a programmer. As I explained earlier, white spaces count in Python. And it is standard practice that one indent must equal 4 spaces. As stated here.

PEP8 is a style guide documentation, written by Guido van Rossum – who happens to be the inventor of Python – and his companions. Following this set of guidelines will help you make your code more readable and more programmer-friendly. I’ll write a separate article to shed more light on PEP8. For now, concentrate on this line:

Readability counts.


Codingbat has some great practice exercises to stretch your mind if you are willing to take on challenges. If you’re feeling lucky, I’d suggest you head straight to CodeWars and tackle one of the Katas there ;).

Happy coding!

Reading and writing text files with Python3

Hello and welcome! I’m Saurabh Lambe, an open source enthusiast and a Linux super nerd who loves to code in Python. I’ve always wanted to publish my own programming blog on the web for two reasons: to enhance my documenting skills, and get priceless feedback for my work. Kicking off this initiative with the first (of hopefully a series of tutorials in Python3) blog to help budding programmers and Pythonistas.

We will start off easy and take baby steps towards writing into a text file.

1. Reading from a file

I’ve already created a text file containing the poem Jack and Jill, you can go ahead and be creative with whatever text you wish.

poem.txt
Jack and Jill
Went up the hill
To fetch a pail of water,
Jack fell down
And broke his crown
And Jill came tumbling after.

So that it would be convenient, we shall save the text file and the Python source code in the same directory.

The first step in reading any text file from a Python program is to save the location of the said file in a variable. On my Linux computer, I have saved the my text file on the below path:

/home/saurabh/Documents/python/poem.txt

Let us assign this “path” to a variable. Don’t forget to enclose the mentioned path by single or double quotes.

file_path = '/home/saurabh/Documents/python/poem.txt'

Python3 provides a built-in function open() that allows us to open a file and perform operations on it. Now, the open() function accepts multiple arguments.

open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

This syntax was copied from Python3 official documentation.

The code() function takes path of the file as its first argument. The mode option in the syntax above is the most important parameter. In this program, we shall use only the file and mode parameters. Some of the common modes that can be used are as follows:

open function

In order to open the poem.txt file for reading, we will use the 'r' mode. To be able to print the output from the text file, we shall the open() function to poem_file variable.

poem_file = open(path, 'r')

Since our file has now been opened and assigned to the variable poem_file, we can now use it to read the file. The read() function outputs entire content of the file as a single string.

Note: Once a file has been read using read() function, it cannot be read once again. For example, if you were to first run poem_file.read(), followed by another attempt at running the same poem_file.read() code, the second operation would return an empty string.

Here’s the complete code we’ve studied so far for reading from poem.txt.

read_poem.py
file_path = '/home/saurabh/Documents/python/poem.txt
poem_file = open(path, 'r')
print (poem_file.read())

2. Creating and writing into a file

Creating and writing into a file has the same more: 'w'. But beware, if a file with similar filename exists, this mode will erase the existing text and enter in the new text.

First of all, we’ll assign a string of words to a variable. In this example, let’s assign one of Linus Torvalds’ famous quotes to the variable quote. We’ll input this line in our new text file called quotes.txt.

quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'

Just like in the previous example, we will now assign the absolute path of the file (quotes.txt in this case) we intend to create to the variable new_path.

new_path = '/home/saurabh/Documents/python/quotes.txt'

Now that the new file path is stored in to a variable, we move on with opening the file in ‘write’ mode.

Note: If quotes.txt already existed before opening the file, its old contents would’ve been destroyed. You need to be careful while using the 'w' mode. If you wish to preserve existing text in the file, you should prefer using the 'a' which indicates append mode. It would append new text at the end of the file.

new_file = open(new_path, 'w')

The write operation takes a single parameter, most probably a string, and writes it to the file. If you want to start a new line in the file, you must explicitly provide the newline character.

create_write.py
quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'
new_path = '/home/saurabh/Documents/python/quotes.txt'
new_file = open(new_path, 'w')
new_file.write(quote)

This will create a new file called quotes.txt and it will contain the quote we had assigned to the variable in the above code. You may verify if the text file is present in the same folder where the source code exists.


3. Closing a file

After a file is opened in Python code, other applications on the computer automatically lose access to the file. Closing a file ensures two things:

  1. It terminates the connection between the file on the disk and the file variable from our code.
  2. It ensures other programs are able to access to the file and the data maintains integrity.

The in-built close() function in Python allows us to close a file in a proper way.

create_write.py
quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'
new_path = '/home/saurabh/Documents/python/quotes.txt'
new_file = open(new_path, 'w')
new_file.write(quote)

new_file.close()

Remember, it is absolutely essential that you close a file after you have finished manipulating a file. Forgetting to do so might result in other programs failing to access the said file.

To wrap up, today we learnt how to open a file to read, and write, and close it after we are done with editing it. Feedback regarding grammar and code, along with suggestions to improve my writing are always welcome. Thanks for reading, cheers!