In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the main difference between Python and JavaScript, the two popular programming languages? many beginners are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
Python and JavaScript
These two languages are very popular and powerful, but there are key differences between them, which we will cover in more detail here.
Let's get started! ✨
Python VS JavaScript: practical application
We'll start by taking a quick look at their real-world applications.
Python
Because of its powerful function and versatility, Python has become an indispensable tool in almost every scientific application in the world. It is a general programming language that supports different programming paradigms.
It is widely used in scientific and professional applications, including data science, artificial intelligence, machine learning, computer science education, computer vision and image processing, medicine, biology and even astronomy.
It is also used for Web development, which is where we can start comparing its applications with JavaScript applications. Python is used for back-end development, which is the area of Web development and is responsible for creating elements that are invisible to users, such as the server side of the application.
JavaScript
Although you can use Python to develop the back-end portion of a Web application, you can use JavaScript to develop the back-end and front-end of the application.
The front end is the part of the application that the user sees and interacts with. Whenever you see or interact with a website or Web application, you use JavaScript "behind the scenes".
Similarly, when you interact with mobile applications, you may use JavaScript, because frameworks like React Native allow us to write applications that adapt to different platforms.
JavaScript is so widely used in Web development because it is a multi-functional language that provides us with the tools we need to develop web application components.
Differences between Python and JavaScript applications
In short, developers use Python for a range of scientific applications. They use JavaScript for web development, user-oriented functions, and servers.
Python VS _ JavaScript: syntax
Now that you know what they are for, let's look at how they are written and their grammatical differences.
We will discuss their differences in the main elements:
Code block
Variable definition
Variable naming convention
Constant
Data types and values
Annotation
Built-in data structure
Operator
Input / output
Conditional statement
For cycle and While cycle
Function
Object oriented programming
Code blocks in Python and JavaScript
Each programming language has its own style to define code blocks, so let's look at the difference between Python and JavaScript:
How Python defines code blocks
Python relies on indentation to define blocks of code. When a series of consecutive lines of code are indented at the same level, they are treated as part of the same code block.
We use it to define conditions, functions, loops, and basically every compound statement in Python.
These are some examples:
Define blocks of code in Python using indentation
Tip: we'll see specific differences between these elements in Python and JavaScript later. For now, please pay attention to indentation.
How JavaScript defines a code block instead, in JavaScript, we use curly braces ({}) to group statements that belong to the same code block.
These are some examples:
Use curly braces to define code blocks in JavaScript
Variable definition assignment statements in Python and JavaScript are one of the most basic statements in any programming language. Let's look at how to define variables in Python and JavaScript.
How to define variables in Python
To define a variable in Python, we write out the name of the variable, followed by an equal sign (=) and the value to be assigned to the variable.
Like this:
=
For example:
X = 5
How to define variables in JavaScript
The syntax is very similar in JavaScript, but we just need to add the keyword var before the variable name and end with a semicolon (;).
Like this:
Var =
For example:
Var x = 5
We can also use the keyword let:
Let =
For example:
Let x = 5
Tip: in this case, when we use let, the variable will have block scope. It is only recognized in the block of code in which it is defined.
Variable definitions in Python and JavaScript
Tip: in JavaScript, the end of a statement is marked with a semicolon (;), but in Python, we just need to start with a new line to mark the end of the statement.
The variable naming conventions in Python and JavaScript, Python and JavaScript, follow two different variable naming conventions.
How to name variables in Python
In Python, we should use snake_case naming styles.
According to the Python style guide:
Variable names follow the same convention as function names.
Function names should be lowercase and, if necessary, separate words with an underscore to improve readability.
Therefore, the typical variable names in Python are as follows:
First_name
Tip: the style guide also mentions: "mixedCase is allowed only in contexts that are already mainstream styles to maintain backward compatibility."
How to name variables in JavaScript
Instead, we should use the lowerCamelCase naming style in JavaScript, where the name begins with a lowercase letter, and then each new word begins with an uppercase letter.
According to the JavaScript guidelines for MDN Web documents, articles:
For variable names, use lowerCamelCasing and, where appropriate, use concise, easy-to-read semantic names.
Therefore, the typical variable names in JavaScript should look like this:
FirstName
Constants in Python and JavaScript
Great. Now that you know more about variables, let's talk about constants, which are values that cannot be changed during program execution.
How to define constants in Python in Python, we rely on naming conventions to define constants because there are no strict rules in the language to prevent changing their values.
According to the Python style guide:
Constants are usually defined at the module level, written in all uppercase letters, and separated by underscores.
This is the naming we use to define constants in Python:
CONSTANT_NAME
For example:
TAX_RATE_PERCENTAGE = 32
Tip: this is a red warning for ourselves and other developers that this value should not be modified in the program. Technically, however, the value can still be modified.
How to define constants in JavaScript
In contrast, in JavaScript, we can define constants that cannot be changed in the program, and we cannot reassign variable identifiers.
But this does not mean that the value itself cannot be changed.
According to the const article in the MDN Web documentation:
The const declaration creates a read-only reference to the value. This doesn't mean that the values it holds are immutable-- it's just that you can't reassign variable identifiers. For example, in the case where the content is an object, this means that the content of the object (for example, its properties) can be changed.
To define a constant in JavaScript, we add the keyword const before the variable name:
Const TAX_RATE_PERCENTAGE = 32
If you try to change the value of a constant, you will see this error:
Therefore, the value cannot be changed.
Tip: to run and test small pieces of JavaScript code, you can use the console in the Chrome developer tool.
Data types and values in Python and JavaScript
Let's look at the main differences between Python and JavaScript data types.
The numeric data type Python has three numeric types that help us perform accurate calculations for scientific purposes, including: int (integer), float (floating point number), and complex (plural). They all have their own attributes, characteristics and applications.
By contrast, JavaScript has only two numeric types: Number and BigInt, and both integers and floating point numbers are considered to be of Number type.
According to the Number article in MDN Web Docs:
Numeric text such as 37 in JavaScript code is a floating-point value, not an integer. There are no separate integer types in daily use. (JavaScript now has a BigInt type, but it is not intended to replace the daily use of Number. 37 is still Number, not BigInt.)
None vs. Null
In Python, there is a special value, None, which we usually use to indicate that the variable has no value at a specific location in the program.
The equivalent value in JavaScript is null, which "indicates that any object value is intentionally missing".
Undefined value
In JavaScript, we have a special value that is automatically assigned when we declare a variable without assigning an initial value.
This is an example:
As you can see, the value of variable x is undefined.
In Python, you must assign an initial value to a variable, which cannot be declared without an initial value.
Tip: you can assign None as the initial value of the variable in Python to indicate the missing value.
Raw data types in Python and JavaScript
Primitive data types represent the most basic values that we can use in programming languages. Let's compare the raw data types of the two languages:
Python has four raw data types: integer (int), floating point number (float), Boolean value (bool), and string (str).
JavaScript has six raw data types: undefined (undefined), Boolean (Boolean), string (String), number (Number), BigInt, and symbol (Symbol).
How to write comments in Python and JavaScript
Comments are important for writing code that is concise and easy to read. Let's see how to use them in Python and JavaScript:
Single-line comment
In Python, we use the pound sign (#) to write comments, and all characters on the same line after that symbol are considered part of the comment.
In JavaScript, we write two slashes (/ /) to start a single-line comment.
This is a graphical example:
In Python:
# Comment
In JavaScript:
/ / Comment
Multiline comment
In Python, to write multiline comments, we start each line with a pound tag.
In JavaScript, multiline comments begin with / * and end with * /, and all characters between these symbols are considered part of the comment.
In Python:
# Multi-line comment # in Python to explain # the code in detail.
In JavaScript:
/ * Multi-line comment in JavaScript to explain the code in detail. , /
Built-in data structures in Python and JavaScript
There are also key differences in the built-in data structures in Python and JavaScript.
Tuple (Tuples)
In Python, we have a built-in data structure called tuple, which is very similar to a list, but immutable. Therefore, it cannot be changed during program execution, so it is used to store data that should not be modified.
In JavaScript, there are no built-in data structures with these characteristics, although you can use some features of the language to implement similar data structures.
List (Lists) vs. Array (Arrays)
In Python, lists are used to store a series of values in the same data structure. It can be modified, indexed, sliced, and used in the program.
In JavaScript, the equivalent version of this data structure is called array.
This is an example:
Hash table (Hash Tables)
In Python, there is a built-in data structure called * * dictionary (dictionary) * *, which helps us map some values to other values and create key-value pairs, which can be used as hash tables.
JavaScript does not have this type of built-in data structure, but there are ways to use certain elements of the language to reproduce its functionality.
Operator operators in Python and JavaScript
Essential for writing expressions in any programming language, let's take a look at the main differences between Python and JavaScript.
Take down the divider
Although most arithmetic operators work exactly the same in Python and JavaScript, the rounding down divider operator is slightly different.
In Python, the base division operation (also known as "integer division") is represented by a double slash (/ /).
In JavaScript, we don't have a specific down integer division operator. Instead, we call the Math.floor () method to round the result to the nearest integer.
Compare values and types
In Python, we use the = = operator to compare whether two values and their data types are equal.
For example:
# Comparing Two Integers > 0 = = 0 True # Comparing Integer to String > 0 = = "0" False
In JavaScript, we also have this operator, but it works slightly differently because it converts two objects to the same type before actually performing the comparison.
If we use JavaScript (0 = ='0') to check the result of the "integer and string" comparison in the previous example, the result is True instead of False, because the value is converted to the same data type before the comparison:
In JavaScript, to check that values and data types are equal, we need to use this operator = (triple equal sign).
Now we have achieved the expected results:
Isn't that great?
Tip: the = = operator in Python works like the = = operator in JavaScript.
Logical operator
In Python, the three logical operators are: and, or, and not.
In JavaScript, these operators are: & &, | | and!.
Type operator
In Python, to check the type of an object, we use the type () function.
In JavaScript, we use the typeof operator.
This is a graphical description of their syntax:
Input and output of Python and JavaScript
It is very common to ask the user to enter and display the value to the user, so let's see how to do this with Python and JavaScript:
Input
In Python, we use the input () function to request user input, and we write the message in parentheses.
In JavaScript, an alternative (if you are running code on a browser) is to display a tip with window.prompt (message) and assign the result to a variable.
The main difference between the two methods is that in Python, the user is prompted to enter a value in the console, while in JavaScript, a small prompt is displayed on the browser that asks the user to enter a value.
? Tip: you will see the following input values in the Python console:
In JavaScript, if you open the Chrome Developer tool and enter the following line of code in the console:
This prompt displays:
The prompt displayed when window.prompt () is called
Output
In Python, we use the print () function to print the value to the console and pass it in parentheses.
In JavaScript, we use console.log () to print the value to the console and pass it in parentheses.
Tip: if you are using a browser, you can also call alert () to display a tip and pass the message (or value) in parentheses.
Conditional statements in Python and JavaScript
Using conditions, we can choose what happens in the program based on whether the particular condition is True or False, and let's look at the difference between Python and JavaScript.
If statement
In Python, we rely on indentation to indicate which lines of code are conditional code.
In JavaScript, you must enclose the condition in parentheses, enclose the code in curly braces, and the code should also be indented.
Conditional use of Python (left) and JavaScript (right)
If/else statement
The else clause in the two languages is very similar, except that:
In Python, we write a colon (:) after the else keyword
In JavaScript, we enclose the code that belongs to this clause in curly braces ({}).
Multiple conditions
To write multiple conditions:
In Python, we write the keyword elif followed by a condition. After the condition, we write a colon (:) and indent the code on the next line.
In JavaScript, if the condition is followed (surrounded by parentheses), we will write the keyword else if. When the condition is complete, we write curly braces and indent the code in parentheses.
Switch in JavaScript
In JavaScript, we have an additional control structure that can be used to choose what to happen based on the value of the expression, which is called switch.
Python does not have this type of built-in control structure.
This is the general syntax of the statement:
Switch statement in JavaScript
In JavaScript:
Switch (expression) {case value1: / / Code break; case value2: / / Code break; case value3: / / Code break; default: / / Code}
Tip: we can add as many case as we need, and the expression can be a variable.
For loop and While loop in Python and JavaScript
Now let's look at how to define different types of loops in Python and JavaScript and their main differences.
For cycle
The syntax for defining for loops in Python is relatively simpler than the syntax in JavaScript.
In Python, we write the keyword for, followed by the name of the loop variable, the keyword in, and a call to the range () function to specify the necessary parameters. Then we write a colon (:) followed by an indented loop body.
In JavaScript, we must specify several values explicitly. We start with the for keyword, followed by parentheses, in which we define the loop variable and its initial value, must be a condition for False to stop the loop, and how to update the variable in each iteration. Then, write curly braces to create the code block, and then write the indented loop body within the curly braces.
For loops in Python (left) and JavaScript (right)
Traversing iterable objects
We can use for loops in Python and JavaScript to iterate over iterable elements.
In Python, we write the keyword for, followed by a loop variable, the in keyword, and iterable. Then we write a colon (:) and the loop body (indent).
In JavaScript, we can use for.. Of loop. We write the for keyword first, followed by parentheses, and then in these parentheses, we write the keyword var, followed by the loop variable, the keywords of and iterable. We enclose the body of the loop in curly braces and indent it.
In JavaScript, we also have for.. The in loop iterates through the properties of the object.
According to the MDN Web documentation:
For... The in statement iterates over all enumerable properties of the object, including inherited enumerable properties, which are typed by a string (ignoring attributes typed by Symbol).
This is an example:
Const object = {a: 1, b: 2, c: 3}; for (const property in object) {console.log (property, object [property]);}
When we run this code in the console of the Chrome developer tool, the output is as follows:
While cycle
While loops are very similar in Python and JavaScript.
In Python, we first write the while keyword, followed by the condition, the colon (:), and write the loop body (indent) in the new line.
In JavaScript, the syntax is very similar. The difference is that we must enclose the condition in parentheses and the body of the loop in curly braces.
While loops in Python (left) and JavaScript (right)
Do..while Loop in JavaScript
In JavaScript, we also have a type of loop that does not exist in Python.
This loop is called a do..while loop because it performs at least one operation and continues to run when the condition is True.
This is the basic syntax:
Do {/ / Code} while (condition)
Tip: this type of loop guarantees that the code will be executed at least once.
This is especially useful when we ask the user for input, because the user will be prompted for input. If the input is valid, we can continue the program. But if it is not valid, we can prompt the user to enter the value again until it is valid.
Functions in Python and JavaScript
Functions are very important for writing concise, maintainable and readable programs. The syntax is very similar in Python and JavaScript, but let's analyze their main differences:
In Python, we write the keyword def, followed by the function name, in parentheses in the argument list. After this list, we write a colon (:) and the function body (indent).
The only difference in JavaScript is that we define a function using the function keyword and enclose the body of the function in curly braces.
In addition, there is a very important difference between Python and JavaScript functions: function parameters.
In Python, the number of parameters passed to a function call must match the number of parameters defined in the function definition. If this is not the case, an exception will occur.
This is an example:
> > def foo (x, y): print (x, y) > foo (3,4,5) Traceback (most recent call last): File ", line 1, in foo (3,4,5) TypeError: foo () takes 2 positional arguments but 3 were given
In JavaScript, this is not necessary because the parameters are optional. You can call a function with fewer or more parameters than those defined in the function definition. By default, missing parameters are assigned undefined values, and other parameters can be accessed using the arguments object.
This is an example in JavaScript:
Notice how to call the function with three parameters, but the function definition contains only two parameters in the parameter list.
Tip: to get the number of arguments passed to the function, you can use arguments.length within the function.
Using Python and JavaScript for object-oriented programming
Both Python and JavaScript support object-oriented programming, so let's look at how to create and use the main elements of this programming paradigm.
Class-like
The first line of the class definition is very similar in Python and JavaScript. We write the keyword class, followed by the name of the class.
The only difference is:
In Python, after the class name, we write a colon (:)
In JavaScript, we surround the contents of the class with curly braces ({})
Class definitions in Python (left) and JavaScript (right)
Tip: in Python and JavaScript, the class name should start with an uppercase letter, and each word should also begin with an uppercase letter.
Constructors and properties
The constructor is a special method that is called when a new instance of a class (a new object) is created, and its main purpose is to initialize the properties of the instance.
In Python, the constructor used to initialize a new instance is called init (with two leading underscores and trailing underscores). This method is automatically called when an instance of the class is created to initialize its properties. Its parameter list defines the values that must be passed to create an instance, starting with self as the first parameter.
In JavaScript, the constructor method is called the constructor function, which also has a parameter list.
Tip: in Python, we use self to reference the instance, while in JavaScript, we use this to reference the instance.
To assign a value to an attribute in Python, we use the following syntax:
Self.attribute = value
Instead, we use the following syntax in JavaScript:
This.attribute = value
Examples of classes in Python (left) and JavaScript (right)
Methods in Python and JavaScript in Python, we use the def keyword to define methods, followed by their names and a list of parameters in parentheses. This parameter list begins with the self parameter to refer to the instance that is calling the method. After this list, we write a colon (:) and indent the body of the method.
This is an example:
Class Circle: def _ init__ (self, radius, color): self.radius = radius self.color = color def calc_diameter (self): return self.radius * 2
In JavaScript, methods are defined by writing the name, followed by a list of parameters and curly braces. In curly braces, we write the body of the method.
Class Circle {constructor (radius, color) {this.radius = radius; this.color = color;} calcDiameter () {return this.radius * 2;}}
Example
To create an instance of a class:
In Python, we write the name of the class and pass parameters in parentheses
My_circle = Circle (5, "Red")
In JavaScript, we need to add the new keyword before the class name.
My_circle = new Circle (5, "Red")
Python and JavaScript are powerful languages with different practical applications.
Python can be used for web development and a wide range of applications, including scientific uses. JavaScript is mainly used for web development (front-end and back-end) and mobile application development.
They have important differences, but they all have the same basic elements that we need to write powerful programs.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.