Python 101: A beginner's guide.

gonzi

Franklin Gonzi

Posted on July 23, 2023

Python 101: A beginner's guide.

Introduction.

The Python programming language’s popularity is surging in recent times. It is a general-purpose programming language used in a variety of applications ranging from data science to automation, software and web development, etc. An example of Python application is it’s use in creating recommendation algorithms, a form of machine learning. This article gives a succinct introduction to this very popular language.

An Overview.

Python is an object-oriented and high-level computer programming language used to build software, websites, automation tasks, and data analysis. There is no specific specialized field for Python hence it’s a general-purpose programming language. It was created by Guido Van Rossum and first released on February 20th 1991. He lavishly got this name from a BBC comedy series called Monty Python’s Flying circus.
Python has spread around the world fast due to the continuous work of programmers, testers, users and enthusiasts. One factor that may have attributed to this is its versatility and easy-to-use features, some of which are listed and described in this article, but first, why Python?

Why Python?

Python Institute describes it as omnipresent (Widely or constantly encountered) and people use numerous Python-powered devices on a daily basis. Its popularity in the tech world means one can work in a multitude of jobs and industries. There are several factors/features that make Python great for learning:

  1. It is easy to learn – It takes a shorter time to learn Python compared to other programming languages. It has a simple syntax that uses English rather than punctuation. It is easy for writing new software due to faster coding.

  2. It is open source and easy to obtain, install and deploy – Python is free, open and multiplatform.

  3. It is extendable - Python code can be written in other languages such as C++ and users can low-level modules to the Python interpreter to customize and optimize tools.

  4. It has a broad standard library that provides a rich set of modules and functions that are easily accessible by everyone.

  5. It is portable – Python is a cross-platform programming language hence you can run the same code on any operating system with a Python interpreter.

  6. It is an Object-Oriented language – It uses objects and classes in programming and hence implements real-world entities like inheritance, polymorphism, data abstraction, etc.

  7. It has GUI programming support – Graphical user interfaces can be made using modules such as PyQt5.

  8. It is a high-level language – When using Python, we do not need to remember system architecture or manage memory.

  9. It allocates memory dynamically – The variable data type does not need to be specified; memory is allocated automatically at run time.

A beginner’s Python programming tutorial.

Installation and setup.

To get started working with Python, you need to have a Python interpreter (preferably the latest) installed on your computer through a series of easy steps which are available in the official website (www.python.org). There are different versions for different operating systems.
After installing the Python setup, you need to execute code and run programs. Python is used interactively by typing code directly into the interpreter, which is then executed or in a script file from the command line. Or you can use an IDE (Integrated Development Environment) such as PyCharm, Visual Studio Code, or Jupyter Notebook to interact with Python, these provide an editor with which you can create and modify code that is submitted to the interpreter for execution.

Libraries and Packages.

Python's strength lies in its extensive collection of libraries and packages. Libraries such as NumPy, Pandas, and Matplotlib provide powerful tools for data manipulation, analysis, and visualization. You can install and manage libraries using the package manager "pip" that comes with Python.

# Installing pandas library
! pip install pandas

# Importing installed libraries
import pandas as pd
Enter fullscreen mode Exit fullscreen mode

Basic Syntax and Variables.

Python uses a simple and intuitive syntax. Statements are in simple English and blocks of code are defined by indentation. Python supports different types of variables, such as integers, floating-point numbers, strings, Booleans, and more.

# Printing a string
print ("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

Variables in Python do not require explicit type declarations, as they are dynamically typed. This means that a variable's type can change during runtime based on the value it holds.
Understanding the different data types is a prerequisite for data structures. There are several built-in data structures for organizing and storing data. The four commonly used ones are lists, sets, tuples, and dictionaries.

  1. Lists - Lists are ordered collections of items enclosed in square brackets [ ]. They can contain elements of different data types (e.g., integers, strings, etc.). Lists are mutable, meaning you can modify, add, or remove elements.
my_list = [1, 2, "hello", 3.14]
Enter fullscreen mode Exit fullscreen mode
  1. Sets - Sets are unordered collections of unique items enclosed in curly braces { } or created using the set() constructor. They cannot contain duplicate values. Sets are useful for tasks like removing duplicates or checking membership. Sets are mutable, meaning you can add or remove elements.
my_set = {1,2,3,4,5}
Enter fullscreen mode Exit fullscreen mode
  1. Tuples - Tuples are ordered collections of items enclosed in parentheses () or without any delimiters. They can contain elements of different data types. Tuples are immutable, meaning you cannot modify their elements after creation. They are commonly used when you want to group related values together.
my_tuple = (1,2, "hello", 4)
Enter fullscreen mode Exit fullscreen mode
  1. Dictionaries - Dictionaries are unordered collections of key-value pairs enclosed in curly braces { } or created using the dict() constructor. They are also known as associative arrays or hash maps. Each element in a dictionary is a key-value pair, where the key is unique and used to access the corresponding value. Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs.
my_dict = {
    "name":"John",
    "age":25,
    "city": "Nairobi"
}
Enter fullscreen mode Exit fullscreen mode

These data structures serve different purposes and have various methods and operations associated with them. Understanding their characteristics and appropriate usage will help you effectively work with collections of data in Python.

Python Operators.

Operators are used to perform operations on variables and values. Python divides the operators in the following groups;

Arithmetic operators – These are used with numeric values to perform common mathematical operations.

They include;

  • addition (x + y).
  • subtraction (x – y).
  • multiplication (x * y).
  • division (x/y).
  • modulus (x%y).

Assignment operators – They are used to assign values to variables. The mostly used one is the = sign, e.g., x = 5. It can be used in combination with other signs to represent operations e.g., +=, x+= 3 is the same as x = x + 3

Comparison operators – These are used to compare values. Common ones include;

  • The Equal operator, ==, e.g., x==y
  • The Not Equal operator, !=, e.g., x!=y.
  • The Greater than operator, >, e.g., x>y.
  • The Less than operator, <, e.g., x<y.
  • The Greater than or Equal to operator, >=, e.g., x>=y.
  • The Less than or Equal to operator, <=, e.g., x<=y.

Logical operators – These are used to combine conditional statements.

  • and - Returns True if both statements are True.
  • or - Returns true if one of the statements is True.
  • not - Returns False if the result is True.

Identity operators – Used to compare objects not on an equal-to basis but on a same to or same memory location basis.

These are;

  • is - Returns True if both variables are the same object, e.g., x is y
  • is not - Returns True if both variables are not the same object, e.g., x is not y.

Membership operators – They are used to test if a sequence is presented in an object.

  • in - Returns True if a sequence with specified values are present in an object, e.g., x in y.
  • not in - Returns True if a sequence with specified values is not in an object, e.g., x not in y.

Control flow statements.

Python provides various control flow statements, such as conditional statements and loops, to control the execution of your program. Conditional statements, like if-else statements, allow you to execute different blocks of code based on certain conditions.

# if statement
x = 7
if x>0:
    print("Positive")
elif x<0:
    print("Negative")
else:
    print("zero")

# output:
Positive
Enter fullscreen mode Exit fullscreen mode
# for loop
for i in range (3):
    print(i)

# output:
0
1
2
Enter fullscreen mode Exit fullscreen mode
# while loop
count = 0
while count <3:
    print(count)
    count += 1

# output:
0
1
2
Enter fullscreen mode Exit fullscreen mode

Functions and Modules.

Functions are reusable blocks of code that perform specific tasks. They allow you to break down complex programs into smaller, manageable parts. In Python, functions are defined using the "def" keyword.

# A function that returns a greeting and name
# Function definition
def greet(name):
    print ("Hi, "+name+"!")


#Function call
greet("Franklin")


Output:
Hi, Franklin!
Enter fullscreen mode Exit fullscreen mode

Applications of Python.

Python is a versatile language and hence has a range of applications in different specialization fields. It is also evolving and opening up opportunities in new fields. A few common applications include;

  1. Web Development - Python is widely used for web development, both on the server side and client-side. Popular frameworks like Django and Flask are built using Python, making it easier to create dynamic websites and web applications.

  2. Data Analysis and Visualization- Python has become the de facto language for data analysis and manipulation due to its extensive libraries like NumPy, Pandas, and Matplotlib. These libraries provide powerful tools for data exploration, cleaning, analysis, and visualization.

  3. Machine Learning and Artificial Intelligence - Python's simplicity and the availability of libraries such as TensorFlow, Keras, and Scikit-learn have made it the go-to language for machine learning and AI development. It offers extensive support for implementing and training machine learning models, as well as processing and analyzing large datasets.

  4. Scripting and Automation - Python's easy-to-read syntax and cross-platform compatibility make it an excellent choice for scripting and automation tasks. It is often used to write scripts for automating repetitive tasks, system administration, and batch processing.

  5. Game Development - Python can be used for game development, ranging from simple 2D games to more complex ones using libraries like Pygame and Panda3D. Python's ease of use and availability of libraries make it an accessible option for game developers.

  6. Desktop GUI Applications - Python offers various frameworks like Tkinter, PyQt, and wxPython for creating graphical user interface (GUI) applications. These frameworks allow developers to build desktop applications with rich functionality and cross-platform compatibility.

  7. Network Programming - Python provides libraries like socket, asyncio, and Twisted for network programming, making it easier to create networking applications, web servers, and networking tools.

  8. Web Scraping - Python's libraries like Beautiful Soup and Scrapy make web scraping and data extraction tasks straightforward. It enables developers to extract data from websites and APIs for various purposes like data analysis, research, and automation.

  9. Internet of Things (IoT) - Python is commonly used in IoT projects for its simplicity and compatibility with microcontrollers. Libraries like PySerial and Adafruit CircuitPython enable developers to interact with sensors, devices, and IoT platforms.

Disadvantages of Python.

While Python is a popular and widely used programming language, it does have some disadvantages that may be hard to ignore. Here are a few such disadvantages:

  1. Performance - Python is an interpreted language, which means it tends to be slower than compiled languages like C or Java. This can be a significant disadvantage for computationally intensive tasks or applications that require real-time processing. While there are ways to optimize Python code, such as using libraries like NumPy or Cython, it may still fall short in terms of raw performance compared to lower-level languages.

  2. Global Interpreter Lock (GIL) - Python has a Global Interpreter Lock, which is a mechanism that prevents multiple native threads from executing Python bytecodes at once. This can limit the ability to fully leverage multi-core processors for certain types of applications, particularly those with high levels of parallelism. While there are workarounds like using multiprocessing or threading libraries, they may introduce additional complexities.

  3. Mobile and game development - Python is not considered the go-to language for mobile app development or game development, especially for performance-critical applications. Native app development for platforms like iOS or Android typically relies on languages like Swift, Objective-C, or Java/Kotlin. Similarly, game development often favors languages like C++ or C# due to their performance and existing game engines.

  4. Limited mobile support - Although Python has frameworks like Kivy and BeeWare that allow for mobile app development, the support and ecosystem for mobile development in Python are not as mature as in languages like Swift or Java. This can lead to limitations in terms of available libraries, tools, and community support, making Python less attractive for mobile-focused projects.

  5. Difficulty in code protection - Python's design philosophy emphasizes readability and simplicity, which can be beneficial for collaborative projects or learning. However, this can also make it challenging to protect Python source code from being easily reverse-engineered or tampered with. While there are tools available for code obfuscation or compilation into bytecode, they are not foolproof, and truly securing Python code can be more challenging compared to compiled languages.

Summary.

Over the past few years, Python has emerged as a top modern software due to its versatile application in modern software development, infrastructure management, and data analysis. Generally, it is an easy-to-use language and is broadly adopted and supported. However, it falls in some tasks that it is not suited for but these disadvantages are contextual and Python’s strength and range of application often outweighs them.

References.

💖 💪 🙅 🚩
gonzi
Franklin Gonzi

Posted on July 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Python 101: A beginner's guide.
python Python 101: A beginner's guide.

July 23, 2023