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

Sunday 30 April 2023

What does the “yield” keyword do in python?

 In Python, the yield keyword is used to create a generator function. When a function includes a yield statement, it becomes a generator function, which returns an iterator object that can be iterated over with a loop.


The yield statement suspends the function's execution and sends a value back to the caller, but unlike return, the function state is saved, and the function can be resumed later from where it left off.

Here's an example to demonstrate the use of yield:

def countdown(num):

    while num > 0:

        yield num

        num -= 1


This generator function countdown() will return an iterator that will produce a sequence of numbers from num down to 1. We can use a for loop to iterate over the sequence:

for i in countdown(5):
    print(i)

5
4
3
2
1

Each time the yield statement is reached, the function's state is saved, and the value of num is sent back to the caller. The next time the generator is called, execution continues from where it left off, and num is decremented until it reaches zero.


Saturday 29 April 2023

Generator Vs List in Python

 In Python, there are two main ways to create sequences of values: using a generator or a list. While both have their uses, they have different performance characteristics and memory usage, so it's important to choose the right one for your specific use case.


A generator is a type of iterable, like a list or a tuple, but unlike a list, a generator does not store all the values in memory at once. Instead, it generates the values on-the-fly as they are requested, using a special type of function called a generator function. Generator functions use the yield keyword to return a value, but unlike a regular function that returns a value and then exits, a generator function can be resumed from where it left off, so it can continue generating values until it is done. Because generators don't store all their values in memory, they can be more memory-efficient than lists for large data sets, and can be faster for certain operations.


Here's an example of a simple generator function that generates a sequence of numbers:

def generate_numbers(n):

    for i in range(n):

        yield i

To use this generator, you would typically use it in a loop or with a function like next() to generate values one at a time:


numbers = generate_numbers(5)

print(next(numbers)) # Output: 0

print(next(numbers)) # Output: 1

print(next(numbers)) # Output: 2

print(next(numbers)) # Output: 3

print(next(numbers)) # Output: 4

A list, on the other hand, is a type of sequence that stores all its values in memory at once. Lists can be created using square brackets [] or the list() function. Lists are very versatile and can be modified, sliced, and indexed in various ways. However, because they store all their values in memory at once, they can be memory-intensive for large data sets.


Here's an example of creating a list of numbers:

numbers = [0, 1, 2, 3, 4]

To iterate over a list, you can use a for loop or various other functions and methods:


for number in numbers:

    print(number)

Both generators and lists have their advantages and disadvantages, so choosing the right one depends on the specific use case. If you have a large data set or you only need to generate values one at a time, a generator might be more memory-efficient and faster. If you need to modify the sequence, access its values multiple times, or if the data set is small enough to fit in memory, a list might be more appropriate.

7 Cool Ways To Use F-Strings In Python


 

1. Align strings with f-strings:

You can use f-strings to align strings to the left, right, or center of a field. Here's an example:

name = "Alice"

age = 30

print(f"|{name:<10}|{age:^5}|")  # Output: |Alice     | 30  |

In this example, the < character aligns the name variable to the left of a 10-character field, and the ^ character centers the age variable in a 5-character field.


2. Use f-strings with dictionary variables:

You can use f-strings with dictionary variables to create dynamic strings. Here's an example:

person = {"name": "Alice", "age": 30}

print(f"My name is {person['name']} and I'm {person['age']} years old.")  # Output: My name is Alice and I'm 30 years old.

In this example, the person variable is a dictionary with keys "name" and "age". The f-string uses the values of these keys to create a dynamic string.


3. Use f-strings to format binary and hexadecimal numbers:

You can use f-strings to format binary and hexadecimal numbers. Here's an example:

x = 42

print(f"x = {x:b}")  # Output: x = 101010

print(f"x = {x:x}")  # Output: x = 2a

In this example, the :b format specifier formats the x variable as a binary number, and the :x format specifier formats the x variable as a hexadecimal number.


4. Use f-strings to format dates and times:

You can use f-strings to format dates and times. Here's an example:

import datetime

now = datetime.datetime.now()

print(f"Today is {now:%B %d, %Y}")  # Output: Today is April 29, 2023

In this example, the %B %d, %Y format specifier formats the now variable as a string in the format Month Day, Year.


5. Use f-strings to format currency values:

You can use f-strings to format currency values. Here's an example:

salary = 50000

print(f"My salary is ${salary:,}")  # Output: My salary is $50,000

In this example, the , character formats the salary variable as a string with comma separators.


6. Use f-strings with formatted strings:

You can use f-strings with formatted strings to create complex strings. Here's an example:

name = "Alice"

age = 30

message = f"My name is {name} and I'm {age} years old."

print(f"Message length: {len(message):<10}, Message: '{message:^20}'")

# Output: Message length: 32        , Message: 'My name is Alice and I'm 30 years old.'

In this example, the f-string uses another f-string to create a complex string that includes the length of the message variable and the message itself.


7.Use f-strings to format scientific notation:

You can use f-strings to format numbers in scientific notation. Here's an example:

x = 1234567890.123456789

print(f"x = {x:e}")  # Output: x = 1.234568e+09

Return VS Yield in Python

 



In Python, return and yield are two ways to send a value back from a function or generator to its caller, but they work in different ways.


return is a statement that immediately terminates the execution of a function and returns a value to the caller. When the function is called again, it starts executing from the beginning.


Here's an example:

def square(x):

    return x * x


result = square(5)

print(result)  # Output: 25


In this example, the square() function takes an argument x and returns its square using the return statement.

On the other hand, yield is a keyword that allows a function to return a generator object, which can be used to iterate over a sequence of values. When the function is called, it executes until it reaches a yield statement, which returns a value to the caller and suspends the function's execution. The next time the function is called, it continues executing from where it left off until it reaches another yield statement or the end of the function.

Here's an example:

def squares(n):
    for i in range(n):
        yield i * i

result = squares(5)
for square in result:
    print(square)  # Output: 0 1 4 9 16

In this example, the squares() function generates a sequence of squares using a for loop and the yield statement. The result variable holds a generator object, which is then iterated over using a for loop to print the squares.

In summary, return is used to immediately terminate a function and return a value to the caller, while yield is used to create a generator object that can be iterated over to return a sequence of values one at a time.

Sunday 23 April 2023

Saturday 22 April 2023

Object Oriented Programming in Python

 Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects," which can contain data and code to manipulate that data. Python is an object-oriented programming language that supports OOP concepts such as inheritance, encapsulation, and polymorphism. Here are some key concepts and syntax used in Python for OOP:

Class: A class is a blueprint or template for creating objects. It defines a set of attributes and methods that the objects of that class will have.

Syntax:

class ClassName:

    # class attributes

    attribute1 = value1

    attribute2 = value2


    # class methods

    def method1(self):

        # method code


    def method2(self):

        # method code

Object: An object is an instance of a class. It has its own set of attributes and methods that were defined in the class.
Syntax:
# create an object of class ClassName
object_name = ClassName()

Method: A method is a function that is defined inside a class and can be called on an object of that class.
Syntax:
# call method1 on object_name
object_name.method1()

Attribute: An attribute is a variable that is defined inside a class and can be accessed by objects of that class.
Syntax:
# access attribute1 of object_name
object_name.attribute1

Inheritance: Inheritance is a mechanism in which a new class is created from an existing class. The new class, called the subclass or derived class, inherits the attributes and methods of the existing class, called the superclass or base class.
Syntax:
# create a subclass of superclass
class SubclassName(SuperclassName):
    # subclass attributes
    attribute3 = value3

    # subclass methods
    def method3(self):
        # method code

Polymorphism: Polymorphism is the ability of objects of different classes to be used interchangeably. It allows the same method to be called on different objects, and the behavior of the method will depend on the object it is called on.
Syntax:
# create two objects of different classes
object1 = ClassName1()
object2 = ClassName2()

# call the same method on both objects
object1.method()
object2.method()

These are some of the key concepts and syntax used in Python for OOP. By using OOP concepts, you can write modular and reusable code that is easier to maintain and understand.

Sunday 26 March 2023

Top 5 examples of Python decorators:

 @staticmethod: This decorator is used to define a static method in a class. A static method is a method that can be called on the class itself rather than on an instance of the class. Here's an example:

class MyClass:

    @staticmethod

    def my_static_method():

        print("This is a static method")

@classmethod: This decorator is used to define a class method in a class. A class method is a method that takes the class itself as its first argument rather than an instance of the class. Here's an example:

class MyClass:

    class_var = "Hello"

    

    @classmethod

    def my_class_method(cls):

        print(cls.class_var)

@property: This decorator is used to define a method as a property of a class. Properties allow you to access and set the value of an attribute of an instance of the class without explicitly calling a getter or setter method. Here's an example:

class MyClass:

    def __init__(self):

        self._x = 0

        

    @property

    def x(self):

        return self._x

    

    @x.setter

    def x(self, value):

        if value < 0:

            raise ValueError("Value must be non-negative")

        self._x = value

@log_calls: This decorator can be used to log all calls to a function. Here's an example:

def log_calls(func):

    def wrapper(*args, **kwargs):

        print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")

        result = func(*args, **kwargs)

        print(f"Finished {func.__name__}")

        return result

    return wrapper


@log_calls

def my_function(x, y):

    return x + y

@cache: This decorator can be used to cache the results of a function so that the function doesn't need to be called again with the same arguments. Here's an example:

def cache(func):

    results = {}

    def wrapper(*args):

        if args in results:

            return results[args]

        result = func(*args)

        results[args] = result

        return result

    return wrapper


@cache

def fibonacci(n):

    if n < 2:

        return n

    return fibonacci(n-1) + fibonacci(n-2)


5 awesome hidden features in Python

 Walrus operator (:=): This operator allows you to assign and return a value in the same expression. It can be particularly useful in list comprehensions or other situations where you need to assign a value to a variable and use it in a subsequent expression. Here's an example:

if (n := len(my_list)) > 10:

    print(f"List is too long ({n} elements, expected <= 10)")


Extended Iterable Unpacking: This feature allows you to unpack an iterable into multiple variables, including a "catch-all" variable that gets assigned any remaining items in the iterable. Here's an example:

first, *middle, last = my_list

In this example, first is assigned the first item in my_list, last is assigned the last item, and middle is assigned all the items in between.


Underscore as a placeholder: In interactive Python sessions, you can use the underscore (_) as a shorthand for the result of the last expression. This can be useful if you need to reuse the result of a previous command. Here's an example:

>>> 3 * 4
12
>>> _ + 5
17

slots attribute: The __slots__ attribute allows you to define the attributes of a class and their data types in advance, which can make the class more memory-efficient. Here's an example:

class MyClass:
    __slots__ = ("x", "y")
    
    def __init__(self, x, y):
        self.x = x
        self.y = y

In this example, we are defining a class with two attributes (x and y) and using the __slots__ attribute to define them in advance.

Callable instances: In Python, instances of classes can be made callable by defining a __call__ method. This can be useful if you want to create objects that behave like functions. Here's an example:

class Adder:
    def __init__(self, n):
        self.n = n
        
    def __call__(self, x):
        return self.n + x
    
add_five = Adder(5)
result = add_five(10)
print(result)  # Output: 15


In this example, we are defining a class Adder that takes a number n and defines a __call__ method that adds n to its argument. We then create an instance of Adder with n=5 and use it like a function to add 5 to 10, resulting in 15.

Monday 2 January 2023

Wednesday 28 December 2022

Sunday 25 December 2022

Python Quiz | Day 35 | What is the output of following code ?

 


Complete Playlist : https://bit.ly/3GLnZPy

Solution: 

Answer: D. Explanation:

The list.pop method removes an element from the list, and returns the removed element.

When used without arguments, pop removes and returns the last element of the list.

When an argument index is specified, 

li.pop(index) removes the element li[index] from li, and returns the removed element.

When li.pop(1) is executed, li[1] is removed from li, and the removed value is returned.

Here li[1] is 3. Therefore, li is modified to [2,1], and the return value from li.pop(1) is 3



Sunday 2 October 2022

Lazy Operators 🥱 --- Python


Introduction

Python is a great language to learn, but it can be hard to pick up if you’ve never programmed before. A lot of the syntax and functions are pretty weird when compared to other languages like JavaScript, Ruby or Java. Luckily, Python has some helpful built-in functions that make it easier for beginners to get started learning programming. In this blog post we will take a look at some of these functions and how they can help us become more efficient programmers in our daily lives!

#Guess the output in this case?

The following Python code is an example of lazy operators. This section shows how to use them in your own programs, but we will first use the examples provided by the python documentation:

  • print(all([])) - returns all items from a list (or other iterable), without necessarily creating any copies. It's like calling len() on a list and then getting its length.

  • print(any([])) - returns true if at least one item in a list satisfies some condition . For example, if you want to know whether there are any numbers greater than 10 inside [10], then it would be easier just to test each number one by one rather than doing this whole loop thingy....

print(all([]))

You can use the all() function to print all of the elements in a list. For example, this will print all numbers in the range:

print(all([1, 2, 3]))

If you want to print only one element from the list, you can use an index:

print(all(1))

print(any([]))

print(any([]))

The first line of code is the same as above, but in Python it looks for a false element. The algorithm looks for the first occurrence of a true element and, if none were found, returns False. Since the sequence is empty, there are no elements that can be true so this runs through and prints False

Explanation :

The first thing that you need to know about lazy operators is that they are lazy. This means that when we use them, we can only get the result at a later time. Here's an example:

```python

print(all([]))

print(any([]))

```The first two lines print out all elements in their operands but do not return any values, because there are no true cases present in those expressions yet. If you were expecting a set or list of tuples as an answer from these expressions and wanted to see if an element existed before returning false, then it would work just fine with these operators -- but what if I told you there was another way?

"""Function all() is a little complicated,

"""Function all() is a little complicated, but you already know how it works.

It accepts one argument and returns a list containing the items in the reversed order. This can be useful for doing things like summing up numbers or sorting them by value. It's also useful for making sure that only unique values are present in your data structures (e.g., if you have an array of dictionaries and one of them contains duplicate keys).

The problem with this function is that it requires more memory than necessary because we don't need to keep track of what order our results will be returned in; they'll always be sorted automatically by Python when they come back from our function call! That means there's no reason not removing those extra elements from both sides before feeding them into any other operation such as filter().

since it represents the concept of vacuous truth.

Since it represents the concept of vacuous truth, the all() function returns True if all elements are true. The any() function returns True if any element is true.

Like with chained lazy logical operators,

If you're looking for the first non-false element, then all([]), like lazy operators, is a function that returns True when provided with any other value.

However, since there are no false elements in an empty sequence (and since Python doesn't have built-in logic to check for nulls), print(all([])) prints True:

print([])

the algorithm is to look for the first false element,

The algorithm is to look for the first false element and, if none were found, return True. If any element of the iterable is true, then return True.

The following code snippet demonstrates how this works in Python:

and if none were found then return True.

The if statement is one of the most useful features in Python. It allows you to check whether or not an element is true, and if none were found then return True.

The following code:

if x > 0 and y < 10:

yields this output: True

Since there are no false elements in an empty sequence, print(all([])) prints True.

Since there are no false elements in an empty sequence, print(all([])) prints True.

However, there is another way to achieve this effect: we can simply use the bool() function! The boolean value of x is true if x is equal to true or false (or any other value that Python determines as being truthy). Using this check for equality will return a boolean result when called on a list containing only one element.

In function any(), it will return True if any element of the iterable is true.

The function any() is the opposite of all(). It will return True if any element in the iterable is true.

If we pass an empty list, no elements will be returned by this function.

For example:

```python print(["Hello", "World"]) # [1] print([]).any() # True```

Logical operators in Python are lazy! The algorithm looks for the first

The first thing that you need to know about lazy operators in Python is that they are the ones that evaluate only when necessary.

The example above shows how logical operators work: the first one to be evaluated is any(), which evaluates to True and then all() evaluates to True, since there are no false elements in the list. If we had another list with three elements and processed it like this (using ** operator), we would have got an empty list back! You might have noticed another thing here—that's right, both operands must be lists!

occurrence of a true element and, if none were found, returns False,

The first true element is found, and if none were found, returns False.

If you have a list of lists , then this means that it's false for every single element in the list. This can be useful for testing whether a given value is true or false (or both). For example:

>>> L = [True, False] # create an empty list

>>> L[0].append(True) # append some values to the beginning of our original list

You'll get back True!

Since the sequence is empty, there are no elements that can be true,

Since the sequence is empty, there are no elements that can be true. So, all() evaluates its argument immediately and returns True.

On the other hand, any() evaluates its argument only when you call it. This means that if you call any() with a sequence containing an element that does not exist in your dataset (for example if we were to create an empty list), then it would return False since there is nothing else for it to consider as true or false.

therefore print(any([]))prints False."""

The truth is that print(any([]))prints False."""

The reason this works is because the equality operator == returns True if both operands are equal. Therefore, any() will return True only if all elements of the iterable are true. So when we pass an empty list to any(), it will return True and then print() will print out “False” in our console!

Conclusion

Python is a dynamic, interpreted language that encourages you to think as you code. It has an elegant syntax that is easy to learn, even for complete beginners. Although it has a reputation for being slow and complicated, Python’s simplicity and dynamic nature make it an ideal language for data science projects. You can use Python to explore machine learning techniques or build web apps from scratch without having any technical knowledge of programming languages like Java or C++!

https://youtu.be/UAhDtGhx6EA

Saturday 10 September 2022

Day 102 : Convert CSV to JSON

 

import pandas as pd

import csv,json

data=pd.read_csv("Instagram.csv")

print(data)

print("Converted JSON file below :")

print (json.dumps(list(csv.reader(open('Instagram.csv')))))


#clcoding.com

Impressions  Home  Hashtags  Explore  Other  Saves

0         3920  2586      1028      619     56     98

1         5394  2727      1838     1174     78    194

2         4021  2085      1188        0    533     41

3         4528  2700       621      932     73    172

Converted JSON file below :

[["Impressions", "Home", "Hashtags", "Explore", "Other", "Saves"], ["3920", "2586", "1028", "619", "56", "98"], ["5394", "2727", "1838", "1174", "78", "194"], ["4021", "2085", "1188", "0", "533", "41"], ["4528", "2700", "621", "932", "73", "172"]]

Popular Posts

Categories

AI (31) 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 (20) 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 (882) Python Coding Challenge (281) 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