Using the Requests Library in Python

Using the Requests Library in Python

First things first, let’s introduce you to Requests. What is the Requests Resource? Requests is an Apache2 Licensed HTTP library, written in Python. It is designed to be used by humans to interact with the language. This means you don’t have to manually add query strings to URLs, or form-encode your POST data. Don’t worry if that made no sense to you. It will in due time. What can Requests do? Requests will allow you to send HTTP/1.1 requests using Python. With it, you can add content like headers, form data, multipart files, and parameters via simple Python libraries. It also allows you to access the response data of Python in the same way. In programming, a library is a collection of pre-configured selections of routines, functions, and operations that a program can use. These elements are often referred to as modules and stored in object format. Libraries are important because you load a module and take advantage of everything it offers without explicitly linking to every program that relies on them. They are truly standalone, so you can build your own programs with them, and yet they remain separate from other programs. Think of modules as a sort of…

Why try-except error handling is useful in Python

Why try-except error handling is useful in Python

Exceptions and errors are undesirable events in any program which may lead to termination of the program execution prematurely. In python,We use try-except error handling to handle the exceptions with python try except and finally blocks. In this article, we will look at a few reasons to use exception handling in python using different examples.  So Lets Start! We can handle errors which cannot be predicted by the programmer In real world applications, there are many use cases and constraints on the variables used in the programs. Every time it is not possible for the programmer to check all the constraints and they may miss some cases which may lead to error in the program while execution. In these cases, we can use try-except error handling to handle the unexpected errors and recover the program if needed. For example, Suppose the user presses ctrl+c or del key to interrupt the program in between the execution, then the program abruptly terminates because KeyBoardInterrupt error occurs. We can handle the error using try-except error handling as follows and show custom message before terminating the program or we can execute other statements to save the state of the program in the file system. In this way we can avoid loss of data…

Try and Except in Python

Try and Except in Python

Earlier I wrote about Errors and Exceptions in Python. This post will be about how to handle those. Exception handling allows us to continue our program (or terminate it) if an exception occurs. Error Handling Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. Try and Except If an error is encountered, a try block code execution is stopped and transferred down to the except block. In addition to using an except block after the try block, you can also use the final block. The code in the finally block will be executed regardless of whether an exception occurs. Exception Handling in Python Exception Handling in Python: Writing a Robust Python Program How to Best Use Try-Except in Python Raising an Exception You can raise an exception in your own program by using the raise exception [, value] statement. Raising an exception breaks current code execution and returns the exception back until it is handled. Example A try block look like below try: print “Hello World” except: print “This is an error message!” Exception Errors Some of the common exception errors are: IOError – If the file cannot be opened.…

Errors and Exceptions in Python

Errors and Exceptions in Python

Errors and Exceptions In Python, there are two kinds of errors: syntax errors and exceptions. This post will describe what those errors are. Upcoming posts will show how we can handle those errors. Syntax Errors Let’s start with syntax errors, (also known as parsing errors). The parser repeats the offending line and displays an ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the keyword print, since a colon (‘:’) is missing before it. File name and line number are printed so you know where to look in case the input came from a script. Example Example of a syntax error >>> while True print ‘Hello world’ File “”, line 1, in ? while True print ‘Hello world’ ^ SyntaxError: invalid syntax Python Programming – Exception Handling Python Programming – Exception Handling Exception Handling in Python Exceptions The other kind of errors in Python are exceptions. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution…

How to handle Errors and Exceptions in Python

How to handle Errors and Exceptions in Python

Errors and Exceptions If you (and you will) write code that doesn’t work, you will get an error message. What are exceptions? Exceptions is what you get after you have first ran the program. Different Errors There are different kind of errors in Python, here are a few of them: ValueError, TypeError, NameError, IOError, EOError, SyntaxError This output show a NameError: >>> print 10 * ten Traceback (most recent call last): File “”, line 1, in NameError: name ‘ten’ is not defined and this output show it’s a TypeError >>> print 1 + ‘ten’ Traceback (most recent call last): File “”, line 1, in TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ Exception Handling in Python Exception Handling in Python: Writing a Robust Python Program Python Programming – Exception Handling Try and Except There is a way in Python that helps you to solve this: try and except #Put the code that may be wrong in a try block, like this: try: fh = open(“non_existing_file”) #Put the code that should run if the code inside the try block fails, like this: except IOError: print “The file does not exist, exiting gracefully” #Putting it together, it will look like this:…

Exception Handling in Python Writing a Robust Python Program

Exception Handling in Python: Writing a Robust Python Program

While writing programs in python, there may be situations where the program enters into an undesirable state called exceptions and exits the execution. This may cause loss of work done or may even cause a memory leak. In this article, we will see how to handle those exceptions so that the program can continue executing in a normal way using exception handling in python. We will also see what are different ways to implement exception handling in python. What are exceptions in Python? An exception is an undesirable event/error in a program that disrupts the flow of execution of the statements in the program and stops the execution of the program if the exception is not handled by the program itself.  There are some predefined exceptions in python. We can also declare user-defined exceptions by defining exceptions by creating classes that inherit the Exception class in python and then creating the exceptions using the raise keyword during the execution of the program. In the following program, we create a dictionary and try to access the values using the keys in the python dictionary. Here, an error occurs in second print statement as “c” is not present in the dictionary as a key. The…

Exception Handling in Python

Exception Handling in Python

Overview In this post we will cover how Python handles errors with exceptions. What is an Exception? An exception is an error that happens during execution of a program. When that error occurs, Python generate an exception that can be handled, which avoids your program to crash. Why use Exceptions? Exceptions are convenient in many ways for handling errors and special conditions in a program. When you think that you have a code which can produce an error then you can use exception handling. Raising an Exception You can raise an exception in your own program by using the raise exception statement. Raising an exception breaks current code execution and returns the exception back until it is handled. Python Programming – Exception Handling Python Programming – Exception Handling Python Programming – Python User Defined Exceptions Exception Errors Below is some common exceptions errors in Python: IOError If the file cannot be opened. ImportError If python cannot find the module ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete) EOFError Raised when one of the built-in functions (input() or raw_input())…

Ways to create dictionary in Python

Ways to create dictionary in Python

In python, a dictionary is a data structure in which we can keep data in the form of key-value pairs. In this article, we will study and implement various methods to create a dictionary in python. Create an empty dictionary in python We can create an empty python dictionary using curly braces or a dictionary constructor. To create an empty dictionary using curly braces, we simply declare a variable and assign a pair of curly braces as shown below. myDict={} print(“Created dictionary is:”) print(myDict) Output: Created dictionary is: {} In the output above, the curly braces show that an empty dictionary has been created. To create an empty dictionary using a dictionary constructor, we can simply call the constructor dict() and assign it to a variable as follows. myDict=dict() print(“Created dictionary is:”) print(myDict) Output: Created dictionary is: {} In the above program, we have used dict() constructor to create an empty dictionary. We can also use the above methods to create dictionaries with key value pairs already defined which has been discussed in following sections. Python Programming – Creation, Initialization and Accessing The Elements In A Dictionary Dictionary Comprehension in Python Iterating over dictionary in Python Create dictionary with key value pairs already defined To…

What is a Dictionary

What is a Dictionary

What is a Dictionary? Dictionaries are collections of items that have a “key” and a “value”. Dictionaries are mutable. You do not have to reassign the dictionary to make changes to it. They are just like lists, except instead of having an assigned index number, you make up the index: Example 1 testList = [“first”, “second”, “third”] testDict = {0:”first”, 1:”second”, 2:”third”} A dictionary in Python is enclosed by {}, and to create one you have to provide a key / value. Each key in the dictionary must be unique. A colon is placed between key and value (key:value) Each key:value pair is separated by a comma Dictionary Comprehension in Python Python Dictionary Basic Usage Python Programming – Dictionaries Example 2 >> phonenumbers = {‘Jack’:’555-555′, ‘Jill’:’555-556′} phonebook = {} phonebook[“Jack”] = “555-555” phonebook[“Jill”] = “555-556” print phonebook {‘Jill’: ‘555-556’, ‘Jack’: ‘555-555’} Dictionaries only work one way, to get a value out of a dictionary,you MUST enter the key. You cannot provide the value and get the key. Example 3 phonebook = {} phonebook[“Jack”] = “555-555” phonebook[“Jill”] = “555-556” print phonebook[‘Jill’] 555-556 Key / Value Usage To add a key / value pair in a dictionary >>phonebook[“Matt”] = “555-557” To change…

How to use Split in Python

How to use Split in Python

Learn how to use split in python. Quick Example: How to use the split function in python Create an array x = ‘blue,red,green’ Use the python split function and separator x.split(“,”) – the comma is used as a separator. This will split the string into a string array when it finds a comma. Result [‘blue’, ‘red’, ‘green’] Definition The split() method splits a string into a list using a user specified separator. When a separator isn’t defined, whitespace(” “) is used. Why use the Split() Function? At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one. To do this, you use the python split function. What it does is split or breakup a string and add the data to a string array using a defined separator. If no separator is defined when you call upon the function, whitespace will be used by default. In simpler terms, the separator is a defined character that will be placed between each variable. How to split string variables in Python Python Programming – String Functions Python String Methods for String Manipulation Examples of the Python Split…