Skip to main content

What IS Python

Short introduction to Python

Python is a general-purpose coding languageβ€”which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development.

What IS Python - Tutorial provided by AppSeed.

Python is interpreted, easy to learn surrounded by a huge ecosystem, actively supported and used in many industries and domains.

Can be used for things like: (starting from the simple ones)

  • Basic programming: using strings, adding numbers, open files
  • Writing system scripts (creating instructions that tell a computer system to β€œdo” something)
  • Back end (or server-side) web and mobile app development
  • Desktop apps and software development
  • Processing big data and performing mathematical computations

βœ… Install Python​

The Python can be downloaded from the official website. Choose the installer for your operating system, download, and click a few times. By typing python --version in a terminal window, you should see something like this:

$ python --version
Python 3.9.12

βœ… Coding in Python​

To start using Python we need to open a terminal, type python and we should be see the python console waiting for input.

Define variables

>>> a = 'Hello'

Use a variable

>>> a
'Hello'

Concatenate strings

>>> a = 'Hello'
>>> b = ' World'
>>> a + b
'Hello World'

Multiply a string

>>> a = 'more '
>>> a * 2
'more more '

Concatenate a string with a number

>>> a = 'text '
>>> b = 1
>>> a + b
TypeError: can only concatenate str (not "int") to str
>>>
>>> a + str(b)
'text 1'

βœ… Install libraries​

Python is an open-source software actively supported by a huge ecosystem where programmers expose their work to be reused by others. Flask and Django are just a few examples. The full-index with available packages can be found on PyPI - Python Package Index.

In this section we will write code to extract the title from a web page. To do this, we will reuse two popular libraries putbished on PyPI and use them in the python console to extract the title from google.com.

PIP is a official package installer for Python and usually is shipped by Python installer.

$ pip install requests
$ pip install BeautifulSoup4

Once the libraries are installed succesfully, we can write code in the Python console. Just for fun, we can scan and extract the title from Google site with a few lines of code:

>>> import requests                        # import the library
>>> from bs4 import BeautifulSoup as bs # import the library
>>> site = 'https://google.com' # define the website we want to process
>>> page = requests.get( site ) # download the page
>>> soup = bs(page.content, 'html.parser') # Parse the downloaded page with BeautifulSoup
>>> soup.title # Print the title
<title>Google</title>

βœ… Sample Programs​

Parse Titanic.csv data​

If the CSV file is hosted online, you can still easily access and extract data from it using Python and the pandas library. You can use the URL of the CSV file directly with pd.read_csv().

Here's how to do it:

  1. Install pandas: If you haven't already installed pandas, you can do so using pip:

    pip install pandas
  2. Import pandas: Import the pandas library in your Python script.

    import pandas as pd
  3. Read the CSV file from the online source: Use the pd.read_csv() function with the URL of the CSV file.

    url = 'https://github.com/datasciencedojo/datasets/blob/master/titanic.csv'
    titanic_data = pd.read_csv(url)
  4. Explore and analyze the data: You can now work with the titanic_data DataFrame just like you would with a locally stored CSV file. You can perform various data analysis tasks on the data, such as filtering, grouping, plotting, and more.

Here's an example of how to display the first few rows of the dataset:

print(titanic_data.head())

This will show you the first 5 rows of the dataset.

Make sure that the online CSV file is publicly accessible and that you have the necessary permissions to access it.

Generate a PIE Chart​

To access the Titanic dataset, categorize passengers into "Men," "Women," and "Child," and generate a pie chart, you can follow these steps using Python and the pandas and matplotlib libraries:

  1. Import necessary libraries:

    import pandas as pd
    import matplotlib.pyplot as plt
  2. Read the Titanic dataset from an online source (as shown in the previous answer).

  3. Categorize passengers:

    You can categorize passengers into "Men," "Women," and "Child" based on age and gender. For this example, let's consider passengers aged 18 or below as "Child." You can adjust this threshold as needed.

    # Create a new column 'Category' to store passenger categories
    titanic_data['Category'] = 'Adult' # Default category is 'Adult'

    # Categorize passengers based on age and gender
    titanic_data.loc[(titanic_data['Age'] <= 18) & (titanic_data['Sex'] == 'male'), 'Category'] = 'Child'
    titanic_data.loc[(titanic_data['Age'] <= 18) & (titanic_data['Sex'] == 'female'), 'Category'] = 'Child'
    titanic_data.loc[titanic_data['Sex'] == 'female', 'Category'] = 'Women'
  4. Generate a pie chart:

    You can create a pie chart to visualize the distribution of passengers in these categories.

    # Count the number of passengers in each category
    category_counts = titanic_data['Category'].value_counts()

    # Create a pie chart
    plt.figure(figsize=(6, 6))
    plt.pie(category_counts, labels=category_counts.index, autopct='%1.1f%%', startangle=140)
    plt.title('Passenger Distribution by Category')

    # Display the pie chart
    plt.show()

    This code will create a pie chart showing the percentage distribution of passengers in the categories "Men," "Women," and "Child."

Make sure to adjust the age threshold and category definitions as needed for your analysis.

βœ… Python Web Frameworks​

A web framework, in the context of software development, is a pre-built collection of tools, libraries, and best practices designed to assist developers in building web applications, websites, or web services.

It provides a structured way to develop web applications by offering a set of reusable components and guidelines for common web development tasks. Web frameworks can be used to streamline the development process, improve code organization, and enhance the maintainability and scalability of web applications.

Here is a short list with popular frameworks for Python

Django​

Django is a leading web development framework written in Python.

Django framework follows the DRY (Don’t Repeat Yourself) principle and provides an impressive number of built-in features rather than offering them as individual libraries. Django makes use of its ORM for mapping objects to database tables.

Flask​

Flask allows the developers to build a solid web application foundation from where it is possible to use any kind of extensions required. Inspired by the Sinatra Ruby framework, the microframework requires Jinja2 template and Werkzeug WSGI toolkit.

FastAPI​

FastAPI is a modern, high-performance, web framework for building APIs with Python. It's designed to be easy to use, efficient, and to provide automatic generation of interactive documentation. FastAPI is built on top of Starlette and Pydantic, and it leverages Python 3.6+ type hints for request and response validation.

AIOHTTP​

AIOHTTP is a Python framework that relies heavily on async & awaits Python capabilities. In addition to being a server web framework, AIOHTTP can also serve as a client framework.

It provides a request object and router to enable the redirection of queries to functions developed to handle the same.

Bottle​

Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library. Here are the features:

  • Routing: Requests to function-call mapping with support for clean and dynamic URLs.
  • Templates: Fast and pythonic built-in template engine and support for mako, jinja2 and cheetah templates.
  • Utilities: Convenient access to form data, file uploads, cookies, headers and other HTTP-related metadata.
  • Server: Built-in HTTP development server and support for paste, bjoern, gae, cherrypy or any other WSGI capable HTTP server.

βœ… Resources​