Introduction to Python Basics #2
Hello everyone, I hope you're doing well. Today I am bringing you another Python Basics Tutorial, this will cover some of the following. If you're enjoying this series then be sure to keep an eye on our Twitter for new blog announcements ahead of time! :)
- Try Statements & Error handling using Except
- if statements, elif and else
- Defining a function
- Completing the challenge from the previous blog
Try Statements, Exception Error Handling
What is the try
statement used for? The try
statement is used to catch exceptions that might be thrown as your program executes thus allowing you to handle errors with exceptions.
An example
import requests
url = "https://www.google.com"
try:
r = requests.get(url)
except requests.exceptions.ConnectionError:
print("Connection Error")
import requests
Here we can see we're importing the requests module which allows us to send requests and do all sorts more on that in the next blog where will be creating a basic Exploit for a Web App-Based Vulnerability!
url = "https://www.google.com"
This is just creating a variable called url
which has the value of https://www.google.com
try:
r = requests.get(url)
except requests.exceptions.ConnectionError:
print("Connection Error")
We start the statement using try
then we need to parse something this can be anything like a function we have defined for example
try:
function_here()
except:
print("An error happened during the exception")
r = requests.get(url)
The above code creates a response variable called r
and then it sends a GET
request to the URL Variable value which is https://www.google.com
except requests.exceptions.ConnectionError:
Here we use the except
handler which has to be defined after a try
statement has been called in this case we're using an error that has been made for Connection Errors requests
is the module we're using exceptions
is the object and we choose the ConnectionError
which if the url
variable doesn't return 200
but a connection error such as an invalid domain it'll print An error happened during the exception
except without any objects
import requests
try:
r = requests.get("https://www.invalidd0main.com")
except:
print("An error occurred")
Same above code which I will not explain, however, the exception doesn't specify any particular error out of the exceptions object within the requests, we will use this if a module doesn't have an exception inside of the objects we're looking for.
In this case, any error that gets returned will be caught and will show us An error occurred
which is the custom error message we've given, now we could've assumed where the code has broken or you could manually find it using the add a breakpoint. The simplest method would be debugging without the try
statement reading the error and then printing that back to the user E.g. HTTPConnection Error invalid URL (now you can use the try statement and on the exception with an accurate error)
if statements
What is an if statement? Think of this in English "if my dog is called Ruby its possibly my dog else it's not my dog" if statements are used to check if something may be empty, equal to or anything really.
name = input("Name: ")
name1 = "Ryan"
if name == "CustomName":
print("Hello CustomName")
elif name == name1:
print("Hello Ryan")
else:
print("Hello", name)
name = input("Name: ")
In this case, we define a variable called name
with the input()
function as its value.
name1 = "Ryan"
This is just a variable called name1
with the value of Ryan
if name == "CustomName":
print("Hello CustomName")
Here we call the statement and say (in English) if the name is custom name do something
In programming terms we check if the name
variable is equal to the string that being "CustomName" the action provided after that print()
is obvious.
elif name == name1:
print("Hello Ryan")
In python, we have this elif
statement which we can use to check multiple expressions we use it after we called the if statement but want to check another expression we could use else
however that just says if the above statement isn't True
so it calls the else
statement.
elif stands for else if
which is another naming in a programming language like CSharp.
Here we check if the variable name
is equal to the second variable called name1
which has the value of Ryan if this is true it just prints Hello Ryan
so we can check if a variable is equal to another variable we can use different Arithmetic Operators like less then etc etc.
else:
print("Hello", name)
This just says if none of the above match the user input from the name
variable being the input() function to just print("Hello")
and then the name
variable value.
Defining a function
This is a basic one but is clean.
Why would we want to define a function? When we want to call a lot of code or something like the above we could call the def()
keyword for the define function.
I am going to keep this short
def myownfunction():
name = input("Name: ")
name1 = "Ryan"
if name == "CustomName":
print("Hello CustomName")
elif name == name1:
print("Hello Ryan")
else:
print("Hello", name)
myownfunction()
Here we use the def()
function and we create the function name myownfunction
we then call the function is here myownfunction()
if we do not specify this then the code will never be ran! Now let's say we wanted to call this again in a try statement
def myownfunction():
name = input("Name: ")
name1 = "Ryan"
if name == "CustomName":
print("Hello CustomName")
elif name == name1:
print("Hello Ryan")
else:
print("Hello", name)
myownfunction()
try:
myownfunction()
except:
print("An error happened")
I will not explain the code above as what I have covered should have taught you so you can read and understand that easily.
Building a calculator
num1 = int(input("Number:"))
num2 = int(input("Number two:"))
print(num1 * num2)
This is all we needed to do! However, I want to show you how we can use what we learned today.
try:
num1 = input("Number:")
num2 = input("Number two:")
print(int(num1) * int(num2))
except ValueError:
print("Not a valid number, we only work out integers please do not specify decimals")
try:
num1 = input("Number:")
num2 = input("Number two:")
print(int(num1) * int(num2))
We call the try
statement and then have two variables one called num1
with the input()
function as its value and num2
with the input()
function as its value too! We then call the print()
function, however, we're calling the int() function which converts the value of their input to an integer, if we do not do this we will have an error has we cannot multiply a string. We use the *
as a multiply operator in Python. You can read more about this in our previous blog.
Error without using the int()
function, note we could've called the int() function on the input()
function E.g. int(input("Number:"))
You could also use the "type()" function to check the type of input().
The code is self-explanatory however, you may ask But how do you know the exception error you're looking for???
Well... Let's do some basic testing.
Note. Calling the except without anything will still give them the error made by you not the functions you're using however this doesn't help when there could be multiple reasons it may be erroring therefore we specify the exception reason.
Traceback (most recent call last):
File "/home/zmex/Desktop/Blog/blog.py", line 4, in <module>
print(int(num1) * int(num2))
ValueError: invalid literal for int() with base 10: '1.2'
Is the error being called after entering decimals which cannot be converted to integers using the ```int()``` function with the way we're using it?
Now we can except using the ValueError.
Change: ```except something(notvalid):``` or ```except:
To: except ValueError:
The End
I hope you've enjoyed this blog, it's longer but covered a lot more useful things. Everything is useful however you will use if statements and try statements A LOT.
The next blog will be constructing a Web App Exploit, we will look at where the vulnerability occurs, constructing a python exploit and then patching the vulnerability if I have time!
I hope you enjoyed, for more follow our Twitter @RiotSecTeam
just to also inform you we're already making the series on YouTube which has covered building a port scanner in Python by Zen! These will be announced on our Twitter and you can view the YouTube Video by clicking the following Link: YouTube Portscanner