Unveiling Python: The Essential Programming Language Powering the Data World

Unveiling Python: The Essential Programming Language Powering the Data World

Discover the indispensable role of Python in the realm of data, from its pivotal role in data manipulation for data engineers to its prowess in data visualization aiding data analysts. Uncover Python's versatility in facilitating data-driven insights through machine learning techniques for aspiring data scientists. Delve into the advantages of mastering Python for a myriad of data-centric disciplines, revolutionizing how we interpret and harness the power of data in today's digital landscape.

#python #programing #data

1. Printing "Hello, World!"

# Code to print "Hello, World!"
print("Hello, World!")
        

Explanation:

  • print() is a built-in Python function used to display text or variables.
  • "Hello, World!" is a string enclosed in double quotes. It's the message that will be printed to the console.

Result:

Article content

2. Calculating Area Using a Loop

# Code to calculate the area using a loop
def calculate_area(x):
    return x * x

for x in range(11):
    print(f"Area when x = {x}: {calculate_area(x)}")
        

Explanation:

  • calculate_area(x) is a function that takes the length of a side (x) and returns the area of a square.
  • for x in range(11): sets up a loop from 0 to 10 (inclusive).
  • print(f"Area when x = {x}: {calculate_area(x)}") prints the value of x and the calculated area for each value of x.

Result:

Article content


3. Comparing Sales Profits Using If-Else Statements

# Code to compare sales profits using if-else statements
import random

# Generate sales data
sales_data = [(f"Sale_{i}", random.randint(4000, 7000)) for i in range(1, 6)]

# Filter sales with profits > 5000
high_profit_sales = [(name, profit) for name, profit in sales_data if profit > 5000]

if high_profit_sales:
    highest_sale = max(high_profit_sales, key=lambda x: x[1])
    print(f"The sale with the highest profit is: {highest_sale[0]}")
    print(f"Profit: {highest_sale[1]}")
else:
    print("No sales with profits greater than 5000.")

print("Total data")
print(sales_data)        

Explanation:

  • import random is used to generate random sales data.
  • sales_data is a list containing tuples representing sales name and profit, generated randomly using list comprehension.
  • high_profit_sales is a list comprehension filtering sales with profits greater than 5000.
  • if high_profit_sales: checks if there are any high-profit sales.
  • max(high_profit_sales, key=lambda x: x[1]) finds the sale with the highest profit using the max() function and a lambda function as the key.
  • The results are then printed accordingly.

Article content


These examples demonstrate basic Python syntax and concepts such as printing, loops, functions, if-else statements, and list comprehension.


Advanced:

4. Using List Comprehension to Square Numbers Greater Than 50 in a Range

# Code to square numbers greater than 50 in a range using list comprehension

squared_numbers = [x ** 2 for x in numbers]
filter_squared_numbers = [x ** 2 if x ** 2 > 50 else 0 for x in numbers]
   
print(squared_numbers)
print("-----------")
print(filter_squared_numbers)
        


Explanation:

  • range(1, 11) generates numbers from 1 to 10.
  • [x ** 2 if x ** 2 > 50 else 0 for x in numbers] is a list comprehension that squares each number in the numbers range, but only includes the squared value if it's greater than 50, otherwise, it includes 0.
  • print(filter_squared_numbers) displays the list of squared numbers or 0s based on the condition.

Article content

This example showcases the versatility of list comprehensions in Python by allowing the incorporation of conditional expressions to filter and transform data within a single line of code to speed up the cpu-time.


5. Generating Fibonacci Sequence Using Depth-First Search (DFS)

Depth-First Search (DFS) Explained:

Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. In the context of generating Fibonacci numbers, DFS can be employed recursively to efficiently compute the sequence.


# Function to generate Fibonacci sequence using DFS
def fibonacci_dfs(n):
    # Base cases for Fibonacci sequence
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        # Initialize Fibonacci sequence with first two numbers
        sequence = [0, 1]
        # Perform DFS to generate Fibonacci sequence
        def dfs(prev1, prev2, count):
            if count == n:
                return
            next_num = prev1 + prev2
            sequence.append(next_num)
            dfs(prev2, next_num, count + 1)
        dfs(0, 1, 2)
        return sequence

# Example usage
n = 10
fib_sequence = fibonacci_dfs(n)
print(f"Fibonacci sequence of length {n}: {fib_sequence}")
        

Explanation:

  • The fibonacci_dfs function takes an integer n as input and returns the Fibonacci sequence of length n.
  • Base cases are handled first. If n is 0, an empty list is returned. If n is 1, a list containing only 0 is returned. If n is 2, a list containing [0, 1] is returned.
  • For n greater than 2, a sequence list is initialized with [0, 1].
  • The dfs function is defined inside fibonacci_dfs. It takes three parameters: prev1 and prev2 (the previous two Fibonacci numbers) and count (the current count of numbers generated).
  • The dfs function recursively generates Fibonacci numbers until the count reaches n.
  • The generated Fibonacci numbers are appended to the sequence list.
  • Finally, the fibonacci_dfs function returns the complete Fibonacci sequence.

Article content


About Testing your function

import unittest

# For Python versions < 3.3
if hasattr(unittest, 'mock'):
    from unittest.mock import patch
else:
    from mock import patch

def unit_function(input_string):
    # Check if input contains numbers
    if any(char.isdigit() for char in input_string):
        print("bad input, includes numbers..")
    else:
        # Convert string to all lowercase
        output_string = input_string.lower()
        print(output_string)

class TestUnitFunction(unittest.TestCase):

    def test_true_case(self):
        # Test case where input contains only alphabets
        expected_output = "abde"
        with patch('builtins.print') as mocked_print:
            unit_function("abDe")
            mocked_print.assert_called_once_with(expected_output)

    def test_false_case(self):
        # Test case where input contains numbers
        expected_output = "bad input, includes numbers.."
        with patch('builtins.print') as mocked_print:
            unit_function("a334")
            mocked_print.assert_called_once_with(expected_output)

if __name__ == '__main__':
    unittest.main()

        

Result:

Article content


Summary 🕶

Once you're comfortable with the basics of Python programming, including concepts like printing, loops, conditional statements, and even more advanced techniques like Depth-First Search (DFS) and one-liner code using list comprehension, you've equipped yourself with essential tools for software development.

Understanding how to write effective unit tests for your modules is crucial, especially when collaborating with a team. Testing ensures that your code behaves as expected and helps maintain its reliability over time.

With a solid foundation in Python, you're ready to explore more advanced topics. These may include:

  1. NumPy for Matrix Operations: NumPy is a powerful library for numerical computing in Python, particularly useful for handling arrays and matrices efficiently.
  2. Pandas for Data Manipulation: Pandas is a popular library for data manipulation and analysis. It provides data structures and functions to work with structured data effectively.
  3. Machine Learning Libraries: Libraries like TensorFlow, PyTorch, and scikit-learn offer tools for implementing machine learning algorithms and models. These libraries enable you to build and train predictive models, perform data analysis, and tackle complex problems in various domains.

By diving into these more advanced topics, you'll be well-equipped to tackle real-world challenges and explore exciting opportunities in data science, machine learning, and software development.


you can download the code from here in git-hub


To view or add a comment, sign in

More articles by WEI CHE Hung

Others also viewed

Explore content categories