How To Build a Discord Bot Using Python

How To Build a Discord Bot Using Python

Intermediate

Discord is a popular collaboration platform that initially was targeted at gamers that has more than 300million users. Within Discord, there’s an ability to create ‘bots’. These are computer users that have code behind them to respond to interactions with them but they can be very useful to do some other tasks as well.

What can you do with a discord bot?

You have control of your bot and what it can do so the ideas are endless. Some popular ideas for bots includes:

  1. Welcome bot – when you join a channel there are welcome messages and instructions for your attendees
  2. Quiz bot – a bot that can generate a quiz to test your members with trivia as a means to engage them
  3. Poll bots – a bot that can survey your members on a particular area
  4. Meme bots – these pull images from the web in reaction to your commands

There are many more ideas you can create with a discord bot. You will be able to recognise a bot with the “BOT” tag in Discord.

How the Discord bot works

A discord bot works by creating an “application” configuration in discord, assigning it to a discord user called a “bot user”, and then running a python program in our case that controls this bot user.

The architecture is as follows where you create the bot independently, then assign it to a given server with your python code running outside of Discord to provide the logic for your bot. You will need to ensure you have a place to run your code (either a server or run it in the background). Whenever your code is not running, your bot will be offline.

So the overall steps will be:

  • Step 1: Setting up your account on Discord and creating your Discord server
  • Step 2: Configuring the bot
  • Step 3: Configuring security and adding your bot to your server
  • Step 4: Writing and then running your python code for your bot logic
  • Step 5: Getting your bot to interact with messages
  • Step 6: Getting your bot show a weather forecast

Step 1: Setting up your account on Discord

First and foremost you will need to create a discord account if you haven’t already at discord.com/register

Once you’ve entered your logon details, you will need to chose a type of server. Server’s are not referring necessarily to a computer server but are more referring to a space on discord for your community. There are different styles of servers and you can select a template which best suits your intent. For this demo we’ll create a simple one:

You can then chose if it is to be a large server (“lead a community”) or intended to be a smaller server (“for friends and family”). Finally you can name the server so that people can find it,

Once you’re done, you will be taken to your own discord server! Please make sure you verify your account through your email. An activation link would have been sent to your email that you used to register.

Now with your space already set up, you’re ready to go.

Step 2: Configuring the bot

Each bot is referred to as an “application” which will need to be registered in the developer portal. This will help Discord know which bots they will allow to be embedded to a given server. You will create an “application” first, and then this will give you the authentication tokens for you to use later in your python code.

Make sure you are logged in, and then go to https://discord.com/developers/applications . In case you go to the chat window, enter the URL. You should see the following:

Click on “New Application” and then you can specify the application – in this case “Weather Forecast” bot.

You can then add further details such as icon, search tags:

You can then “Save changes”.

Finally, on the left hand menu, click on “Bot” and then “Add Bot”. This will help to assign your application as a bot and make the bot look like a user in the chat screens.

In the bot screen, you will need to click on Reset Token to get a new security token. You will need to copy this token to use in your python code. This is the security token you will use to connect to your bot. In case you lost this security token or it was leaked, you can generate a new one in this same screen:

Your Discord Bot Security Token

Step 3: Configuring Authentication and Adding Your Bot to Your Server

On the left menu list, click on OAuth. This is where permissions will be configured so that your remote python code can acccess the Discord bot.

Chose the option “bot”, and then scroll down and select all the “Text messages”. At the bottom of the screen a generated URL be created. Copy this as this will be your URL to connect to the server.

Paste the copied link into a new tab, select your server and hit continue.

Chose the server that your bot is intended to connect to – in this case “PythonHowToProgram”:

Next confirm the access rights (already pre-selected before) and click on Authorize at bottom of the screen:

Finally there will be a captcha to confirm you are a real person.

That’s it, configuration is done.

When you go to your main chat window, you should be able to see the bot in the users that are connected to your server:

The reason it shows as offline is because there’s no python code generated yet.

Step 4: Getting the bot online

So at this point, you will be able to see your bot in the server members tab but it will be offline. So here is where the coding part begins!

The engine of the bot will be a event based where you specify events to

Let’s install the discords files first.

pip install discord

Now we will import the discord files and add a token that will be used as an ID for the BOT. Remember to add the token code which you have copied from Step 1 and use that otherwise it won’t work. The following code will help to get the bot online. Please note the print statement will only show on your console and not anywhere else.

import discord

TOKEN = '<Your Discord Bot Security Token>'
client = discord.Client()

@client.event
async def on_ready():
	print('We have logged in successfully')

if __name__ == '__main__':
	client.run(TOKEN)

When you run this code – you’ll notice the code will run forever as it is waiting to process the next event:

On your Discord server you’ll now see your bot is online – it’s green!

However, right now your bot cannot do anything and cannot respond to any messages since we have yet to write that logic in there.

Step 5: How To Read Write Messages from a Discord Bot

Now the Bot is online, but it doesn’t talk or interact so in this step we are going to make the bot read user messages and store them.

The event you need to manage is “on_message”. With this event, you will intercept every message that is being entered on your server. The object that is passed is a Message object that has some interesting properties. with the argument below of message representing the Message object you can access some useful fields:

  • message.channel.name – the name of the channel where the message was sent
  • message.author.name – name of the user
  • message.content – actual content of the message

The following code will add a direct response of the message posted in the channel was ‘hello’ or ‘bye’:

#Read message
@client.event
async def on_message(message):
	print(f'({message.channel.name}):{message.author.name}:{message.content}')
	if message.content.lower() =='hello':
		await message.channel.send(f'Hello There {message.author.name}')
		return
	elif message.content.lower() == 'bye':
		await message.channel.send(f'bye bye {message.author.name}!')
		return

You can see the bot responding in Discord server below:

The code is fairly easy to understand as it just checks to see the user typed “hello” or “bye” and if so then returns a message to the same channel through the message.channel.send() function call.

There are the async and await commands that are there. These prevent the code to block if the response is not fast enough since there might be more messages that might come through at the same time. You can see an explanation here:

Now that we know how to have a bot registered that can respond, let’s create a slightly more interesting example.

Step 6: See the 5 day weather forecast from your bot

For the final section, let’s create a response from your bot, that if you ask for the current weather and provide a location, you’ll get a 7 day weather forecast as an image.

For this to work you can use the python library weatherchart

pip install weatherchart

In order to get the weather chart for a given location you need to arrange two things:

  1. Token to call a weather API from OpenWeatherMap. You can create your API key from your profile “My API Keys”
  2. The timezone name (e.g. EST or Asia/Hong_Kong) to use for the 7 day forecast. Full list on Wiki

To test the API, try the following:

from weatherchart import WeatherChart

wchart = WeatherChart('<your open weather map API token>', 'Asia/Hong_Kong')
print( wchart.get_forecast_chart_image_by_loc('Tokyo, Japan'  ) )

When you run this you’ll get the URL of your particular 7-day forecast:

You can then combine this to your discord bot fairly easily by responding to a chat. If a user types in weather <location>, then the <location> will be sent to the get_forecast_chart_image_by_loc() and a URL be returned.

wchart = WeatherChart('<your OpenWeatherMap token>', 'Asia/Hong_Kong')
space_index = message.content.find(' ')
await message.channel.send(f"{ wchart.get_forecast_chart_image_by_loc( message.content[ space_index+1:] )  }")

Hence the full code will look like this:

import discord

from weatherchart import WeatherChart
TOKEN = '<your discord bot token>'

client = discord.Client()


@client.event
async def on_ready():
	print('We have logged in successfully')

#Read message
@client.event
async def on_message(message):
	print(f'({message.channel.name}):{message.author.name}:{message.content}')
	if message.content.lower() =='hello':
		await message.channel.send(f'Hello There {message.author.name}')
		return
	elif message.content.lower() == 'bye':
		await message.channel.send(f'bye bye {message.author.name}!')
		return
	elif message.content.split(' ')[0] == 'weather':
		wchart = WeatherChart('<your OpenWeatherMap API token>', 'Asia/Hong_Kong')
		space_index = message.content.find(' ')
		await message.channel.send(f"{ wchart.get_forecast_chart_image_by_loc( message.content[space_index+1:] )  }")

if __name__ == '__main__':
	client.run(TOKEN)

With the above code, if you type in for example weather Seattle then what happens in the background is that first the location is converted to a Lat/Long, then sent to OpenWeatherMap to get the 7 day weather forecast, and finally this is converted to a chart image using quickcharts.io. A URL is in fact returned and this URL, which is an image file, when sent to the bot will be automatically be shown as that image!

Conclusion

That’s a good start on your Discord bot. We just only scratched the surface. You can do many more things such as trigger an event when a new person joins the chatroom, you could do some ‘onboarding’ for them, you could schedule a job to send reminders, you could also have some automatic moderation as well! You can refer to the official Discord developer documentation or also look into the PyPi discord library which has a range of sample code as well.

Comments? Feedback? Email us at admin@pythonHowToProgram.com

Error SendFox Connection: 403 Forbidden

403 Forbidden

Use Open Street Map To Show Geodata with python 3

Use Open Street Map To Show Geodata with python 3

Advanced

Have you ever wondered how many restaurants, buildings or schools are in your interested area? There is an amazing tool known as OSM(Open Street Map) which gives us the power to analyze and visualize any area in the most conveniently flexible way. In this blog you will learn how to use OpenStreetMap using OSMnx (a Python Package)

What is OSM (OpenStreetMap)?

Open Street Map  is a global crowd sourced dataset which focuses at developing a free editable map of the world containing a lot of information about our environment, In short it is a great open source map of the world. You can learn a lot about Open street map here in the video below which will show you how to extract data from Open street map using web browser.

Familiarize yourself with open street map

Pre – requisite Python libraries

  • geopandas
  • rtree
  • OSMnx

you can drop first two if you are using Anaconda as it automatically handles all this stuff for us. otherwise we have to manually install these from the terminal using pip.

OSMnx Python Package for Map Data

OSMnx is a python package which offers really handy functions to retrieve data from OSM and analyze, visualize and construct properties of OSM street network and other spatial data from OSM. Users can download networks with small piece of code and then analyze them.

For example a simple line of code below will download, develop and model and visualize the street network for Banglore, India

import osmnx as ox

banglore_street = ox.graph_from_place('Banglore, India', network_type = 'drive') 

blr_street_projected = ox.project_graph(banglore_street)
 
ox.plot_graph(blr_street_projected)

What can you do with OSMnx

There are many operations you can do with the map data ranging from route analysis to bounding boxes. The following is a non-exhaustive list:

  • Downloading networks with small piece of code
  • Download infrastructures, footprints and Point of interest
  • Downloading by name, a bounding box or point.
  • Downloading walk area, bike area, different kind of streets
  • Downloading nodes and edges
  • Simplify network topology
  • Fastest routes to closest graph edges
  • Save networks to disks in different formats
  • Load/Save networks from xml files
  • Analyze shortest time to different edges in a graph.

Installing OSMnx

OSMnx is on github you can install it with anaconda

conda install -c conda-forge osmnx

or on terminal using pip:

pip install osmnx

Working with OSMnx

Different GIS software packages like( QGIS, PostGIS and ArcGIS) could provide the interface to run the code here, but we will run the code in pure python here without any third party application as it will be more flexible and not incur any significant effort.

To begin with, let’s go through the above code to see what happened in there step by step.

First, let’s import the library.

import osmnx as ox

Let’s now create a variable and call the street network using place name we want to extra map data from

banglore_street = ox.graph_from_place('Banglore, India', network_type = 'drive') 

Now we will assign projection (a model) to the street network

blr_street_projected = ox.project_graph(banglore_street)

We can finally visualize the imported layer by plotting the graph:

ox.plot_graph(blr_street_projected)
Plotted Graph of Bengaluru

Check your directory in which you are working, it should be empty then we can save the shapefile using the save_graph_shapefile method which will require two arguments the projected place and the file name to be saved.

 ox.save_graph_shapefile(blr_street_projected, filename='Bengaluru')

Now if you check the working directory it will contain a folder named ‘Bengaluru’ which will contain another folders named ‘edges’ and ‘nodes’ and they contain the relative data in different formats

Open any GIS application. We will use QGIS to open these files and analyze the data as shown below are the intersections and segments of street data.

Segments of street data
Intersection of street data

Getting boundaries of places

As a next step, let’s find the boundary of a geographical region. If we go by the traditional way we will have to manually select an area and download it’s shapefile. However, we can do it easily using OSMnx as geopandas Geo Data Frames. The below code will get the boundary of Bengaluru (or ‘Bangalore’, which is the high tech center of India).

import osmnx as ox
bengaluru_boundary = ox.geocode_to_gdf('Bengaluru, India')
AXIS = ox.project_gdf(bengaluru_boundary).plot()
_ = AXIS.axis('off')

You can also select any format to search for your desired location locality, city, State, Country.

place1 = ox.geocode_to_gdf('Mumbai, Maharashtra, INDIA')
place2 = ox.geocode_to_gdf('Mumbai, INDIA')
place3 = ox.geocode_to_gdf('Maharashtra, INDIA')
place4 = ox.geocode_to_gdf('INDIA')

You can select multiple locations in your query to get a single shapefile from any geographical entity. These could be Countries, States, or cities.

places = ox.geocode_to_gdf(['India', 'China', 'Bangladesh'])
places = ox.project_gdf(places)
AXIS = places.plot()
_ = AXIS.axis('off')
Multiple Locations in single query

Downloading and modelling street network

OSMnx can be used to download the street network and build accurate topological street network, which can be used to plot the network. We can save the results in the form of SVG, GraphML or Shapefiles which can be later worked upon.

There are two key parameter types – one is the method for locating the map section:

  1. A bounding box
  2. Latitude-longitude co-ordinates
  3. Using an address and the distance we want to map
  4. A polygon of the desired street network’s boundaries
  5. Name of a place or multiple places

The second is how to traverse the network:

  1. drive: drive parameter will give us the paths that could be used to drive , excluding the service paths.
  2. drive service: drive_service parameter will give us the paths that could be used to drive, including the service paths.
  3. walk : renders all the paths that could be used by pedestrians, this excludes uni – directional paths.
  4. bike: gives us the paths that bikers and cyclists can use.
  5. all: collects all of the open(Public) part of maps that are available for use.
  6. all private” collects all the Open Street Map streets and paths, inclusive of the private ones
1. Download street networks using bounding box

This gives us the drivable street network within some latitude-longitude bounding box, in a short piece of python code

G = ox.graph_from_bbox(37.69, 37.68, -122.41, -122.43, network_type='drive')
projected_G = ox.project_graph(G)
ox.plot_graph(projected_G)
2. Download street networks using the latitude and longitude

This will get us the street network within 100 m (of the network) of a latitude-longitude point:

Graph = ox.graph_from_point((12.9716, 77.5946), dist=100, network_type='all')
ox.plot_graph(Graph)
3. Download street network using the address

This will get us the street network within 1000 m (of network) of the Jail Road, Mumbai:

G = ox.graph_from_address('100 Jail Road, Mumbai, Maharashtra', network_type='drive')
ox.plot_graph(G)
4. Download street network using a polygon

We can render a shapefile with geo-pandas, and then passing it’s geometrical shape to the OSMnx package. This will give us the street network of the Mission District in Mumbai:

Graph = ox.graph_from_polygon(mission_shape, network_type='drive')
ox.plot_graph(Graph)
5. Download street network from a place name

This is where OSMnx outperforms. Pass any place name in OSMnx for which the OpenStreetMap has an edge data, and it automatically downloads & construct the street network within that perimeter. Here, we could create the driving network within the city of Mumbai, India:

Graph = ox.graph_from_place('Mumbai, India', network_type='drive')
ox.plot_graph(Graph)

Conclusion

OpenStreetMaps are amazing to work with. We learnt that we can take out all the relevant information out of a map with just few simple lines of code, and transform that data into anything useful plan or layout for future.

Get Notified Automatically Of New Articles

Error SendFox Connection: 403 Forbidden

403 Forbidden

How To Generate Bitly Shortener URLs with the Bitly API in Python 3

How To Generate Bitly Shortener URLs with the Bitly API in Python 3

Intermediate

In this tutorial, we will be learning how we can use bitly url Api service to create shortened links using python 3 programmatically.

Let’s talk about Bitly before we get into the coding part. Bitly is a link management platform that lets you harness the power of your links by shortening, sharing, managing, and analyzing links to your content. Although there are many services, it is widely known for its url shortening service where you can have a very long URL which can be unsightly, to copy manually and difficult to communicate. The analytics capabilities are also a very valuable feature as well.

How Bitly works?

  • Copy the link you want to shorten.
  • Visit bitly homepage
  • Scroll down and you find an input box to paste the link
  • And the click on Shorten to shorten the link

So instead of going to visit Bitly every time you want to shorten the urls we will be using Bitly Api and python to save some time get the shortened url or multiple urls in just a click. All we have to do is give input URL and our code will generate the Short URL using bitly API. We will go through two methods to perform this task.

Method 1: Using bitly_api package

Step 1: Create a bitly account

Visit bitly and sign up for a new account in case you don’t have one.

Step 2: Get the access token

  • Click on your profile.
  • Open profile settings.
  • Then click on the generic access token.
  • Enter your password and you will get an access token.

Step 3: Install bitly_api library

Click on this link and download the repository from GitHub. Once the download is complete, you can extract the zip file. After extraction open your terminal/cmd prompt and navigate to the bitly-api-python-master folder.

cd bitly-api-python-master

After you navigate to the folder, run the following command

python setup.py install

And the installation process is complete.

Step 4: Sample code for bitly_api package

Here is the code:

import bitly_api  
BITLY_ACCESS_TOKEN ="YOUR_ACCESS_TOKEN" access = bitly_api.Connection(access_token = BITLY_ACCESS_TOKEN)full_link = input("Enter a link") short_url = access.shorten(full_link)  print('Short URL = ',short_url['url']) 

Like most 3rd party packages, you will need to start with importing bitly_api in your code.

Next, we have keep to have a place to keep the API keys that were setup under your bitly accountwe will declare a variable BITLY_ACCESS_TOKEN and store the access token that we copied earlier. And then call the connection function with the access token in it.

We will then create another variable named accessand call the bitly_api.Connection(access_token = BITLY_ACCESS_TOKEN)to establish a connection with bitly_api.

Next, we will be taking input url that we need to shorten and store into full_link variable.

This is where the magic happens access.shorten(full_link) we will pass the url into shorten(full_link) which will shorten our url and save it into short_url varable.

let’s print our shortened url using print('Short URL = ',short_url['url']) funtion.

But why [‘url’] ?

because the short_url stores some additional data that we don’t need so we will passing [‘url’] to get our shortened url.

And now our url shortener is ready to use !!!

Output:

Enter a URL to short https://bitly.com/documentation/v1/
Shortened URL : https://bitly.is/2KCXQaM

Method 2: Using bitlyshortener package

Using bitlyshortener

bitlyshortener is a python package created by impredicative that helps us to achieve the same results but with a more easy and simple setup. Just run the following command in your cmd/terminal to install the bitlyshortener package.

pip install bitlyshortener

Once you have installed the package successfully we can move on to the coding part.

Instead of executing the program for every single url why don’t we try and write a program that could take multiple and urls as input and convert all urls into shortened urls at once. interesting right?

This is the code:

import bitlyshortener

access_tokens = ["YOUR_ACCESS_TOKEN"] 
shortener = bitlyshortener.Shortener(tokens=access_tokens)
n=int(input( "NO. of urls want shorten?"))
long_urls=[]

for i in range(n):
    li=input("Enter url")
    long_urls.append(li)

long_urls= shortener.shorten_urls(long_urls)
print('Shortened url :',long_urls)

Firstly, import bitlyshortener then create a variable to store your access token. also, you can add multiple access tokens.

Use a variable shortener that will pass our tokens and create a connection.

Then, create a variablen that will store the count of urls to shorten.

create an empty list long_urls=[] which we will be using to store the links. taken from the user.

Now, to store these urls into long_urls=[] we will use the for loop.

for i in range(n):

li=input("Enter url") variable li is used to take input and the .append() method to store the li into list.

Once we append links in long_urls we will be calling shortener.shorten_urls(long_urls) function to shorten the url in bulk and store it back to the long_urls list.

And once the for loop is ended. we will print the list which has all the shortened links.

Output :

How many links you want shorten? 2
Enter url: https://bitly.com/documentation/v1
Enter url: https://www.google.com/search
Shortened url : ['https://bitly.is/2KCXQaM', 'https://j.mp/2Kc8zJe']

Conclusion

That’s it. In this article, we saw two methods to generate short links using bitly_api and python. in the first method, we created a program to accept a single link and generate the shorten link and in second method we created a program that will take ‘n’ number of links as input and generate the shorten link at once which also saves time and hustle to keep pasting every single link and generating the shorten link.

Get Notified Automatically Of New Articles

Error SendFox Connection: 403 Forbidden

403 Forbidden

Remove items from a list while iterating in python 3

Remove items from a list while iterating in python 3

Beginner

Managing lists is a very common task in any program activity. Within python it’s fairly straightforward to do. One area that come up is to remove items from a list while iterating in Python language, this just requires a simple pattern. We give you clear explanations with examples in this article.

There are several solutions for this task such as list comprehension, reverse iteration with remove() function, lambda function with filter() way, and while loop with copy(), append(), pop() functions. They differ from each other by their speed and readability.

The most ineffective method among the above ways is iterating through the list and removing certain items by given condition via remove() function. Because this involves copying the entire list and performing O(n) remove operation to remove certain element which is O(n^2) algorithm.

Method 1: List comprehension 

This is the easiest solution for a task. We create a list comprehension and then filter the list to save items from the given condition. So let us see an example to understand the concept. Here we want to delete the list when iterating over it. When all occurrences are not less than 5 then delete. The concept is like this:

somelist = [x for x in somelist if not determine(x)]  



So:

list_items = list(range(7))  
list_items[:] = [x for x in list_items if x < 5]  print(list_items)



Output:

Method 2. Reverse iteration.

Here we iterate values in reverse order which guarantees no elements are skipped. We use reversed() function to reverse a list. We can see an example to understand the concept:

list_items = list(range(7))
for x in reversed(list_items):
   if x >= 5:
       list_items.remove(x)
print(list_items) 


Output:

Method 3. Lambda function.

Lambda function gives a quick solution to this task. Filter() function in python is to accept a function as well as a list as an argument. This function is also to filter out elements from a sequence. Let us look at an example to understand the concept:

list_items = list(range(10)) 
list_items = list(filter(lambda x: (x < 5), list_items)) print(list_items)



Output:

Method 4. While loop to pop and append items.

Another method is using while loop to iterate through each value in the list. Then we extract them out of the list to items one by one. After that, we check a condition on each value and append them to another list. When the list is ready, we will copy that list to original list and delete that temporary list in order to save memory space.

Here we use a pop() function to remove a specified Python index. If there is no index, it will remove the last item from the list. The append() way is to add an item to the end of the list. Del keyword is to delete the index or the entire list.

Example:

list_items = list(range(7)) 
# here we create a temporary list in order to store the items that satisfy the criteria 
temporary_list = [] 
# while loop to loop through a list 
while list_items:     
        # variable x holds the items of the list one by one. pop() is    used to extract them from the list.     
        x = list_items.pop()     
        if x < 5:         
                # appending the items that meet the criteria to the temporary list         
                temporary_list.append(x) 
# the temporary list stores items in the reverse order. So copy them to list_items using reversed() 
list_items = list(reversed(temporary_list.copy())) 
# delete the temporary list to save memory 
del temporary_list 
print(list_items)



Output:

Conclusion

In conclusion, if we want to remove items from a list while iterating, we can use a list comprehension, a reverse iteration, a lambda function and a while loop using pop(), append() functions. Among them, list comprehension is the fastest in many scenarios.  However, we can use any of them according to our needs.

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden

One Line If Elif Else Statements in Python 3

One Line If Elif Else Statements in Python 3

Intermediate

If statements are present in all our code and can in fact be written efficiently in a single line. A condition-less code will be monotonous and one couldn’t do much with such a linear flow. If statements or conditional statements are an indispensable part of a programming flow to make decisions and also to direct the program flow. If... elif... else conditions steer and guide your code based on the conditions that you provide. In this article, you will learn and master the usage of If... elif... else statements in your code.

The Normal If Else Syntax

There are multiple ways to design your control flow using the If clause. Based on the use cases, simplicity, and readability, any of the following syntaxes can be used. And it is important to note that whenever a condition is used, it is used in a boolean context i.e.) Evaluation of a condition results in a boolean value, based on which the decision is take, whether to execute the expression or not to.

a) If Statement In Python

if <condition>:
    expression

A standard if block contains a condition and an expression. If the condition is tested to be True, the expression gets executed. If the condition is tested to be False, the expression won’t be executed.

'''
Snippet to check if the provided number is positive - If clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput >= 0:
    print ("The number {} is positive".format(numberInput))

if numberInput < 0:
    print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: Native If clause Demonstration

b) If… else Statement In Python

if <condition>:
    expression 1
else:
    expression 2

In the case of two conditions, either of the two conditions may hold True. In this case, the expression belonging to the condition which is tested to be True, gets executed and if this condition is tested to be False, the expression belonging to the else block gets evaluated.

'''
Snippet to check if the provided number is positive - If... else clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if a>=0:
    print ("The number {} is positive".format(numberInput))
else:
    print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: Native If-Else clause Demonstration

c) If… elif… else Statement In Python

if <condition 1>:        # If True, Execute this block and exit
    expr1
elif <condition 2>:      # If True, Execute this block and exit
    expr2
elif <condition 3>:
    expr3
else:
    do = 'this and that'

The snippet above shows the skeleton of an if... elif... else block. The block under each condition gets executed only if the condition returns True and a summary of it can be given as:

  • Each condition ends with a colon (:)
  • The statements under each condition is a block with an indentation.
  • Don’t have more than a single condition? You may avoid elif block!
  • An else condition is optional; Yes, you heard that right!

Maybe python is a new language to you or you have transitioned from another language, getting the hang of scripting in python and you might be wondering, why is else if being written as elif? Python is well known for its code readability with mandatory indentations. In fact, that’s the reason why, for better readability and to avoid excessive indentation, else if is referred to as elif.

Let’s get our hands dirty with a practical example for an ‘if-else-if’ use case:

'''
Snippet to check if the provided number is odd or even - If... Elif... Else... demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput%2 == 0: 
             # Even numbers are divisible by 2
    print ("The number {} is even".format(numberInput))
elif numberInput%2 != 0:
             # Odd numbers are not divisible by 2
    print ("The number {} is odd".format(numberInput))
else:
    print ("You have entered an invalid Number")
Odd/Even number Program Output: Native If-Elif-Else Demonstration

Checking for Multiple Conditions

In the previous section, we examined the skeleton of an If-Elif-Else block, in which each block contains a single condition. What if we wanted to have multiple conditions in a single if statement to be validated for each block? This can be done using logical operators: and, or.

if <condition 1> and <condition 2>:  # If True, Execute this block and exit
    expr1
elif <condition 3> or <condition 4>: # If True, Execute this block and exit
    expr2
elif <condition 5>:
    expr3
else:
    do = 'this and that'

condition 1 and condition 2 ==> both the conditions must be True

condition 3 or condition 4 ==> Either of the conditions must be True

For an and logical operator, if the first condition fails, the execution skips the second condition, since the validation depends on both the conditions. Let’s observe a practical example to demonstrate the usage of multiple conditions in an If Statement as follows:

'''
Snippet to find the biggest of three numbers - If Elif Else multiple conditions demonstration
'''

number_input = input("Enter three numbers separated with spaces: ")
a, b, c = number_input.split(' ')

if (a>=b) and (a>=c):
    print ("{} is the biggest".format(a))
elif (b>=a) and (b>=c):
    print ("{} is the biggest".format(b))
else:
    print ("{} is the biggest".format(c))

A Pythonic take on the If Else condition

Now that we have an understanding of how an if... elif... else conditional blocks work, let’s learn how the cool kids write the same as a one-liner. In the following sections, the examples are rewritten based on the pythonic take on the if... elif... else block.

a) One line if statements

if condition: expr

An one-liner if statement contains both the condition and the expression on a single line. This is a time saving way of writing an if statement with a single condition. Few things to note:

  • The colon (:) differentiates your condition from the expression. The space between the colon (:) and the expression (expr) need not be confined to just a single space, the indentation between them is not strict.

The following example is the one-line version of the normal if syntax.

'''
Snippet to check if the provided number is positive - If clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput >= 0: print ("The number {} is positive".format(numberInput))
if numberInput < 0: print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: One Line If clause Demonstration

b) One line if… else

expr if condition else expr

An one line if...else statement contains both the condition and the expression on a single line and the returning value needs to be assigned to a variable or passed to a function.

The following example is the one-line version of the normal if... else syntax.

'''
Snippet to check if the provided number is positive - If... else clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

print ("The number {} is positive".format(numberInput) if numberInput>=0 else "The number {} is negative".format(numberInput))
Positive/negative number Program Output: One Line If-Else clause Demonstration

c) One line if… else… if… else

expr1 if condition1 else expr2 if condition2 else expr

This lets you wrap up things pretty quickly. However, a few aspects contradict what you have learned so far when you write it as a one-liner:

  • The else after the last condition is mandatory with a value to be returned.
  • Each condition and expression is split by an else clause and not by an elif.

Time for a demonstration on the learnings from above:

'''
Snippet to check if the provided number is odd or even - If Elif Else demonstration
'''

print ("Enter your number: ")
numberInput = int(input())

# An if-else-if clause in a single line; how cool is that?

print ("Number is Even" if numberInput%2 == 0 else "Number is Odd" if numberInput%2 != 0 else "Invalid")
Odd/Even number Program Output: One Line If-Else If-Else Demonstration

Wait, but where is the switch statement?

No, we don’t have any switch statements or switch cases in Python. You can use a if..elif..else statement to do the same thing (and in some cases, use a python dictionary to do it even faster).

Summary

Practicing the above given examples, you can master the aspects of using the flow structure if... elif... else clause in your script, effectively. Although one-line conditions are time-saving, it gives poor readability to the code. It is a tradeoff between the time and the readability and it’s up to you to decide on the syntax. Some of the other commonly used control flow statements include: while and for loop with break and continue statements.

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden