Python Basics Part-1

In the ever-evolving world of DevOps, where automation and efficient software delivery are paramount, having a solid understanding of Python can be a game-changer. Python, with its simplicity, versatility, and rich ecosystem, offers numerous advantages for DevOps engineers. Whether you're involved in infrastructure management, continuous integration, deployment, or monitoring, Python can empower you to tackle complex tasks with ease and efficiency. In this blog post, we will explore the basics of Python, providing a comprehensive guide for beginners.

What is Python?

Python is a high-level, general-purpose programming language that was created by Guido van Rossum and first released in 1991. It is designed to be easy to read and write, with a clear and expressive syntax that emphasizes simplicity and readability. Python can be used to create all sorts of programs, like websites, games, data analysis tools, and much more. It is popular because it works on different types of computers and has lots of helpful tools and libraries that make programming faster and easier.

Python has gained popularity due to its versatility and ease of use, making it suitable for a wide range of applications. Here are some real-time examples where Python is commonly used:

1) Web Development: Python is widely used for web development. Popular web frameworks like Django and Flask are built with Python, enabling developers to create robust and scalable web applications.

2) Data Analysis and Visualization: Python, along with libraries such as Pandas, NumPy, and Matplotlib, is extensively used for data analysis and visualization tasks. It is employed in fields like finance, market research, and scientific research to analyze and visualize large datasets.

3) Machine Learning and Artificial Intelligence: Python has become the go-to language for machine learning and artificial intelligence applications. Libraries like TensorFlow, Keras, and scikit-learn provide powerful tools for building and training machine learning models.

4) Scientific Computing: Python is widely used in scientific computing for tasks such as simulations, data modeling, and data visualization. Libraries like SciPy and NumPy provide efficient numerical computations and scientific algorithms.

5) Scripting and Automation: Python's simplicity and ease of use make it a popular choice for scripting and automation tasks. It can be used to write scripts to automate repetitive tasks, manage files, or perform system administration tasks.

6) Game Development: Python is used in game development, both for creating complete games and for scripting game logic. Libraries like Pygame offer frameworks and tools for developing 2D games.

7) Internet of Things (IoT): Python is often used in IoT projects due to its versatility and simplicity. It can be used to develop software for controlling and interacting with IoT devices.

8) Robotics: Python is used in robotics for tasks such as controlling robots, processing sensor data, and implementing algorithms for autonomous navigation.

9) Data Science: Python is widely used in the field of data science, where it is employed for tasks like data cleaning, preprocessing, and building predictive models. Libraries like Pandas and scikit-learn are commonly used in data science workflows.

These are just a few examples, but Python's versatility allows it to be used in a wide range of applications and industries. Its rich ecosystem of libraries and frameworks makes it a flexible choice for various programming tasks.

Installation of Python

You can install Python in your System whether it is Windows, MacOS, ubuntu, centos etc. Let's check out the python installation process in Windows and Ubuntu below-

WINDOWS

  1. Visit the official Python website: python.org/downloads

  2. Download the latest version of the installer corresponding to your version of Windows (either 32-bit or 64-bit).

  3. Once the installer is downloaded, locate the installer file in your Downloads folder or the location where you saved it. The installer filename should be something like python-x.x.x.exe, where "x.x.x" represents the version number.

  4. Double-click on the installer file to launch the Python installer. You may see a security warning; click "Run" to proceed.

  5. In the Python installer, you will see an option to "Install Now." Make sure to check the box that says "Add Python to PATH" and then click on the "Install Now" button. This will ensure that Python is added to your system's PATH environment variable, allowing you to run Python from any command prompt or terminal window.

  6. The installation will begin, and you will see a progress bar indicating the installation status. It may take a few moments to complete.

  7. Once the installation is finished, you will see a screen that says "Setup was successful." You can now close the installer.

  8. To verify that Python is installed correctly, open the Command Prompt and run the command "python --version" (without the quotes) and press Enter. You should see the version number of Python printed on the screen, confirming that Python is installed correctly.

UBUNTU

Installing Python in Ubuntu is super easy, we can achieve this just by running few commands in the terminal.

  1. Open your terminal and run the below commands -
  sudo apt-get update
  sudo apt-get install python3
  • The first command updates the package index.

  • The second command installs Python 3, which is the recommended version. In Ubuntu, python3 is the command used to invoke Python 3.

  1. After the installation is complete, you can verify that Python is installed correctly by checking the version. Run the following command:
  python3 --version

This command should display the version number of Python 3 installed on your system.

  1. Additionally, you may want to install pip, the package installer for Python, by running the following command:
sudo apt install python3-pip

Pip allows you to easily install additional Python packages and libraries.

Python and pip are now installed on your Ubuntu system. You can start using Python by running scripts or launching the Python interpreter from the terminal.

Data Types in Python

Data types in programming are categories or classifications of the different types of data that can be used in a program. They define the kind of values that can be stored and manipulated. For example, data types determine whether a value is a number, a text, a true/false statement, or a collection of values.

Python has several built-in data types that are used to represent different kinds of values. Here are some commonly used data types in Python:

1) Numeric Types:

Numeric types in Python are used to represent numbers. There are three numeric types:

  • int: Represents integer values, such as 1, -10, or 1000.

  • float: Represents floating-point numbers with decimal places, such as 3.14 or -2.5.

  • complex: Represents complex numbers in the form a + bj, where a and b are floats and j is the imaginary unit.

Example:

# Integer variable
x = 10
print(x)  
print(type(x))  

# Float variable
y = 3.14
print(y)  
print(type(y)) 

# Complex variable
z = 2 + 3j
print(z)  
print(type(z))

2) Sequence Types:

Sequence types are data types that represent an ordered collection of elements or items. The elements in a sequence can be accessed using their index. Python provides several built-in sequence types, including lists, tuples, and strings.

  • str: Represents a string of characters, such as "Hello, world!" or 'Python'.
# String variable
name = "John"
print(name)
print(type(name))

# Concatenating strings
greeting = "Hello, " + name + "!"
print(greeting)

  • list: Represents an ordered collection of items, enclosed in square brackets ([]) and the elements within the list are separated by commas (,) for eg. such as [1, 2, 3]. Lists maintain the order of elements as they are inserted. You can access elements in a list using their index, starting from 0. Lists are mutable, meaning you can modify their elements after creation. You can add, remove, or change elements in a list.
# List variable
fruits = ["apple", "banana", "orange"]
print(fruits)  # Output: ['apple', 'banana', 'orange']

# Accessing list elements
print(fruits[0])  # Output: apple (Accessing the first element)
print(fruits[1])  # Output: banana (Accessing the second element)

# Modifying list elements
fruits[2] = "grape"
print(fruits)  # Output: ['apple', 'banana', 'grape']

# List concatenation
vegetables = ["carrot", "broccoli"]
combined = fruits + vegetables
print(combined)  # Output: ['apple', 'banana', 'grape', 'carrot', 'broccoli']

  • tuple: Represents an ordered, immutable collection of items enclosed in parentheses (()), and the elements within the tuple are separated by commas (,) such as (1, 2, 3). It is similar to a list, but once created, a tuple cannot be modified (immutable).
# Tuple variable
point = (5, 10)
print(point)  # Output: (5, 10)

# Accessing tuple elements
print(point[0])  # Output: 5 (Accessing the first element)
print(point[1])  # Output: 10 (Accessing the second element)

# Unpacking a tuple
x, y = point
print(x)  # Output: 5
print(y)  # Output: 10

3) Mapping Type:

dict: Represents a collection of key-value pairs, enclosed in curly braces ({}) or created using the dict() constructor. Each key-value pair is separated by a colon (:), and pairs are separated by commas (,). Dictionaries are mutable, which means you can add, update, or remove key-value pairs after the dictionary is created.

# Dictionary example
student = {
    "name": "John",
    "age": 20,
    "university": "ABC University",
    "major": "Computer Science"
}

# Accessing dictionary values
print("Name:", student["name"])
print("Age:", student["age"])
print("University:", student["university"])
print("Major:", student["major"])

4) Set Types:

Set types in Python represent unordered collections of unique elements. They include:

  • set: Represents an unordered collection of unique items, enclosed in curly braces ({}) or created using the set() constructor.

  • frozenset: Similar to a set but is immutable, meaning its elements cannot be changed once defined.

# Set example
fruits = {"apple", "banana", "orange"}
print(fruits)  # Output: {'apple', 'banana', 'orange'}
print(type(fruits))  # Output: <class 'set'>

# Adding elements to a set
fruits.add("mango")
print(fruits)  # Output: {'apple', 'banana', 'orange', 'mango'}

# Removing an element from a set
fruits.remove("banana")
print(fruits)  # Output: {'apple', 'orange', 'mango'}

# Frozenset example
immutable_fruits = frozenset(fruits)
print(immutable_fruits)  # Output: frozenset({'apple', 'orange', 'mango'})
print(type(immutable_fruits))  # Output: <class 'frozenset'>

# Trying to modify a frozenset (results in an error)
# immutable_fruits.add("grape")  # Uncommenting this line will raise an error
# immutable_fruits.remove("apple")  # Uncommenting this line will raise an error

5) Boolean Type:

bool: The boolean data type represents two possible values: True and False. Booleans are used to perform logical operations, control program flow, and make decisions based on conditions. They are case-sensitive and should be written with the first letter capitalized.

# Boolean variable
is_active = True

# Conditional statement
if is_active:
    print("User is active.")
else:
    print("User is inactive.")

6) None Type:

None: None is a built-in constant in Python that represents a null or empty value. It is often used to indicate the absence of a meaningful result or to initialize a variable without assigning it any specific value.

# None variable
result = None

# Conditional statement
if result is None:
    print("No result found.")
else:
    print("Result:", result)

These are the fundamental built-in data types in Python. Additionally, Python allows you to define your own custom data types using classes and objects, which are part of object-oriented programming in Python.

That's a wrap for today! I hope you found this article helpful. If you did, please give it a Like and let me know in the comments. In the next article, we'll dive deeper into Data types and Data structure concepts in Python, so stay tuned!