Introduction to Python functions| Creating a youtube video downloader
Tags: python, programming, devops
Published: 2021-08-03 11:19:27

A function is a block of code that runs only when it is called.
A function can be passed `arguments` called `parameters` and can return results.

In python, functions are defined using the `def` keyword and a colon marks the beginning of the function block.

A function block in python should be indented in one tab space which is equivalent to four spaces. However, Python 3 disallows mixing the use of tabs and spaces for indentation.

Any code indented after the function declaration is part of the function. We exit out of the function by _"outdenting"_ with the same space.

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

You can read more about style guide for Python code on [pep8](https://www.python.org/dev/peps/pep-0008/).


> _In python indents are sensitive_

Calling a function in python is similar to other programming languages i.e calling the function name with brackets.

If a function requires parameters, they should be passed in the brackets.


An example of a python function:
```python
def greetings(name):
  print(f"Hello {name}!!")

# calling the function
greetings("Martin")  # Hello Martin!!
```

## Creating a YouTube video downloader. 

Creating the program involves of the following steps:

- importing of required libraries
- Creating a user interface
- creating a downloader function

## Lets start coding.

For this we will import two modules i.e `tkinter` and `pytube`.

__pytube__
According to [pytube](https://pytube.io/), its a lightweight, Pythonic, dependency-free, library (and command-line utility) for downloading YouTube Videos.

We should install the latest version of pytube as it does not come pre-installed with python.

```bash
python -m pip install git+https://github.com/nficano/pytube
```

__tkinter__
The official python [tkinter](https://docs.python.org/3/library/tkinter.html) package documentation states that its the standard Python interface to the Tk GUI toolkit.
It is a very good tool for GUI programming in python.

```python
from tkinter import *
from pytube import YouTube
```
### Creating the GUI

To make our program more user friendly, we will user `tkinter` to create the Graphical User Interface.

```python
root = Tk()
root.geometry('500x300')
root.resizable(0,0)
root.title('Youtube Downloader')

link = StringVar()

Label(root, text = 'Paste Link Here: ', font='arial 15 bold').place(x=160, y=60)
text_box = Entry(root, width = 50, textvariable = link).place(x = 32, y = 100)
```

__`root`__ is a standard name used to initialize `Tk()` as it is the base of the GUI.

__`geometry()`__ function takes a string of the form `widthxheight`, where width and height are measured in pixels for most widgets (in characters for widgets displaying text). For example: fred["geometry"] = "200x100".

By passing `0, 0` make the Interface not resizable on both axis. A value more than 0 makes the axis resizable.

Tkinter Label is a widget that is used to implement display boxes where you can place text or images.

### Creating the downloader function

`Pytube` is used for downloading videos from YouTube.
Using a function for this is perfect as this will wrap the code in one place.

```python
def download():
    url = YouTube(str(link.get()))
    video = url.streams.get_by_resolution("720p")
    video.download()
    Label(root, text = 'DOWNLOADED', font='arial 15').place(x=180, y=210)

Button(root,text = 'DOWNLOAD', font='arial 15 bold', bg='skyblue', padx = 2, command = download).place(x = 180, y = 150)

root.mainloop()
```

The  `url` variable is an instance of the `YouTube` object.

The `video` variable stores `720p` resolution stream of the video to be downloaded.

The `download` methods takes a number of arguments including `output_path`. This is download storage location of the video. If the argument is not specified then the default is the current working directory.

`mainloop()` tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until the window it's called on is closed.