Python Programming Tutorial 15

 Error Handling

Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we did in the previous lesson, but we also need to make sure that input is not going to make our program crash. In order to do that, we are going to use the try and except statements. So let's understand why the program crashed. 

Let's create a new variable called number, and let's assign a user input converted to a float and type a string to see what happens. 








This leads to an error, as Python is unable to convert this value into a string. So in order to solve this problem, we are going to use try and accept statements. 
 
Let's just copy and paste our program in a new file, and instead of converting to float immediately, we can ask for user input first. 

Instead of this: 
number = float ( input("Type a number: ") )

We are going to use this instead:
number =input("Type a number: ")

Then, we are going to use a try statement. This works the same way as the conditionals. The code after the try function is going to be inside the try statement. 
number = input("Type a number:")
try:
      number = float(numbers)
      print("The number is:", number)
What I tried to do here is that i tried to get the conversion. If we are able to get to the next line it means we were able to do this without any problems. If we see the print message, it means we made the conversion without any problem. 

If we have any errors inside the try block, instead of crashing we can just jump to the except function. And inside the except function we can print invalid number.
except:
    
    print("Invalid number")

Entire code:
number =input("Type a number: ")

try:
      number = float(number)
      print("The number is:", number)
except:
    
    print("Invalid number")
Okay, so let's run this code and see what happens. 
First, let's try a valid number and see if it will print the float conversion in the format 20.0.
Output:
>>> 
== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Error handling.py ==
Type a number: 20
The number is: 20.0
>>> 

And it worked. Now, let's try an invalid number: a string.

>>> 
== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Error handling.py ==
Type a number: test
Invalid number
>>> 

And now instead of crashing, it just printed a message. We could have done anything we wanted inside the except block. So this is how we do error handling in Python. 
See you inside our next tutorial. Goodluck.
 

 































dgbds

No comments:

Post a Comment

Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...