Python Learning Part 4
Aug 12 2019In our last post we have discussed about looping techniques, data structures in Python. In this post we’ll take a look at Functions, File Handling and Exceptions in Python.
Functions, are a block of code which are reusable throught our programme and can be called upon whenever required. We need to define functions to use them like,
>>> def function_name():
print("This is just a function")
>>> call_function = function_name()
This is just a function
Functions can be with or wihtout parameters. In the above example, we have defined a function which doesn’t have a parameter and upon calling, outputs a print statement. Similaraly,
>>> def sum(val1, val2):
s = val1 + val2
return s
>>> print(sum(3, 5))
8
The above example shows a function sum which takes two parameters as val1 & val2 and returns the sum of these two variables. Also, function can return only one value in Python. In a function, parameters may have a default argument value as well. Like,
>>> def sum_again(val1, val2=9):
s = val1 + val2
return s
>>> print(sum_again(3))
12
In the above example, we have defined a function which has a default value of 9. Which means, while calling that function even if we don’t pass second parameter it’s going to take that default value and return the output accordingly. One thing to remember here is if we have defined a variable with default value then, the variable defined after that cannot have a default value. Like,
>>> def sum_again(val1, val2=9, val3):
s = val1 + val2 + val3
return s
In the above example, val3 cannot have a default value since val2 is already having that. Python also supports Higher order functions. Higher order functions are those which can either take one or more function as argument or returns another function as output. And, map is a very useful higher order function in python. It takes one function and an iterator as input and applies that same function on each value of iterator, returning a list of results.
Files are most extensively used in our day-to-day activities to store information of any kind be it normal text, any important record, music, video etc. With Python, we can handle files quite easily and use few existing function to manipulate those as well. Let’s begin with opening a file in Python. We use open() function to open a file in following modes,
"r" -> to open in read only mode
"w" -> to open in write mode. If the file already exists, it deletes all existing content
"a" -> to open in append mode
Let’s take a look at an example:
>>> file_open = open("new_file.text")
>>> file_open
<_io.TextIOWrapper name='new_file.txt' mode='r' encoding='UTF-8'>
To close a file we use close() method,
>>> file_open = open("new_file.text")
>>> file_open.close()
When we want to read the whole file at once we use, read() method.
>>> file_open_read = open("new_file_sample.text")
>>> file_open_read.read()
'I Love Python\nAnd sometimes I code in Python too'
To read all the lines in Python we use readlines() method which stores the lines in a list.
>>> new_file = open("sample.text")
>>> new_File.readlines()
['I Love Python', 'And sometimes I code in Python too']
To write in a file we need to open the file in write mode using ‘w’ and then we can write lines in that file using write() method.
>>> new_file = open("sample.text", "w")
>>> new_file.write("PowerPuff Girls\n")
>>> new_file.write("Shaktiman")
>>> new_file.close()
Whenever we write code, it’s very likely that we’ll face errors upon execution. And that is what helps us in making our code better as well. Exceptions are such errors which occurs during the execution of code. And in Python we can handle such exceptions effectively too. We are most likely to face two kinds of error: NameError & Type Error. NameError, occurs when we try to access variables which are not defined. Where, TypeError occurs when we try to do operations with different kind of incompatible data types. To handle these exceptions we use, try…except blocks.
try:
statement 1
statement 2
statement 3
except ExceptionName:
statement to execute in case of ExceptionName occurs
Firstly, all the lines under try block are executed and if any exception happens then statements under except blocks are executed in order to handle that exception. Example,
>>> try:
x = 5/0
except ZeroDivisionError:
print("Error handled")
Handled
We can also raise exceptions in Python using raise statement.
>>> try:
raise ValueError("Here is a value error eh!")
except ValueError:
print("Value error handled")
Value error handled
And lastly, we can use finally keyword if we want to have some statements which must be executed under all circumstances. Finally, will always be executed before finishing try statements.