• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

From JavaScript to Python: A Syntax Guide for Developers

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction


If you’re a JavaScript developer diving into Python, you’ll find many concepts familiar but with syntactic twists. Python’s emphasis on readability and simplicity means fewer brackets, strict indentation, and a different approach to common tasks. Let’s break down key differences with side-by-side examples.

1. Variables and Constants

JavaScript


let mutableVar = 10; // Mutable
const immutableVar = 20; // Immutable
Python


mutable_var = 10 # No 'let' or 'const'—all variables are mutable
IMMUTABLE_VAR = 20 # Convention: UPPER_CASE for "constants" (not enforced)

Key Notes:

  • Python uses snake_case (not camelCase).
  • No var or const—just assign values.
2. Data Types

JavaScriptPythonNotes
number int, float Python distinguishes integers and floats.
stringstrBoth use template literals/f-strings.
boolean (lowercase) bool (TitleCase)Python: True/False (case-sensitive).
array list, tuple Lists are mutable; tuples are immutable.
objectdictPython dicts ≈ JS objects.
null/undefined NonePython’s universal "no value" placeholder.
3. Conditionals

JavaScript


if (age > 18) {
console.log("Adult");
} else if (age === 18) {
console.log("Exactly 18");
} else {
console.log("Minor");
}
Python


if age > 18:
print("Adult")
elif age == 18: # 'elif' instead of 'else if'
print("Exactly 18")
else:
print("Minor") # Indentation defines blocks (no curly braces!)

Gotchas:

  • Use == for equality checks (Python has no ===).
  • Indentation is mandatory—use 4 spaces (no tabs).
4. Loops

For Loop


JavaScript (C-style):


for (let i = 0; i < 5; i++) {
console.log(i);
}

Python (range-based):


for i in range(5): # range(0, 5) → 0,1,2,3,4
print(i)
Iterating Over Arrays/Lists


JavaScript:


const fruits = ["apple", "banana"];
for (const fruit of fruits) {
console.log(fruit);
}

Python:


fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
5. Functions

JavaScript


function multiply(a, b) {
return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
Python


def multiply(a, b):
return a * b

# Lambda (anonymous)
multiply = lambda a, b: a * b

Key Differences:

  • Python uses def instead of function.
  • Lambdas are limited to single expressions.
6. Strings

Template Literals (JS) vs. f-Strings (Python)


JavaScript:


const name = "Alice";
console.log(`Hello, ${name}!`); // Backticks

Python:


name = "Alice"
print(f"Hello, {name}!") # 'f' prefix
7. Arrays (JS) vs. Lists (Python)

ActionJavaScriptPython
Add elementarr.push(4)lst.append(4)
Remove lastarr.pop()lst.pop()
Check existencearr.includes(4)4 in lst
Create copy[...arr]lst.copy()
Maparr.map(x => x*2)[x*2 for x in lst]

Python List Comprehension Example:


squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
8. Objects (JS) vs. Dictionaries (Python)


JavaScript:


const user = {
name: "Alice",
age: 30
};
console.log(user.name); // Dot notation

Python:


user = {
"name": "Alice",
"age": 30
}
print(user["name"]) # Or user.get("name")
9. Classes

JavaScript


class Dog {
constructor(name) {
this.name = name;
}

bark() {
console.log("Woof!");
}
}
Python


class Dog:
def __init__(self, name): # Constructor
self.name = name

def bark(self): # 'self' is explicit
print("Woof!")

Key Notes:

  • Python requires self as the first method parameter.
  • No new keyword: my_dog = Dog("Buddy").
10. Error Handling


JavaScript:


try {
throw new Error("Failed!");
} catch (error) {
console.log(error.message);
}

Python:


try:
raise Exception("Failed!")
except Exception as e:
print(e)
11. Modules and Imports


JavaScript (ES6):


import React from 'react';
export const PI = 3.14;

Python:


import math
from math import sqrt

# Exporting: Just write variables/functions in the file.
PI = 3.14
12. Truthy and Falsy Values

JavaScript FalsyPython Falsy
false, 0, "" False, 0, ""
null, undefined None
NaN [], {}, ()

Example:


if not []: # Empty list is falsy
print("This list is empty!")
Key Takeaways

  1. Indentation Rules: Python uses indentation (4 spaces) instead of curly braces.
  2. Simplicity: Python favors explicit, readable code (e.g., elif over else if).
  3. Rich Data Structures: Lists, tuples, sets, and dictionaries offer flexibility.
  4. No Semicolons: Optional in Python (but avoid them).
Example: Factorial Function


JavaScript:


function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}

Python:


def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Next Steps

  1. Practice: Use platforms like

    Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

    to solve problems in Python.
  2. Explore Libraries: Learn numpy (arrays), pandas (dataframes), and requests (HTTP).
  3. Read the Zen of Python: Run import this in a Python shell.
Final Thoughts


Python’s syntax feels minimalist compared to JavaScript, but its strict structure encourages clean code. Start small, embrace indentation, and leverage Python’s powerful built-in tools.

Happy coding! ?

Author: Mohin Sheikh

Follow me on

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

for more insights!



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу