Nat  Grady

Nat Grady


Difference between Python vs. R: Syntactic Sugar Magic

Python and R empower data scientists to solve problems using elegant syntactic sugar, simplifying coding and solution exploration. Each language brings its unique capabilities and approach to bear.

My development palate has expanded since I learned to appreciate the sweetness found in Python and R. Data science is an art that can be approached from multiple angles but requires a careful balance of language, libraries, and expertise. The expansive capabilities of Python and R provide syntactic sugar: syntax that eases our work and allows us to address complex problems with short, elegant solutions.

These languages provide us with unique ways to explore our solution space. Each language has its own strengths and weaknesses. The trick to using each effectively is recognizing which problem types benefit from each tool and deciding how we want to communicate our findings. The syntactic sugar in each language allows us to work more efficiently.

R and Python function as interactive interfaces on top of lower-level code, allowing data scientists to use their chosen language for data exploration, visualization, and modeling. This interactivity enables us to avoid the incessant loop of editing and compiling code, which needlessly complicates our job.

These high-level languages allow us to work with minimal friction and do more with less code. Each language’s syntactic sugar enables us to quickly test our ideas in a REPL (read-evaluate-print loop), an interactive interface where code can be executed in real-time. This iterative approach is a key component in the modern data process cycle.

R vs. Python: Expressive and Specialized

The power of R and Python lies in their expressiveness and flexibility. Each language has specific use cases in which it is more powerful than the other. Additionally, each language solves problems along different vectors and with very different types of output. These styles tend to have different developer communities where one language is preferred. As each community grows organically, their preferred language and feature sets trend toward unique syntactic sugar styles that reduce the code volume required to solve problems. And as the community and language mature, the language’s syntactic sugar often gets even sweeter.

Although each language offers a powerful toolset for solving data problems, we must approach those problems in ways that exploit the particular strengths of the tools. R was born as a statistical computing language and has a wide set of tools available for performing statistical analyses and explaining the data. Python and its machine learning approaches solve similar problems but only those that fit into a machine learning model. Think of statistical computing and machine learning as two schools for data modeling: Although these schools are highly interconnected, their origins and paradigms for data modeling are different.

R Loves Statistics

R has evolved into a rich package offering for statistical analysis, linear modeling, and visualization. Because these packages have been part of the R ecosystem for decades, they are mature, efficient, and well documented. When a problem calls for a statistical computing approach, R is the right tool for the job.

The main reasons R is loved by its community boils down to:

  • Discrete data manipulation, computation, and filtering methods.
  • Flexible chaining operators to connect those methods.
  • A succinct syntactic sugar that allows developers to solve complex problems using comfortable statistical and visualization methods.

A Simple Linear Model With R

To see just how succinct R can be, let’s create an example that predicts diamond prices. First, we need data. We will use the diamonds default dataset, which is installed with R and contains attributes such as color and cut.

We will also demonstrate R’s pipe operator (%>%), the equivalent of the Unix command-line pipe (|) operator. This popular piece of R’s syntactic sugar feature is made available by the tidyverse package suite. This operator and the resulting code style is a game changer in R because it allows for the chaining of R verbs (i.e., R functions) to divide and conquer a breadth of problems.

The following code loads the required libraries, processes our data, and generates a linear model:


mode <- function(data) {
  freq <- unique(data)
  freq[which.max(tabulate(match(data, freq)))]

data <- diamonds %>% 
        mutate(across(where(is.numeric), ~ replace_na(., median(., na.rm = TRUE)))) %>% 
        mutate(across(where(is.numeric), scale))  %>%
        mutate(across(where(negate(is.numeric)), ~ replace_na(.x, mode(.x)))) 

model <- lm(price~., data=data)

model <- step(model)
lm(formula = price ~ carat + cut + color + clarity + depth + 
    table + x + z, data = data)

    Min      1Q  Median      3Q     Max 
-5.3588 -0.1485 -0.0460  0.0943  2.6806 

             Estimate Std. Error  t value Pr(>|t|)    
(Intercept) -0.140019   0.002461  -56.892  < 2e-16 ***
carat        1.337607   0.005775  231.630  < 2e-16 ***
cut.L        0.146537   0.005634   26.010  < 2e-16 ***
cut.Q       -0.075753   0.004508  -16.805  < 2e-16 ***
cut.C        0.037210   0.003876    9.601  < 2e-16 ***
cut^4       -0.005168   0.003101   -1.667  0.09559 .  
color.L     -0.489337   0.004347 -112.572  < 2e-16 ***
color.Q     -0.168463   0.003955  -42.599  < 2e-16 ***
color.C     -0.041429   0.003691  -11.224  < 2e-16 ***
color^4      0.009574   0.003391    2.824  0.00475 ** 
color^5     -0.024008   0.003202   -7.497 6.64e-14 ***
color^6     -0.012145   0.002911   -4.172 3.02e-05 ***
clarity.L    1.027115   0.007584  135.431  < 2e-16 ***
clarity.Q   -0.482557   0.007075  -68.205  < 2e-16 ***
clarity.C    0.246230   0.006054   40.676  < 2e-16 ***
clarity^4   -0.091485   0.004834  -18.926  < 2e-16 ***
clarity^5    0.058563   0.003948   14.833  < 2e-16 ***
clarity^6    0.001722   0.003438    0.501  0.61640    
clarity^7    0.022716   0.003034    7.487 7.13e-14 ***
depth       -0.022984   0.001622  -14.168  < 2e-16 ***
table       -0.014843   0.001631   -9.103  < 2e-16 ***
x           -0.281282   0.008097  -34.740  < 2e-16 ***
z           -0.008478   0.005872   -1.444  0.14880    
Signif. codes:  0 ‘***' 0.001 ‘**' 0.01 ‘*' 0.05 ‘.' 0.1 ‘ ' 1

Residual standard error: 0.2833 on 53917 degrees of freedom
Multiple R-squared:  0.9198,    Adjusted R-squared:  0.9198 
F-statistic: 2.81e+04 on 22 and 53917 DF,  p-value: < 2.2e-16

R makes this linear equation simple to program and understand with its syntactic sugar. Now, let’s shift our attention to where Python is king.

Python Is Best for Machine Learning

Python is a powerful, general-purpose language, with one of its primary user communities focused on machine learning, leveraging popular libraries like scikit-learn, imbalanced-learn, and Optuna. Many of the most influential machine learning toolkits, such as TensorFlow, PyTorch, and Jax, are written primarily for Python.

Python’s syntactic sugar is the magic that machine learning experts love, including succinct data pipeline syntax, as well as scikit-learn’s fit-transform-predict pattern:

  1. Transform data to prepare it for the model.
  2. Construct a model (implicit or explicitly).
  3. Fit the model.
  4. Predict new data (supervised model) or transform the data (unsupervised).
    • For supervised models, compute an error metric for the new data points.

The scikit-learn library encapsulates functionality matching this pattern while simplifying programming for exploration and visualization. There are also many features corresponding to each step of the machine learning cycle, providing cross-validation, hyperparameter tuning, and pipelines.

A Diamond Machine Learning Model

We’ll now focus on a simple machine learning example using Python, which has no direct comparison in R. We’ll use the same dataset and highlight the fit-transform-predict pattern in a very tight piece of code.

Following a machine learning approach, we’ll split the data into training and testing partitions. We’ll apply the same transformations on each partition and chain the contained operations with a pipeline. The methods (fit and score) are key examples of powerful machine learning methods contained in scikit-learn:

import numpy as np
import pandas as pd
from sklearn.linear_model LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from pandas.api.types import is_numeric_dtype

diamonds = sns.load_dataset('diamonds')
diamonds = diamonds.dropna()

x_train,x_test,y_train,y_test = train_test_split(diamonds.drop("price", axis=1), diamonds["price"], test_size=0.2, random_state=0)

num_idx = x_train.apply(lambda x: is_numeric_dtype(x)).values
num_cols = x_train.columns[num_idx].values
cat_cols = x_train.columns[~num_idx].values

num_pipeline = Pipeline(steps=[("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())])
cat_steps = Pipeline(steps=[("imputer", SimpleImputer(strategy="constant", fill_value="missing")), ("onehot", OneHotEncoder(drop="first", sparse=False))])

# data transformation and model constructor
preprocessor = ColumnTransformer(transformers=[("num", num_pipeline, num_cols), ("cat", cat_steps, cat_cols)])

mod = Pipeline(steps=[("preprocessor", preprocessor), ("linear", LinearRegression())])

# .fit() calls .fit_transform() in turn, y_train)

# .predict() calls .transform() in turn

print(f"R squared score: {mod.score(x_test, y_test):.3f}")

We can see how streamlined the machine learning process is in Python. Additionally, Python’s sklearn classes help developers avoid leaks and problems related to passing data through our model while also generating structured and production-level code.

What Else Can R and Python Do?

Aside from solving statistical applications and creating machine learning models, R and Python excel at reporting, APIs, interactive dashboards, and simple inclusion of external low-level code libraries.

Developers can generate interactive reports in both R and Python, but it’s far simpler to develop them in R. R also supports exporting those reports to PDF and HTML.

Both languages allow data scientists to create interactive data applications. R and Python use the libraries Shiny and Streamlit, respectively, to create these applications.

Lastly, R and Python both support external bindings to low-level code. This is typically used to inject highly performant operations into a library and then call those functions from within the language of choice. R uses the Rcpp package, while Python uses the pybind11 package to accomplish this.

Python and R: Getting Sweeter Every Day

In my work as a data scientist, I use both R and Python regularly. The key is to understand where each language is strongest and then adjust a problem to fit within an elegantly coded solution.

When communicating with clients, data scientists want to do so in the language that is most easily understood. Therefore, we must weigh whether a statistical or machine learning presentation is more effective and then use the most suitable programming language.

Python and R each provide an ever-growing collection of syntactic sugar, which both simplify our work as data scientists and ease its comprehensibility to others. The more refined our syntax, the easier it is to automate and interact with our preferred languages. I like my data science language sweet, and the elegant solutions that result are even sweeter.

Further Reading on the Toptal Engineering Blog:

Original article source at:

#python #r 

What is GEEK

Buddha Community

Difference between Python vs. R: Syntactic Sugar Magic

CSharp REPL: A Command Line C# REPL with Syntax Highlighting


A cross-platform command line REPL for the rapid experimentation and exploration of C#. It supports intellisense, installing NuGet packages, and referencing local .NET projects and assemblies.

C# REPL screenshot 

(click to view animation)

C# REPL provides the following features:

  • Syntax highlighting via ANSI escape sequences
  • Intellisense with fly-out documentation
  • Nuget package installation
  • Reference local assemblies, solutions, and projects
  • Navigate to source via Source Link
  • IL disassembly (both Debug and Release mode)
  • Fast and flicker-free rendering. A "diff" algorithm is used to only render what's changed.


C# REPL is a .NET 6 global tool, and runs on Windows 10, Mac OS, and Linux. It can be installed via:

dotnet tool install -g csharprepl

If you're running on Mac OS Catalina (10.15) or later, make sure you follow any additional directions printed to the screen. You may need to update your PATH variable in order to use .NET global tools.

After installation is complete, run csharprepl to begin. C# REPL can be updated via dotnet tool update -g csharprepl.


Run csharprepl from the command line to begin an interactive session. The default colorscheme uses the color palette defined by your terminal, but these colors can be changed using a theme.json file provided as a command line argument.

Evaluating Code

Type some C# into the prompt and press Enter to run it. The result, if any, will be printed:

> Console.WriteLine("Hello World")
Hello World

> DateTime.Now.AddDays(8)
[6/7/2021 5:13:00 PM]

To evaluate multiple lines of code, use Shift+Enter to insert a newline:

> var x = 5;
  var y = 8;
  x * y

Additionally, if the statement is not a "complete statement" a newline will automatically be inserted when Enter is pressed. For example, in the below code, the first line is not a syntactically complete statement, so when we press enter we'll go down to a new line:

> if (x == 5)
  | // caret position, after we press Enter on Line 1

Finally, pressing Ctrl+Enter will show a "detailed view" of the result. For example, for the DateTime.Now expression below, on the first line we pressed Enter, and on the second line we pressed Ctrl+Enter to view more detailed output:

> DateTime.Now // Pressing Enter shows a reasonable representation
[5/30/2021 5:13:00 PM]

> DateTime.Now // Pressing Ctrl+Enter shows a detailed representation
[5/30/2021 5:13:00 PM] {
  Date: [5/30/2021 12:00:00 AM],
  Day: 30,
  DayOfWeek: Sunday,
  DayOfYear: 150,
  Hour: 17,
  InternalKind: 9223372036854775808,
  InternalTicks: 637579915804530992,
  Kind: Local,
  Millisecond: 453,
  Minute: 13,
  Month: 5,
  Second: 0,
  Ticks: 637579915804530992,
  TimeOfDay: [17:13:00.4530992],
  Year: 2021,
  _dateData: 9860951952659306800

A note on semicolons: C# expressions do not require semicolons, but statements do. If a statement is missing a required semicolon, a newline will be added instead of trying to run the syntatically incomplete statement; simply type the semicolon to complete the statement.

> var now = DateTime.Now; // assignment statement, semicolon required

> DateTime.Now.AddDays(8) // expression, we don't need a semicolon
[6/7/2021 5:03:05 PM]

Keyboard Shortcuts

  • Basic Usage
    • Ctrl+C - Cancel current line
    • Ctrl+L - Clear screen
    • Enter - Evaluate the current line if it's a syntactically complete statement; otherwise add a newline
    • Control+Enter - Evaluate the current line, and return a more detailed representation of the result
    • Shift+Enter - Insert a new line (this does not currently work on Linux or Mac OS; Hopefully this will work in .NET 7)
    • Ctrl+Shift+C - Copy current line to clipboard
    • Ctrl+V, Shift+Insert, and Ctrl+Shift+V - Paste text to prompt. Automatically trims leading indent
  • Code Actions
    • F1 - Opens the MSDN documentation for the class/method under the caret (example)
    • F9 - Shows the IL (intermediate language) for the current statement in Debug mode.
    • Ctrl+F9 - Shows the IL for the current statement with Release mode optimizations.
    • F12 - Opens the source code in the browser for the class/method under the caret, if the assembly supports Source Link.
  • Autocompletion
    • Ctrl+Space - Open autocomplete menu. If there's a single option, pressing Ctrl+Space again will select the option
    • Enter, Right Arrow, Tab - Select active autocompletion option
    • Escape - closes autocomplete menu
  • Text Navigation
    • Home and End - Navigate to beginning of a single line and end of a single line, respectively
    • Ctrl+Home and Ctrl+End - Navigate to beginning of line and end across multiple lines in a multiline prompt, respectively
    • Arrows - Navigate characters within text
    • Ctrl+Arrows - Navigate words within text
    • Ctrl+Backspace - Delete previous word
    • Ctrl+Delete - Delete next word

Adding References

Use the #r command to add assembly or nuget references.

  • For assembly references, run #r "AssemblyName" or #r "path/to/assembly.dll"
  • For project references, run #r "path/to/project.csproj". Solution files (.sln) can also be referenced.
  • For nuget references, run #r "nuget: PackageName" to install the latest version of a package, or #r "nuget: PackageName, 13.0.5" to install a specific version (13.0.5 in this case).

Installing nuget packages

To run ASP.NET applications inside the REPL, start the csharprepl application with the --framework parameter, specifying the Microsoft.AspNetCore.App shared framework. Then, use the above #r command to reference the application DLL. See the Command Line Configuration section below for more details.

csharprepl --framework  Microsoft.AspNetCore.App

Command Line Configuration

The C# REPL supports multiple configuration flags to control startup, behavior, and appearance:

csharprepl [OPTIONS] [response-file.rsp] [script-file.csx] [-- <additional-arguments>]

Supported options are:

    • -r <dll> or --reference <dll>: Reference an assembly, project file, or nuget package. Can be specified multiple times. Uses the same syntax as #r statements inside the REPL. For example, csharprepl -r "nuget:Newtonsoft.Json" "path/to/myproj.csproj"
      • When an assembly or project is referenced, assemblies in the containing directory will be added to the assembly search path. This means that you don't need to manually add references to all of your assembly's dependencies (e.g. other references and nuget packages). Referencing the main entry assembly is enough.
    • -u <namespace> or --using <namespace>: Add a using statement. Can be specified multiple times.
    • -f <framework> or --framework <framework>: Reference a shared framework. The available shared frameworks depends on the local .NET installation, and can be useful when running an ASP.NET application from the REPL. Example frameworks are:
      • Microsoft.NETCore.App (default)
      • Microsoft.AspNetCore.All
      • Microsoft.AspNetCore.App
      • Microsoft.WindowsDesktop.App
    • -t <theme.json> or --theme <theme.json>: Read a theme file for syntax highlighting. This theme file associates C# syntax classifications with colors. The color values can be full RGB, or ANSI color names (defined in your terminal's theme). The NO_COLOR standard is supported.
    • --trace: Produce a trace file in the current directory that logs CSharpRepl internals. Useful for CSharpRepl bug reports.
    • -v or --version: Show version number and exit.
    • -h or --help: Show help and exit.
  • response-file.rsp: A filepath of an .rsp file, containing any of the above command line options.
  • script-file.csx: A filepath of a .csx file, containing lines of C# to evaluate before starting the REPL. Arguments to this script can be passed as <additional-arguments>, after a double hyphen (--), and will be available in a global args variable.

If you have dotnet-suggest enabled, all options can be tab-completed, including values provided to --framework and .NET namespaces provided to --using.

Integrating with other software

C# REPL is a standalone software application, but it can be useful to integrate it with other developer tools:

Windows Terminal

To add C# REPL as a menu entry in Windows Terminal, add the following profile to Windows Terminal's settings.json configuration file (under the JSON property profiles.list):

    "name": "C# REPL",
    "commandline": "csharprepl"

To get the exact colors shown in the screenshots in this README, install the Windows Terminal Dracula theme.

Visual Studio Code

To use the C# REPL with Visual Studio Code, simply run the csharprepl command in the Visual Studio Code terminal. To send commands to the REPL, use the built-in Terminal: Run Selected Text In Active Terminal command from the Command Palette (workbench.action.terminal.runSelectedText).

Visual Studio Code screenshot

Windows OS

To add the C# REPL to the Windows Start Menu for quick access, you can run the following PowerShell command, which will start C# REPL in Windows Terminal:

$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut("$env:appdata\Microsoft\Windows\Start Menu\Programs\csharprepl.lnk")
$shortcut.TargetPath = "wt.exe"
$shortcut.Arguments = "-w 0 nt csharprepl.exe"

You may also wish to add a shorter alias for C# REPL, which can be done by creating a .cmd file somewhere on your path. For example, put the following contents in C:\Users\username\.dotnet\tools\csr.cmd:

wt -w 0 nt csharprepl

This will allow you to launch C# REPL by running csr from anywhere that accepts Windows commands, like the Window Run dialog.

Comparison with other REPLs

This project is far from being the first REPL for C#. Here are some other projects; if this project doesn't suit you, another one might!

Visual Studio's C# Interactive pane is full-featured (it has syntax highlighting and intellisense) and is part of Visual Studio. This deep integration with Visual Studio is both a benefit from a workflow perspective, and a drawback as it's not cross-platform. As far as I know, the C# Interactive pane does not support NuGet packages or navigating to documentation/source code. Subjectively, it does not follow typical command line keybindings, so can feel a bit foreign.

csi.exe ships with C# and is a command line REPL. It's great because it's a cross platform REPL that comes out of the box, but it doesn't support syntax highlighting or autocompletion.

dotnet script allows you to run C# scripts from the command line. It has a REPL built-in, but the predominant focus seems to be as a script runner. It's a great tool, though, and has a strong community following.

dotnet interactive is a tool from Microsoft that creates a Jupyter notebook for C#, runnable through Visual Studio Code. It also provides a general framework useful for running REPLs.

Download Details:
Author: waf
Source Code:
License: MPL-2.0 License

#dotnet  #aspdotnet  #csharp 

August  Larson

August Larson


R vs Python: What Should Beginners Learn?

Let go of any doubts or confusion, make the right choice and then focus and thrive as a data scientist.

I currently lead a research group with data scientists who use both R and Python. I have been in this field for over 14 years. I have witnessed the growth of both languages over the years and there is now a thriving community behind both.

I did not have a straightforward journey and learned many things the hard way. However, you can avoid making the mistakes I made and lead a more focussed, more rewarding journey and reach your goals quicker than others.

Before I dive in, let’s get something out of the way. R and Python are just tools to do the same thing. Data Science. Neither of the tools is inherently better than the other. Both the tools have been evolving over years (and will likely continue to do so).

Therefore, the short answer on whether you should learn Python or R is: it depends.

The longer answer, if you can spare a few minutes, will help you focus on what really matters and avoid the most common mistakes most enthusiastic beginners aspiring to become expert data scientists make.

#r-programming #python #perspective #r vs python: what should beginners learn? #r vs python #r

Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Shardul Bhatt

Shardul Bhatt


Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.


Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python