Sunday, 4 August 2024

4 Python Mistakes That Make You Look Like a Beginner (And How to Avoid Them)



 1. Using Mutable Default Arguments

Mistake:


def add_item(item, items=[]):

    items.append(item)

    return items

Problem: Default mutable arguments, like lists or dictionaries, retain changes between function calls, which can lead to unexpected behavior.


Fix:


def add_item(item, items=None):

    if items is None:

        items = []

    items.append(item)

    return items


#clcoding.com



2. Not Using List Comprehensions

Mistake:


result = []

for i in range(10):

    result.append(i * 2)

Problem: This approach is verbose and less efficient than it could be.


Fix:


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


#clcoding.com

Explanation: List comprehensions are more Pythonic, concise, and often faster.



3. Misunderstanding Python’s Scope Rules (LEGB Rule)

Mistake:


x = 10


def example():

    print(x)

    x = 5

example()

Problem: This raises an UnboundLocalError because Python considers x inside example() as a local variable due to the assignment.


Fix:


x = 10


def example():

    global x

    print(x)

    x = 5

example()

#clcoding.com



4. Using print() for Debugging Instead of Proper Debugging Tools

Mistake:


def calculate(x):

    print(f"Debug: x = {x}")

    return x * 2


result = calculate(5)

Problem: Relying on print() statements for debugging can clutter code and is less efficient.


Fix:


def calculate(x):

    return x * 2


result = calculate(5)


# Use a debugger for inspection

import pdb; pdb.set_trace()


#clcoding.com

 

Guidelines for Writing Clean and Maintainable Python Functions

 

1. Simplicity and Clarity

Keep It Simple: Avoid unnecessary complexity. Each function should do one thing and do it well.


Descriptive Naming: Use clear, descriptive names for functions and variables. Avoid abbreviations unless they are widely understood.


Type Annotations: Use type hints to clarify what types of arguments a function expects and what it returns.


def calculate_area(radius: float) -> float:

    return 3.14 * radius * radius


#clcoding.com


2. Avoid Hardcoding

Use Constants: Define constants for values that shouldn't change. Avoid magic numbers.


Parameterization: Make functions flexible by passing parameters instead of hardcoding values. python


PI = 3.14159


def calculate_circumference(radius: float, pi: 

                            float = PI) -> float:

    return 2 * pi * radius


#clcoding.com


3. Readability

Docstrings: Include a docstring that explains what the function does, its parameters, and its return value.


Consistent Indentation: Stick to 4 spaces per indentation level.


Avoid Long Lines: Break lines at 79 characters where possible.


def calculate_bmi(weight: float, height: float) -> float:

    """

    Calculate the Body Mass Index (BMI).


    :param weight: Weight in kilograms.

    :param height: Height in meters.

    :return: BMI value.

    """

    return weight / (height ** 2)


#clcoding.com


4. Testing and Error Handling

Input Validation: Check for invalid inputs and handle them gracefully.


Unit Tests: Write tests for each function. Ensure edge cases are covered.


def divide_numbers(numerator: float, denominator: float) -> float:

    if denominator == 0:

        raise ValueError("Denominator cannot be zero.")

    return numerator / denominator


#clcoding.com


5. Performance

Efficiency: Avoid unnecessary computations. Optimize for performance if the function will be called frequently or handle large data sets.


Avoid Global State: Don’t rely on or modify global variables


def is_prime(n: int) -> bool:

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True


#clcoding.com


6. DRY Principle

Don’t Repeat Yourself: Reuse code by abstracting common functionality into separate functions or modules.


def get_positive_input(prompt: str) -> float:

    value = float(input(prompt))

    if value <= 0:

        raise ValueError("Input must be a +ve number.")

    return value


#clcoding.com

Saturday, 3 August 2024

Happy Friendship Day using Python

 



from rich.console import Console

from rich.text import Text

console = Console()

# Create the message and color mapping

text = "Happy Friendship Day!"

colors = [

    "red", "yellow", "green", "cyan", "blue", "white", "magenta",

    "red", "yellow", "green", "cyan", "blue", "magenta", "red",

    "yellow", "green", "white", "cyan", "blue", "magenta", "red"

]

# Generate the colorful message

message = Text()

[message.append(char, style=color) for char,color in zip(text, colors)]

console.print(message)

#clcoding.com

Happy Friendship Day!



Happy Friendship Day using Python

import pyfiglet

from termcolor import colored

text = "Happy Friendship Day!"

fonts = ["slant"]

for i, word in enumerate(text.split()):

    font = pyfiglet.Figlet(font=fonts[i % len(fonts)])

    color = ["red", "green", "yellow", "blue", "magenta"][i % 5]

    ascii_art = font.renderText(word)

    print(colored(ascii_art, color))


#clcoding.com

    __  __                       

   / / / /___ _____  ____  __  __

  / /_/ / __ `/ __ \/ __ \/ / / /

 / __  / /_/ / /_/ / /_/ / /_/ / 

/_/ /_/\__,_/ .___/ .___/\__, /  

           /_/   /_/    /____/   


    ______     _                __     __    _     

   / ____/____(_)__  ____  ____/ /____/ /_  (_)___ 

  / /_  / ___/ / _ \/ __ \/ __  / ___/ __ \/ / __ \

 / __/ / /  / /  __/ / / / /_/ (__  ) / / / / /_/ /

/_/   /_/  /_/\___/_/ /_/\__,_/____/_/ /_/_/ .___/ 

                                          /_/      


    ____              __

   / __ \____ ___  __/ /

  / / / / __ `/ / / / / 

 / /_/ / /_/ / /_/ /_/  

/_____/\__,_/\__, (_)   

            /____/      


Happy Friendship Day using Python

print('\n'.join

 ([''.join

   ([('Friendship'[(x-y)%8 ]

     if((x*0.05)**2+(y*0.1)**2-1)

      **3-(x*0.05)**2*(y*0.1)

       **3<=0 else' ')

        for x in range(-30,30)])

         for y in range(15,-15,-1)]))

print("Happy Friendship Day !!")

#clcoding.com

                                                            

                                                            

                                                            

                shFriends           iendshFri               

            endshFriendshFrie   hFriendshFriendsh           

          iendshFriendshFriendshFriendshFriendshFri         

         iendshFriendshFriendshFriendshFriendshFrien        

        iendshFriendshFriendshFriendshFriendshFriends       

        endshFriendshFriendshFriendshFriendshFriendsh       

        ndshFriendshFriendshFriendshFriendshFriendshF       

        dshFriendshFriendshFriendshFriendshFriendshFr       

        shFriendshFriendshFriendshFriendshFriendshFri       

        hFriendshFriendshFriendshFriendshFriendshFrie       

         riendshFriendshFriendshFriendshFriendshFrie        

          endshFriendshFriendshFriendshFriendshFrie         

          ndshFriendshFriendshFriendshFriendshFrien         

            hFriendshFriendshFriendshFriendshFrie           

             riendshFriendshFriendshFriendshFrie            

              endshFriendshFriendshFriendshFrie             

                shFriendshFriendshFriendshFri               

                  riendshFriendshFriendshFr                 

                    ndshFriendshFriendshF                   

                       FriendshFriends                      

                          ndshFrien                         

                             Fri                            

                              i                             

                                                            

                                                            

                                                            

                                                            

Happy Friendship Day !!


Python Coding challenge - Day 239 | What is the output of the following Python Code?

 

cl1 = "hello"

cl1_unicode = "hell\u00f6"

print(cl1 != cl1_unicode)

In Python, the comparison cl1 != cl1_unicode checks whether the two strings cl1 and cl1_unicode are different.


Here's the breakdown:

cl1 = "hello": This string contains the characters "h", "e", "l", "l", "o".

cl1_unicode = "hell\u00f6": This string contains the characters "h", "e", "l", "l", followed by the Unicode character \u00f6, which represents "ö".

When comparing cl1 and cl1_unicode:

"hello" is different from "hellö" because the last character in cl1_unicode ("ö") is different from the last character in cl1 ("o").

So, cl1 != cl1_unicode evaluates to True because the strings are not identical.

The print statement outputs True, indicating the strings are not equal.


7 Things I Should’ve Learnt Much Earlier For Python Functions

 

Closures

What: Functions that capture the local state of the environment in which they were created.


Why: Useful for creating function factories or decorators.


def outer(x):

    def inner(y):

        return x + y

    return inner


add_five = outer(5)

print(add_five(10))  

#clcoding.com

Function Annotations

What: Provides a way to attach metadata to function arguments and return values.


Why: Helps in providing hints about the expected data types, which improves code readability.


def add(a: int, b: int) -> int:

    return a + b


print(add(2, 3))  


#clcoding.com

Returning Multiple Values

What: Python allows functions to return multiple values as a tuple.


Why: Enables you to return complex data without creating a class or data structure.


def get_name_age():

    name = "clcoding"

    age = 30

    return name, age


name, age = get_name_age()

print(name, age)  

#clcoding.com

clcoding 30

Docstrings

What: Strings that describe what a function does, placed as the first line within the function body.


Why: Helps in documenting your code, making it more understandable.


def add(a, b):

    """Returns the sum of two numbers."""

    return a + b


print(add.__doc__)  


#clcoding.com

Returns the sum of two numbers.

Lambda Functions

What: Small, anonymous functions defined using lambda.


Why: Useful for short functions that are used once or passed as arguments to higher-order functions.


double = lambda x: x * 2

print(double(5))  


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

squared = list(map(lambda x: x**2, items))

print(squared)  


#clcoding.com

10

[1, 4, 9, 16, 25]

***args and kwargs

What: args and *kwargs allow functions to accept an arbitrary number of positional and keyword arguments, respectively.


Why: Useful when you don’t know in advance how many arguments will be passed.


def print_args(*args):

    for arg in args:

        print(arg)


print_args(1, 2, 3)  


def print_kwargs(**kwargs):

    for key, value in kwargs.items():

        print(f"{key}: {value}")


print_kwargs(name="clcoding", age=30)

#clcoding.com

1

2

3

name: clcoding

age: 30

Default Arguments

What: Allows you to set default values for function parameters.


Why: Makes your functions more flexible and easier to use.


def greet(name="Guest"):

    print(f"Hello, {name}!")


greet()             

greet("clcoding")   


#clcoding.com

Hello, Guest!

Hello, clcoding!

Wednesday, 31 July 2024

Password authentication process using Python

 

Password authentication process using Python

import hashlib, os


def hash_psd(psd: str) -> str:

    salt = os.urandom(16)

    hashed_psd = hashlib.pbkdf2_hmac('sha256',

                                     psd.encode(), salt, 100000)   

    return salt.hex() + hashed_psd.hex()


def verify_psd(stored_psd: str, provided_psd: str) -> bool:    

    salt = bytes.fromhex(stored_psd[:32])

    stored_hash = stored_psd[32:]

    hashed_psd = hashlib.pbkdf2_hmac('sha256',

                                     provided_psd.encode(),salt,100000)

    return hashed_psd.hex() == stored_hash


if __name__ == "__main__":

    psd_to_store = input("Enter a Password: ")

    stored_psd = hash_psd(psd_to_store)

    print(f'Stored Password: {stored_psd}')


    psd_attempt = 'clcoding'

    is_valid = verify_psd(stored_psd, psd_attempt)

    print(f'Password is valid: {is_valid}')


#clcoding.com

Stored Password: ec87cb3f526a3dc27e5a67fe7878f850a6b24c71c2941edc5bbe2c3500afc164cebb1ec8bbbc6a2260faa4825307600e

Password is valid: True

 

 

Saturday, 27 July 2024

Olympic data-based analysis using Python



 import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

df = pd.read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-07-27/olympics.csv')

print(df.head())

medal_counts = df.groupby('team')['medal'].count().reset_index()

medal_counts = medal_counts.sort_values(by='medal', ascending=False).head(10)

print(medal_counts)

top_countries = medal_counts['team'].head(5)

df_top_countries = df[df['team'].isin(top_countries)]

medals_by_year = df_top_countries.groupby(['year', 'team'])['medal'].count().reset_index()

# Plot: Medals Over Time for Top 5 Countries

plt.figure(figsize=(14, 8))

sns.lineplot(data=medals_by_year, x='year', y='medal', hue='team')

plt.title('Medals Over Time for Top 5 Countries')

plt.xlabel('Year')

plt.ylabel('Number of Medals')

plt.legend(title='Country')

plt.show()

# What is the distribution of medals by sport?

medals_by_sport = df.groupby('sport')['medal'].count().reset_index()

medals_by_sport = medals_by_sport.sort_values(by='medal', ascending=False).head(10)

# Plot: Top 10 Sports by Number of Medals

plt.figure(figsize=(14, 8))

sns.barplot(data=medals_by_sport, x='medal', y='sport', palette='viridis')

plt.title('Top 10 Sports by Number of Medals')

plt.xlabel('Number of Medals')

plt.ylabel('Sport')

plt.show()


#clcoding.com 

Thursday, 25 July 2024

Olympics Logo using Python

 

import turtle


def draw_ring(color, x, y):

    turtle.penup()

    turtle.color(color)

    turtle.goto(x, y)

    turtle.pendown()

    turtle.circle(50)


turtle.speed(5)

turtle.width(5)

draw_ring("blue", -120, 0)

draw_ring("black", 0, 0)

draw_ring("red", 120, 0)

draw_ring("yellow", -60, -50)

draw_ring("green", 60, -50)

turtle.hideturtle()

turtle.done()

#clcoding.com

Python Coding challenge - Day 238 | What is the output of the following Python Code?

 

In Python, dictionaries are compared based on their keys and corresponding values. When you use the != operator to compare two dictionaries, it checks if there is any difference between them.

Here’s the explanation for the given code:

dict1 = {"a": 1, "b": 2}

dict2 = {"a": 1, "b": 3}

print(dict1 != dict2)

Dictionary Creation:

dict1 is created with keys "a" and "b" having values 1 and 2, respectively.

dict2 is created with keys "a" and "b" having values 1 and 3, respectively.

Comparison:

The comparison dict1 != dict2 checks if dict1 is not equal to dict2.

Python compares each key-value pair in dict1 with the corresponding key-value pair in dict2.

Key-Value Comparison:

Both dictionaries have the same keys: "a" and "b".

For key "a", both dictionaries have the value 1. So, these are equal.

For key "b", dict1 has the value 2 and dict2 has the value 3. These are not equal.

Since there is at least one key-value pair that differs ("b": 2 in dict1 vs. "b": 3 in dict2), the dictionaries are considered not equal.

Result:

The expression dict1 != dict2 evaluates to True.

Therefore, the output of print(dict1 != dict2) will be True, indicating that dict1 is not equal to dict2.

Sunday, 21 July 2024

Computer Science: Programming with a Purpose

 


Are you eager to dive into the world of Java programming and software engineering? Coursera offers an excellent course titled Java Programming and Software Engineering Fundamentals that provides a comprehensive foundation in these essential skills. Whether you're a beginner or looking to refresh your knowledge, this course is a great starting point.

Why Learn Java?

Java is one of the most widely-used programming languages in the world. Its versatility, robustness, and cross-platform capabilities make it a favorite among developers. Java powers a multitude of applications, from mobile apps to large-scale enterprise systems. By learning Java, you open doors to a vast array of career opportunities in software development, web development, data science, and more.

Course Overview

The "Java Programming and Software Engineering Fundamentals" course is designed to take you from zero to proficient in Java programming. Here's a breakdown of what you can expect:

  1. Introduction to Java Programming

    • Understand the basics of Java syntax and structure.
    • Learn to write simple Java programs.
    • Get acquainted with essential programming concepts such as variables, data types, and control structures.
  2. Object-Oriented Programming (OOP)

    • Dive into the principles of OOP, a core paradigm in Java.
    • Master concepts like classes, objects, inheritance, and polymorphism.
    • Develop skills to design and implement complex software systems.
  3. Data Structures and Algorithms

    • Learn about essential data structures like arrays, lists, stacks, and queues.
    • Explore algorithms for sorting and searching.
    • Understand how to optimize your code for efficiency.
  4. Software Engineering Fundamentals

    • Gain insights into the software development lifecycle.
    • Learn about version control systems like Git.
    • Understand the importance of testing and debugging.
  5. Practical Projects

    • Apply your knowledge through hands-on projects.
    • Build real-world applications that solidify your understanding of Java and software engineering principles.

What Makes This Course Unique?

  • Expert Instructors: The course is taught by experienced instructors from top universities and industry experts. Their guidance ensures you receive high-quality education.
  • Flexible Learning: Coursera offers a flexible learning schedule, allowing you to learn at your own pace. This is ideal for balancing your studies with other commitments.
  • Interactive Learning Experience: The course includes quizzes, assignments, and projects that provide an interactive and engaging learning experience.
  • Certification: Upon completion, you'll receive a certificate that you can share with potential employers, showcasing your skills and dedication.

Who Should Enroll?

  • Beginners: If you're new to programming, this course will help you build a solid foundation in Java.
  • Aspiring Developers: Those looking to start a career in software development will find this course invaluable.
  • Professionals: If you're already working in the tech industry and want to enhance your skills or transition to a Java-centric role, this course is perfect for you.

Final Thoughts

The "Java Programming and Software Engineering Fundamentals" course on Coursera is an excellent opportunity to gain a deep understanding of Java and software engineering. With its comprehensive curriculum, expert instructors, and flexible learning options, this course is a valuable resource for anyone looking to advance their programming skills.

Ready to embark on your Java programming journey? Enroll today and take the first step towards becoming a proficient Java developer!

Enroll Now

Python Coding challenge - Day 237 | What is the output of the following Python Code?

 

This Python code defines a function and then calls it with specific arguments. Let's break it down step by step:

Function Definition:

def func(x, y):

    return x + y

def func(x, y):: This line defines a function named func that takes two parameters, x and y.

return x + y: This line specifies that the function will return the sum of x and y.

Function Call:

print(func(y=2, x=3))

func(y=2, x=3): This calls the func function with x set to 3 and y set to 2. The order of the arguments doesn't matter here because they are passed as keyword arguments.

The function func adds x and y, so 3 + 2 results in 5.

print(5): The print function then outputs the result, which is 5.

Putting it all together, the code defines a function that adds two numbers, then calls the function with x as 3 and y as 2, and prints the result, which is 5.

Saturday, 20 July 2024

Python Coding challenge - Day 236 | What is the output of the following Python Code?

 

The code provided consists of two parts: defining a dictionary and using the fromkeys method to create a new dictionary. Let's break it down:

Defining a Dictionary:

d = {'a': 1, 'b': 2, 'c': 3}

Here, d is a dictionary with three key-value pairs:

'a' maps to 1

'b' maps to 2

'c' maps to 3

Using dict.fromkeys:

print(dict.fromkeys(d, 0))

The dict.fromkeys method is used to create a new dictionary from the keys of an existing iterable (in this case, the dictionary d). The method signature is:

dict.fromkeys(iterable, value)

iterable: An iterable containing keys.

value: The value to assign to each key in the new dictionary.

In this code, d is used as the iterable. When d is used as an iterable, it provides its keys ('a', 'b', and 'c'). The second argument is 0, which means all keys in the new dictionary will have the value 0.


Therefore, the new dictionary created by dict.fromkeys(d, 0) will have the same keys as d but with all values set to 0:

{'a': 0, 'b': 0, 'c': 0}

Output:

The print statement will output:

{'a': 0, 'b': 0, 'c': 0}

In summary, the code defines a dictionary d and then creates a new dictionary with the same keys as d but with all values set to 0, and prints this new dictionary.

Friday, 19 July 2024

Why you should use PEP 8 guidelines ?

 

7. Error Prevention

Reason: PEP 8 includes guidelines that help prevent common errors, such as mixing tabs and spaces for indentation.


Without PEP 8:


def calculate_sum(a, b):

  return a + b

    print("Sum calculated")

  Cell In[16], line 3

    print("Sum calculated")

    ^

IndentationError: unexpected indent

With PEP 8:


def calculate_sum(a, b):

    return a + b


print("Sum calculated")

Sum calculated

6. Community Standard

Reason: PEP 8 is the de facto standard for Python code. Following it ensures your code aligns with what other Python developers expect, making it easier for others to read and contribute to your projects.


Without PEP 8:


class Person: 

  def __init__(self,name,age):

    self.name=name

    self.age=age

  def getDetails(self):

    return self.name + " is " + str(self.age)

With PEP 8:


class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age


    def get_details(self):

        return f"{self.name} is {self.age}"

5. Professionalism

Reason: Following PEP 8 shows that you care about writing high-quality code. It demonstrates professionalism and attention to detail, which are valuable traits in any developer.


Without PEP 8:


def square(x):return x*x

With PEP 8:


def square(x):

    return x * x

4. Maintainability

Reason: Code that adheres to a standard style is easier to maintain and update. PEP 8’s guidelines help you write code that is more maintainable in the long run.


Without PEP 8:


def processData(data): 

  result = data["name"].upper() + " is " + str(data["age"]) + " years old"

  return result


    

With PEP 8:


def process_data(data):

    result = f"{data['name'].upper()} is {data['age']} years old"

    return result


#clcoding.com

3. Collaboration

Reason: When everyone on a team follows the same style guide, it’s easier for team members to read and understand each other’s code, making collaboration smoother.


Without PEP 8:


def fetchData(): 

  # fetch data from API

  data = {"name":"John","age":30}

  return data

With PEP 8:


def fetch_data():

    # Fetch data from API

    data = {"name": "John", "age": 30}

    return data

2. Readability

Reason: Readable code is easier to understand and debug. PEP 8 encourages practices that make your code more readable.


Without PEP 8:


def add(a,b):return a+b

With PEP 8:


def add(a, b):

    return a + b

1. Consistency

Reason: Consistent code is easier to read and understand. PEP 8 provides a standard style guide that promotes consistency across different projects and among different developers.


Without PEP 8:


def my_function():print("Hello"); print("World")

my_function()

Hello

World

With PEP 8:


def my_function():

    print("Hello")

    print("World")


my_function()

Hello

World

Python Coding challenge - Day 235 | What is the output of the following Python Code?

 

In Python, memoryview is a built-in class that allows you to access the memory of an object without copying it. This can be useful for performance reasons, especially when dealing with large data sets or when you want to manipulate data in place.

Here's a breakdown of the code snippet you provided:

x = memoryview(b'clcoding')

print(type(x))

Creating a memoryview object:

b'clcoding' is a bytes object. The b prefix indicates that this is a bytes literal, which is a sequence of bytes.

memoryview(b'clcoding') creates a memoryview object that exposes the memory of the bytes object b'clcoding' without copying it.

Printing the type of the memoryview object:

print(type(x)) prints the type of the object x.

When you run this code, you will get the following output:

<class 'memoryview'>

This output indicates that x is an instance of the memoryview class.

Why use memoryview?

Efficiency: It allows you to access and manipulate data without copying it, which can save memory and improve performance.

Slicing and indexing: You can use memoryview to slice and index data structures such as bytes, bytearray, and other objects that support the buffer protocol.

Interoperability: It can be useful when working with binary data and interfacing with C/C++ extensions or other low-level APIs.

Example Usage

Here's a simple example to demonstrate the usage of memoryview:

data = b'clcoding'

mv = memoryview(data)

# Accessing elements

print(mv[0])  # Output: 99 (ASCII value of 'c')

# Slicing

print(mv[1:4])  # Output: <memory at 0x...> (a slice of the memoryview)

# Converting back to bytes

print(mv.tobytes())  # Output: b'clcoding'

In this example:

mv[0] accesses the first byte, which is 99, the ASCII value of 'c'.

mv[1:4] creates a new memoryview object that is a slice of the original memoryview.

mv.tobytes() converts the memoryview back to a bytes object.

Using memoryview is particularly beneficial when you need to work with large data structures efficiently.

Monday, 15 July 2024

Practical Uses of continue and break Statements

 

Example 5: Summing Non-Negative Numbers

Using continue to skip negative numbers and sum the non-negative ones.


numbers = [10, -5, 20, -10, 30]

total = 0


for num in numbers:

    if num < 0:

        continue  # Skip negative numbers

    total += num


print(f"Total sum of non-negative numbers is: {total}")


#clcoding.com

Total sum of non-negative numbers is: 60

Example 4: Finding the First Negative Number

Using break to find and print the first negative number in a list.


numbers = [10, 20, -5, 30, -10]


for num in numbers:

    if num < 0:

        print(f"First negative number is: {num}")

        break  


#clcoding.com

First negative number is: -5

Example 3: Skipping a Specific Number and Stopping at Another

Combining continue and break to skip the number 3 and stop at 7.


for i in range(1, 11):

    if i == 3:

        continue  # Skip the number 3

    if i == 7:

        break  # Stop the loop when i is 7

    print(i)


#clcoding.com

1

2

4

5

6

Example 2: Stopping at a Specific Number

Using break to stop the loop when encountering the number 5.


for i in range(1, 11):

    if i == 5:

        break 

    print(i)


#clcoding.com

1

2

3

4

Example 1: Skipping Even Numbers

Using continue to skip even numbers in a loop.


for i in range(1, 11):

    if i % 2 == 0:

        continue  

    print(i)


#clcoding.com

1

3

5

7

9

Sunday, 14 July 2024

Python Coding challenge - Day 234 | What is the output of the following Python Code?

 

Class Definition

Class Vehicle:

class Vehicle:

    def __init__(self, color):

        self.color = color

Class Declaration: class Vehicle: defines a class named Vehicle.

Constructor: def __init__(self, color): defines the constructor method (__init__). It initializes a new instance of Vehicle.

Instance Variable: self.color = color assigns the value of the parameter color to the instance variable self.color.

Class Car (Inheritance):

class Car(Vehicle):

    def __init__(self, color, model):

        super().__init__(color)

        self.model = model

Class Declaration with Inheritance: class Car(Vehicle): defines a class named Car that inherits from the Vehicle class.

Constructor: def __init__(self, color, model): defines the constructor method (__init__). It initializes a new instance of Car.

Calling Superclass Constructor: super().__init__(color) calls the constructor of the superclass Vehicle to initialize the color attribute.

Instance Variable: self.model = model assigns the value of the parameter model to the instance variable self.model.

Object Instantiation

Creating an Instance:

my_car = Car("Red", "Toyota")

This line creates an instance of the Car class with color set to "Red" and model set to "Toyota". The constructor of the Vehicle class is also called to initialize the color attribute.

Accessing Attributes

Printing the Model:

print(my_car.model)

This line prints the model attribute of the my_car object, which is "Toyota".

Complete Code

Here is the complete code for clarity:

class Vehicle:

    def __init__(self, color):

        self.color = color

class Car(Vehicle):

    def __init__(self, color, model):

        super().__init__(color)

        self.model = model

my_car = Car("Red", "Toyota")

print(my_car.model)

Output

The output of the code is: Toyota

Explanation Summary

Vehicle Class: Defines a vehicle with a color.

Car Class: Inherits from Vehicle and adds a model attribute.

Object Creation: An instance of Car is created with color "Red" and model "Toyota".

Attribute Access: The model attribute of my_car is printed, displaying "Toyota".

Saturday, 13 July 2024

Different Line graph plot using Python

 

5. Interactive Line Graph using Plotly

import plotly.express as px


# Sample data

data = {

    'x': [1, 2, 3, 4, 5],

    'y': [2, 3, 5, 7, 11]

}


# Creating an interactive line plot

fig = px.line(data, x='x', y='y', 

              title='Interactive Line Graph using Plotly', markers=True)

fig.show()


4. Line Graph using Seaborn

import seaborn as sns

import matplotlib.pyplot as plt


# Sample data

data = {

    'x': [1, 2, 3, 4, 5],

    'y': [2, 3, 5, 7, 11]

}


# Creating a Seaborn line plot

sns.lineplot(x='x', y='y', data=data, marker='o')

plt.title('Line Graph using Seaborn')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.grid(True)

plt.show()

3. Line Graph with Error Bars using Matplotlib

import matplotlib.pyplot as plt

import numpy as np


# Sample data

x = np.array([1, 2, 3, 4, 5])

y = np.array([2, 3, 5, 7, 11])

yerr = np.array([0.5, 0.4, 0.3, 0.2, 0.1])


# Plotting the line graph with error bars

plt.errorbar(x, y, yerr=yerr, fmt='-o', capsize=5)

plt.title('Line Graph with Error Bars')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.grid(True)

plt.show()

2. Multiple Line Graphs using Matplotlib

import matplotlib.pyplot as plt


# Sample data

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

y1 = [2, 3, 5, 7, 11]

y2 = [1, 4, 6, 8, 10]


# Plotting multiple line graphs

plt.plot(x, y1, label='Line 1', marker='o')

plt.plot(x, y2, label='Line 2', marker='s')

plt.title('Multiple Line Graphs')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.legend()

plt.grid(True)

plt.show()

1. Basic Line Graph using Matplotlib

import matplotlib.pyplot as plt


# Sample data

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

y = [2, 3, 5, 7, 11]


# Plotting the line graph

plt.plot(x, y, marker='o')

plt.title('Basic Line Graph')

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.grid(True)

plt.show()

5 Practical Examples to Master Python Decorators

 

5. Decorator for Timing
A decorator to measure the execution time of a function.

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} executed in {end_time - start_time} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(2)
    return "Finished"

print(slow_function())

#clcoding.com
slow_function executed in 2.001049518585205 seconds
Finished
4. Decorator for Caching
A decorator to cache the results of expensive function calls.

def cache(func):
    cached_results = {}
    def wrapper(*args):
        if args in cached_results:
            return cached_results[args]
        result = func(*args)
        cached_results[args] = result
        return result
    return wrapper

@cache
def slow_function(x):
    print(f"Computing {x}...")
    return x * x

print(slow_function(4))
print(slow_function(4))
print(slow_function(5))

#clcoding.com
Computing 4...
16
16
Computing 5...
25
3. Decorator for Logging
A decorator to log function calls and their arguments.

def logger(func):
    def wrapper(*args, **kwargs):
        print(f"Function {func.__name__} called with args: {args} and kwargs: {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add(a, b):
    return a + b

add(3, 5)

#clcoding.com
Function add called with args: (3, 5) and kwargs: {}
Function add returned 8
8
2. Decorator with Arguments
A decorator that accepts arguments to customize its behavior.

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")
greet("Clcoding")

#clcoding.com
Hello, Clcoding!
Hello, Clcoding!
Hello, Clcoding!
1. Basic Decorator
A simple example to understand the basic structure and functionality of decorators.

def simple_decorator(func):
    def wrapper():
        print("Before the function runs")
        func()
        print("After the function runs")
    return wrapper

@simple_decorator
def say_hello():
    print("Hello!")

say_hello()

#clcoding.com
Before the function runs
Hello!
After the function runs

Python Coding challenge - Day 233 | What is the output of the following Python Code?



 Let's break down the code and explain what each part does:

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

my_list[1:3] = []

print(my_list)

Step-by-Step Explanation

Create a List:

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

This line initializes a list named my_list with the elements [1, 2, 3, 4, 5].

Slice Assignment:

my_list[1:3] = []

my_list[1:3] is a slice of the list from index 1 to index 3, but not including index 3. In this case, my_list[1:3] refers to the sublist [2, 3].

The assignment my_list[1:3] = [] replaces the slice [2, 3] with an empty list [], effectively removing the elements 2 and 3 from the list.

Print the Modified List:

print(my_list)

This line prints the modified list.

After the slice assignment, my_list is modified to remove the elements at indices 1 and 2 (the elements 2 and 3). The resulting list is:

[1, 4, 5]

Visual Breakdown

Let's visualize the process:

Initial list: [1, 2, 3, 4, 5]

Slice my_list[1:3] refers to [2, 3]

Assigning [] to the slice removes [2, 3]

Resulting list: [1, 4, 5]

Full Code with Output

Here is the complete code along with its output:

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

my_list[1:3] = []

print(my_list)  # Output: [1, 4, 5]

The output is [1, 4, 5], as explained.

Popular Posts

Categories

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

Followers

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