Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday 17 September 2024

Create Audio Book using Python

 

from gtts import gTTS

import os


def create_audiobook(text_file, output_file):

    with open(text_file, 'r', encoding='utf-8') as file:

        text = file.read()


    tts = gTTS(text=text, lang='en')


    tts.save(output_file)

    print(f"Audiobook saved as {output_file}")


text_file = "clcodingtxt.txt"  

output_file = "audiobook.mp3"


create_audiobook(text_file, output_file)

os.system(f"start {output_file}")  


#source code --> clcoding.com

Generate Emoji using Python

 

import emoji


def text_to_emoji(text):

    return emoji.emojize(text)


input_text = input("Enter text with emoji aliases : ")


converted_text = text_to_emoji(input_text)


print("Converted Text with Emojis:", converted_text)


#source code --> clcoding.com

Monday 16 September 2024

Python Program to Check Email Accounts Across Services

 

import subprocess


def check_email(email):

    result = subprocess.run(["holehe", email],

                            capture_output=True, text=True)

    return result.stdout


email = input("Enter the email: ")

response = check_email(email)

print(response)


#source code --> clcoding.com



Sunday 15 September 2024

A Quick Guide to Learning Python: Easy Coding, Designed for Beginners | Free

 

Mastering a programming language requires understanding code and writing it effectively. This book offers quizzes to improve skills in reading and understanding code, while the exercises aim to improve writing code skills.

Each chapter starts with an explanation and code examples and is followed by exercises and quizzes, offering an opportunity for self-testing and understanding which level you achieved.

This book goes beyond the traditional approach by explaining Python syntaxes with real-world code examples. This approach makes learning exciting and ensures readers can apply their knowledge effectively. The included exercises and quizzes, along with their solutions, provide a guarantee to readers and empower them to create simple yet valuable programs.

Learning one computer language facilitates learning other computer languages. This principle arises from rules and logic that connect computer languages. A confirmation of this was when I was asked to teach the C# programming language at the University of Applied Science. Despite having no experience with C#, I dedicated a weekend to diving into the language and realized it wasn't fundamentally different from other object-oriented programming languages.

Python is also a language reliant on object-oriented programming principles. Our focus is real-world examples, enabling you to apply these concepts in your programming works. Learning programming is a communication tool with computers, as machines operate using their language defined by specific logical structures and sentences known as statements.

Free Kindle : A Quick Guide to Learning Python: Easy Coding, Designed for Beginners

Friday 13 September 2024

Create table using Python

 

Rich allows you to display data in well-formatted tables, useful for presenting data in a structured manner.


Use Case: Displaying tabular data in the terminal (e.g., database results, CSV data).


from rich.table import Table

from rich.console import Console


console = Console()

table = Table(title="User Data")


table.add_column("ID", justify="right", style="cyan", no_wrap=True)

table.add_column("Name", style="magenta")

table.add_column("Age", justify="right", style="green")


table.add_row("1", "Alice", "28")

table.add_row("2", "Bob", "32")

table.add_row("3", "Charlie", "22")


console.print(table)

      User Data       

┏━━━━┳━━━━━━━━━┳━━━━━┓

┃ ID ┃ Name    ┃ Age ┃

┡━━━━╇━━━━━━━━━╇━━━━━┩

│  1 │ Alice   │  28 │

│  2 │ Bob     │  32 │

│  3 │ Charlie │  22 │

└────┴─────────┴─────┘

Rich – Display colorful, formatted console output using Python

 

pip install rich

from rich.console import Console

console = Console()

message = "Welcome to [bold magenta]clcoding.com[/bold magenta]"
style = "bold green"

console.print(message, style=style)

#clcoding.com
Welcome to clcoding.com

Monday 9 September 2024

Spiralweb using Python

 

import matplotlib.pyplot as plt

import numpy as np


num_lines = 50;  num_turns = 10;  num_points = 1000  


fig, ax = plt.subplots(figsize=(6, 6))

theta = np.linspace(0, num_turns * 2 * np.pi, num_points)

r = np.linspace(0, 1, num_points)


x = r * np.cos(theta)

y = r * np.sin(theta)

ax.plot(x, y, color='black')


for i in range(num_lines):

    angle = 2 * np.pi * i / num_lines

    x_line = [0, np.cos(angle)]

    y_line = [0, np.sin(angle)]

    ax.plot(x_line, y_line, color='black', linewidth=0.8)


ax.axis('off')

plt.show()

# Source code -->  clcoding.com

Bullet Charts using Python

 

import matplotlib.pyplot as plt

categories = ['Category']

values = [75]

ranges = [(50, 100)]

markers = [85]

fig, ax = plt.subplots()

ax.barh(categories, values, color='lightblue')

for i, (low, high) in enumerate(ranges):

    ax.plot([low, high], [i]*2, color='black')

    ax.plot([markers[i]], [i], marker='o', markersize=10, color='blue')

plt.title('Bullet Chart')

plt.show()

# Source code --> clcoding.com

Sunday 8 September 2024

Convert CSV to JSON using Python

 

import csv

import json


def csv_to_json(csv_file, json_file):

    

    with open(csv_file, mode='r') as file:

        csv_reader = csv.DictReader(file)

        data = [row for row in csv_reader]


    with open(json_file, mode='w') as file:

        json.dump(data, file, indent=4)


    print(f"CSV to JSON conversion completed! {json_file}")


csv_to_json('Instagram.csv', 'data.json')


#source code --> clcoding.com

CSV to JSON conversion completed! data.json

Friday 6 September 2024

4 Python Power Moves to Impress Your Colleagues

 

1. Use List Comprehensions for Cleaner Code

List comprehensions are a compact way to generate lists from existing lists or other iterable objects. They are often faster and more readable than traditional for loops.


# Traditional for loop approach

squares = []

for i in range(10):

    squares.append(i**2)


# List comprehension approach

squares = [i**2 for i in range(10)]



2. Use the zip() Function for Iterating Over Multiple Lists

The zip() function allows you to combine multiple iterables and iterate through them in parallel. This is useful when you need to handle multiple lists in a single loop.


names = ['Alice', 'Bob', 'Charlie']

scores = [85, 90, 95]


for name, score in zip(names, scores):

    print(f'{name}: {score}')

Alice: 85

Bob: 90

Charlie: 95



3. Use enumerate() for Indexed Loops

Instead of manually managing an index variable while iterating, you can use the enumerate() function, which provides both the index and the value from an iterable.


fruits = ['apple', 'banana', 'cherry']


# Without enumerate

for i in range(len(fruits)):

    print(i, fruits[i])


# With enumerate

for i, fruit in enumerate(fruits):

    print(i, fruit)

0 apple

1 banana

2 cherry

0 apple

1 banana

2 cherry




4. Use Unpacking for Cleaner Variable Assignment

Python supports unpacking, which allows you to assign multiple variables in a single line. This is particularly useful when working with tuples or lists.


# Unpacking a tuple

point = (3, 5)

x, y = point

print(f'X: {x}, Y: {y}')


# Unpacking with a star operator

a, *b, c = [1, 2, 3, 4, 5]

print(a, b, c)  

X: 3, Y: 5

1 [2, 3, 4] 5

Thursday 5 September 2024

Flexible Chaining Without External Libraries



1. Basic Math Operations Pipeline

def add(x, y):

    return x + y


def multiply(x, y):

    return x * y


def subtract(x, y):

    return x - y


def pipe(value, *functions):

    for func, arg in functions:

        value = func(value, arg)

    return value


# Example

result = pipe(5, (add, 3), (multiply, 4), (subtract, 10)) 

print(result)  

22




2. String Manipulation Pipeline

def append_text(text, suffix):

    return text + suffix


def replace_characters(text, old, new):

    return text.replace(old, new)


def pipe(value, *functions):

    for func, *args in functions:  

        value = func(value, *args)

    return value


# Example

result = pipe("hello", (append_text, " world"), (replace_characters, "world", "Python"))

print(result)  

hello Python



3. List Transformation Pipeline

def append_element(lst, element):

    lst.append(element)

    return lst


def reverse_list(lst):

    return lst[::-1]


def multiply_elements(lst, factor):

    return [x * factor for x in lst]


def pipe(value, *functions):

    for func, *args in functions:

        if args:  # If args is not empty

            value = func(value, *args)

        else:  # If no additional arguments are needed

            value = func(value)

    return value


# Example

result = pipe([1, 2, 3], (append_element, 4), (reverse_list,), (multiply_elements, 2))

print(result)  

[8, 6, 4, 2]



4. Dictionary Manipulation Pipeline

def add_key(d, key_value):

    key, value = key_value

    d[key] = value

    return d


def increment_values(d, inc):

    return {k: v + inc for k, v in d.items()}


def filter_by_value(d, threshold):

    return {k: v for k, v in d.items() if v > threshold}


def pipe(value, *functions):

    for func, arg in functions:

        value = func(value, arg)

    return value


# Example

result = pipe({'a': 1, 'b': 2}, (add_key, ('c', 3)), (increment_values, 1), (filter_by_value, 2))

print(result)  

{'b': 3, 'c': 4}


Wednesday 4 September 2024

Watermarking in Python

 

from PIL import Image, ImageDraw, ImageFont


def add_watermark(input_image_path, output_image_path, watermark_text):

    original = Image.open(input_image_path).convert("RGBA")

    txt = Image.new("RGBA", original.size, (255, 255, 255, 0))

    font = ImageFont.truetype("arial.ttf", 40)

    draw = ImageDraw.Draw(txt)

    width, height = original.size

    text_bbox = draw.textbbox((0, 0), watermark_text, font=font)

    text_width = text_bbox[2] - text_bbox[0]

    text_height = text_bbox[3] - text_bbox[1]

    position = (width - text_width - 10, height - text_height - 10)

    draw.text(position, watermark_text, fill=(255, 255, 255, 128), font=font)

    watermarked = Image.alpha_composite(original, txt)

    watermarked.show()  

    watermarked.convert("RGB").save(output_image_path, "JPEG")


add_watermark("cl.jpg", "cloutput.jpg", "clcoding.com")

Encryption and Decryption in Python Using OOP

 


class Encrypt:

    def __init__(self):

        self.send = ""

        self.res = []


    # Sender encrypts the data

    def sender(self):

        self.send = input("Enter the data: ")

        self.res = [ord(i) + 2 for i in self.send]  

        print("Encrypted data:", "".join(chr(i) for i in self.res))


class Decrypt(Encrypt):

    # Receiver decrypts the data

    def receiver(self):

        decrypted_data = "".join(chr(i - 2) for i in self.res)  

        print("Decrypted data:", decrypted_data)


# Usage

obj = Decrypt()

obj.sender()

obj.receiver()


#source code --> clcoding.com

Encrypted data: jvvru<11z0eqo1eneqfkpi

Decrypted data: https://x.com/clcoding

Monday 2 September 2024

5 Essential Tuple Unpacking Techniques

 

1. Basic Tuple Unpacking

person = ("John", 28, "Engineer")


name, age, profession = person


print(f"Name: {name}")

print(f"Age: {age}")

print(f"Profession: {profession}")

Name: John

Age: 28

Profession: Engineer

Explanation: This program unpacks a tuple containing personal details into individual variables.



2. Swapping Variables Using Tuple Unpacking

a = 5

b = 10


a, b = b, a


print(f"a: {a}")

print(f"b: {b}")

a: 10

b: 5

Explanation: This program swaps the values of two variables using tuple unpacking in a single line.



3. Unpacking Elements from a List of Tuples

students = [("Alice", 85), ("Bob", 90), ("Charlie", 88)]


for name, score in students:

    print(f"Student: {name}, Score: {score}")

Student: Alice, Score: 85

Student: Bob, Score: 90

Student: Charlie, Score: 88

Explanation: This program iterates over a list of tuples and unpacks each tuple into individual variables within a loop.



4. Unpacking with * (Star Operator)

numbers = (1, 2, 3, 4, 5, 6)


first, second, *rest = numbers


print(f"First: {first}")

print(f"Second: {second}")

print(f"Rest: {rest}")

First: 1

Second: 2

Rest: [3, 4, 5, 6]

Explanation: This program uses the * (star) operator to unpack the first two elements of a tuple and collect the rest into a list.



5. Returning Multiple Values from a Function Using Tuple Unpacking

def get_student_info():

    name = "Eve"

    age = 22

    major = "Computer Science"

    return name, age, major


student_name, student_age, student_major = get_student_info()


print(f"Name: {student_name}")

print(f"Age: {student_age}")

print(f"Major: {student_major}")

Name: Eve

Age: 22

Major: Computer Science

Explanation: This program demonstrates how a function can return multiple values as a tuple, which can then be unpacked into individual variables when called.

Friday 30 August 2024

How much do know Python's is Operator?

 

1. Comparing Small Integers

a = 100

b = 100


print(a is b)

True

Explanation:


In Python, small integers (typically between -5 and 256) are cached and reused for efficiency.

When you assign 100 to both a and b, they reference the same memory location because they fall within this range.

Thus, a is b returns True because a and b point to the same object in memory.

2. Comparing Large Integers

a = 300

b = 300


print(a is b)

False

Explanation:


Integers outside the small integer cache range (typically beyond 256) are not necessarily cached.

When you assign 300 to both a and b, they may reference different memory locations.

As a result, a is b returns False because a and b do not necessarily point to the same object in memory.


3. Comparing Strings

a = "hello"

b = "hello"


print(a is b)

True

Explanation:


Python optimizes string storage by using interning for identical string literals.

Since both a and b are assigned the same string literal "hello", they point to the same object in memory.

Hence, a is b returns True because a and b reference the same object.

4. Comparing Lists python

a = "hello"

b = "hello"


print(a is b)

True

Explanation:


Lists are mutable and are not interned like small integers or strings.

Even if a and b contain the same elements, they are distinct objects in memory.

Therefore, a is b returns False because a and b do not refer to the same memory location.


5. Comparing Tuples

a = (1, 2, 3)

b = (1, 2, 3)


print(a is b)

False

Explanation:


Tuples with identical content are not always interned or cached by Python.

Although a and b have the same elements, they are separate objects in memory.

Hence, a is b returns False because a and b do not necessarily point to the same object in memory.

Thursday 29 August 2024

Manhattan Distance in Python

 

Manhattan Distance in Python

def manhattan_distance(point1, point2):

    return sum(abs(a - b) for a, b in zip(point1, point2))


point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance(point1, point2)

print(f"Manhattan distance: {distance}")

Manhattan distance: 7

Manhattan Distance Using NumPy

import numpy as np


def manhattan_distance_np(point1, point2):

    return np.sum(np.abs(np.array(point1) - np.array(point2)))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_np(point1, point2)

print(f"Manhattan distance (NumPy): {distance}")

Manhattan distance (NumPy): 7

Manhattan Distance Using a Custom Loop

def manhattan_distance_loop(point1, point2):

    distance = 0

    for a, b in zip(point1, point2):

        distance += abs(a - b)

    return distance


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_loop(point1, point2)

print(f"Manhattan distance (Loop): {distance}")

Manhattan distance (Loop): 7

Manhattan Distance Using Map and Lambda

def manhattan_distance_map(point1, point2):

    return sum(map(lambda a, b: abs(a - b), point1, point2))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_map(point1, point2)

print(f"Manhattan distance (Map and Lambda): {distance}")

Manhattan distance (Map and Lambda): 7

Manhattan Distance Using a One-Liner Function

manhattan_distance_oneliner = lambda p1, p2: sum(abs(a - b) for a, b in zip(p1, p2))


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_oneliner(point1, point2)

print(f"Manhattan distance (One-Liner): {distance}")

Manhattan distance (One-Liner): 7

Manhattan Distance Using List Comprehension

def manhattan_distance_listcomp(point1, point2):

    return sum([abs(a - b) for a, b in zip(point1, point2)])


# Example usage

point1 = (1, 2)

point2 = (4, 6)

distance = manhattan_distance_listcomp(point1, point2)

print(f"Manhattan distance (List Comprehension): {distance}")

Manhattan distance (List Comprehension): 7

Wednesday 28 August 2024

Create Your First Web App with Python and Flask

 


What you'll learn

Create Web Applications with Flask

Use WTForms and SQLAlchemy in Flask Applications

Use Templates in Flask Applications

Join Free: Create Your First Web App with Python and Flask

About this Guided Project

In this 2-hour long project-based course, you will learn the basics of web application development with Python using the Flask framework. Through hands on, practical experience, you will go through concepts like creating a Flask Application, using Templates in Flask Applications, using SQLAlchemy and SQLite with Flask, and using Flask and WTForms. You will then apply the concepts to create your first web application with Python and Flask.

This course is aimed at learners who are looking to get started with web application development using Python, and have some prior programming experience in the Python programming language. The ideal learner has understanding of Python syntax, HTML syntax, and computer programming concepts.

Note: This course works best for learners who are based in the North America region. We’re currently working on providing the same experience in other regions.

Developing AI Applications with Python and Flask

 


What you'll learn

Describe the steps and processes involved in creating a Python application including the application development lifecycle 

Create Python modules, run unit tests, and package applications while ensuring the PEP8 coding best practices

Explain the features of Flask and deploy applications on the web using the Flask framework

Create and deploy an AI-based application onto a web server using IBM Watson AI Libraries and Flask

Join Free: Developing AI Applications with Python and Flask

There are 3 modules in this course

This mini course is intended to apply basic Python skills for developing Artificial Intelligence (AI) enabled applications. In this hands-on project you will assume the role of a developer and perform tasks including:  

- Develop functions and application logic 
- Exchange data using Watson AI libraries
- Write unit tests, and 
- Package the application for distribution. 

You will demonstrate your foundational Python skills by employing different techniques to develop web applications and AI powered solutions. After completing this course, you will have added another project to your portfolio and gained the confidence to begin developing AI enabled applications using Python and Flask, Watson AI libraries, build and run unit tests, and package the application for distribution out in the real world.

Tuesday 27 August 2024

5 Practical Python Programs Using the Pickle Library

 

1. Saving and Loading a List

This program saves a list to a file and then loads it back.


import pickle


my_list = ['apple', 'banana', 'cherry']


with open('list.pkl', 'wb') as file:

    pickle.dump(my_list, file)


with open('list.pkl', 'rb') as file:

    loaded_list = pickle.load(file)


print("Loaded List:", loaded_list)


#source code --> clcoding.com

Loaded List: ['apple', 'banana', 'cherry']



2. Saving and Loading a Dictionary

This program demonstrates saving a dictionary to a file and loading it back.


import pickle


my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}


with open('dict.pkl', 'wb') as file:

    pickle.dump(my_dict, file)


with open('dict.pkl', 'rb') as file:

    loaded_dict = pickle.load(file)


print("Loaded Dictionary:", loaded_dict)


#source code --> clcoding.com

Loaded Dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}



3. Saving and Loading a Custom Object

This program saves an instance of a custom class to a file and loads it back.


import pickle


class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age


    def __repr__(self):

        return f"Person(name={self.name}, age={self.age})"


person = Person('Alice', 25)


with open('person.pkl', 'wb') as file:

    pickle.dump(person, file)


with open('person.pkl', 'rb') as file:

    loaded_person = pickle.load(file)


print("Loaded Person:", loaded_person)


#source code --> clcoding.com

Loaded Person: Person(name=Alice, age=25)



4. Saving and Loading a Tuple

This program saves a tuple to a file and loads it back.


import pickle


my_tuple = (10, 20, 30, 'Hello')


with open('tuple.pkl', 'wb') as file:

    pickle.dump(my_tuple, file)


with open('tuple.pkl', 'rb') as file:

    loaded_tuple = pickle.load(file)


print("Loaded Tuple:", loaded_tuple)


#source code --> clcoding.com

Loaded Tuple: (10, 20, 30, 'Hello')



5. Saving and Loading Multiple Objects

This program saves multiple objects to a single file and loads them back.


import pickle


list_data = [1, 2, 3]

dict_data = {'a': 1, 'b': 2}

string_data = "Hello, World!"


with open('multiple.pkl', 'wb') as file:

    pickle.dump(list_data, file)

    pickle.dump(dict_data, file)

    pickle.dump(string_data, file)


with open('multiple.pkl', 'rb') as file:

    loaded_list = pickle.load(file)

    loaded_dict = pickle.load(file)

    loaded_string = pickle.load(file)


print("Loaded List:", loaded_list)

print("Loaded Dictionary:", loaded_dict)

print("Loaded String:", loaded_string)


#source code --> clcoding.com

Loaded List: [1, 2, 3]

Loaded Dictionary: {'a': 1, 'b': 2}

Loaded String: Hello, World!


7 Lesser-Known Python Techniques about Lists

 

1. Flatten a Nested List

Flatten a deeply nested list into a single list of elements.


from collections.abc import Iterable


def flatten(lst):

    for item in lst:

        if isinstance(item, Iterable) and not isinstance(item, str):

            yield from flatten(item)

        else:

            yield item


nested_list = [1, [2, 3, [4, 5]], 6]

flat_list = list(flatten(nested_list))

print(flat_list)  

[1, 2, 3, 4, 5, 6]


2. List of Indices for Specific Value

Get all indices of a specific value in a list.


lst = [10, 20, 10, 30, 10, 40]

indices = [i for i, x in enumerate(lst) if x == 10]

print(indices) 

[0, 2, 4]

3. Transpose a List of Lists (Matrix)

Transpose a matrix-like list (switch rows and columns).


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

transposed = list(map(list, zip(*matrix)))

print(transposed)  

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]



4. Rotate a List

Rotate the elements of a list by n positions.


def rotate(lst, n):

    return lst[-n:] + lst[:-n]


lst = [1, 2, 3, 4, 5]

rotated_lst = rotate(lst, 2)

print(rotated_lst) 

[4, 5, 1, 2, 3]

5. Find Duplicates in a List

Identify duplicate elements in a list.


from collections import Counter


lst = [1, 2, 2, 3, 4, 4, 4, 5]

duplicates = [item for item, count in Counter(lst).items() if count > 1]

print(duplicates)  

[2, 4]


6. Chunk a List

Split a list into evenly sized chunks.


def chunk(lst, n):

    for i in range(0, len(lst), n):

        yield lst[i:i + n]


lst = [1, 2, 3, 4, 5, 6, 7, 8]

chunks = list(chunk(lst, 3))

print(chunks)  

[[1, 2, 3], [4, 5, 6], [7, 8]]

7. Remove Consecutive Duplicates

Remove consecutive duplicates from a list, preserving order.


from itertools import groupby


lst = [1, 2, 2, 3, 3, 3, 4, 4, 5]

result = [key for key, _ in groupby(lst)]

print(result)  

[1, 2, 3, 4, 5]

Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (122) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (840) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses