Skip to main content

Command Palette

Search for a command to run...

The JavaScript Developer's Guide to Learning Python - PART 1

Updated
•18 min read•View as Markdown
The JavaScript Developer's Guide to Learning Python - PART 1

Absolutely. I also noticed a few improvements that will make your article feel much more like it was written by an engineer rather than AI:

  • More conversational introduction.

  • Better spacing.

  • "💡 JavaScript Comparison" callouts.

  • "🤖 Why it matters for AI" sections.

  • Cleaner code blocks.

  • Better conclusion.

This is the style I'd recommend for your entire series.


🐍 Python for AI: A JavaScript Developer's Guide to the Basics

This is part of my journey of learning Python for AI Engineering. Since I already have a JavaScript background, I'll be explaining Python from a JavaScript developer's perspective. If you're making the same transition, this series is for you.


Why Python?

If you've been working with JavaScript, learning Python won't feel like learning programming all over again. Most programming concepts remain the same—the biggest difference is the syntax and philosophy.

JavaScript is everywhere in web development.

Python, however, has become the language of choice for:

  • 🤖 Artificial Intelligence

  • 🧠 Machine Learning

  • 📊 Data Science

  • ⚡ Automation

  • 🔬 Research

Since my goal is to become an AI Engineer, learning Python isn't optional—it's essential.

Let's begin with the fundamentals.


Variables

A variable is simply a name that stores a value in memory.

One of the first things you'll notice is that Python doesn't have let, const, or var.

You simply assign a value.

JavaScript

let name = "Aditya";
const age = 22;

Python

name = "Aditya"
age = 22

Simple.

Python automatically determines the data type based on the assigned value. This behavior is known as Dynamic Typing.

For example:

value = 10
print(value)

value = "Ten"
print(value)

Output

10
Ten

Although Python allows changing a variable's type, it's generally considered a bad practice because it makes code harder to understand and maintain.

💡 JavaScript Comparison

JavaScript also uses dynamic typing, so this concept should already feel familiar.


Data Types

Every value stored in Python belongs to a specific data type.

The five basic data types you'll use constantly are:

  • int

  • float

  • str

  • bool

  • None

Let's understand each one.


Integer (int)

Integers represent whole numbers.

age = 22
year = 2026

Checking the data type:

print(type(age))

Output

<class 'int'>

Float (float)

Floats represent decimal numbers.

price = 199.99
temperature = 36.6
print(type(price))

Output

<class 'float'>

String (str)

Strings store text.

Python allows both single and double quotes.

name = "Aditya"
city = 'Varanasi'
print(type(name))

Output

<class 'str'>

Boolean (bool)

Booleans represent True or False values.

is_logged_in = True
is_admin = False
print(type(is_logged_in))

Output

<class 'bool'>

💡 JavaScript Comparison

JavaScript uses true and false.

Python uses True and False.

The capitalization matters.


None

Sometimes a variable doesn't have any value yet.

Python represents this using None.

user = None
print(type(user))

Output

<class 'NoneType'>

💡 JavaScript Comparison

None in Python is similar to null in JavaScript.


Input & Output

Displaying output is done using the print() function.

print("Hello, World!")

You can also print variables.

name = "Aditya"

print(name)

Taking Input

Python provides the input() function.

name = input("Enter your name: ")

print("Hello,", name)

One important thing to remember:

input() always returns a string.

Even if the user enters a number.

age = input("Enter your age: ")

print(type(age))

Output

<class 'str'>

If you want a number, you'll need to convert it yourself.


Type Casting

Type casting means converting one data type into another.

Suppose a user enters their age.

age = input("Enter your age: ")

age = int(age)

print(age + 5)

A shorter and cleaner approach is:

age = int(input("Enter your age: "))

Other common conversions are:

int("25")

float("3.14")

str(100)

bool(1)

bool(0)

Output

25
3.14
100
True
False

🤖 Why This Matters for AI

Almost every AI application reads data from users, CSV files, APIs, databases, or sensors. Type conversion is something you'll use almost every day while working with datasets.


Comments

Comments make your code easier to understand.

A single-line comment starts with #.

# This is a comment

name = "Aditya"

For longer explanations, Python developers commonly use triple quotes.

"""
This is a multi-line comment.

It can span
multiple lines.
"""

Technically, triple quotes create a multi-line string, but they're widely used for documentation and explanatory notes.


JavaScript vs Python

JavaScript Python
let age = 22; age = 22
console.log() print()
prompt() input()
null None
true / false True / False
Number() int() / float()
String() str()

Key Takeaways

✅ Python doesn't use let, const, or var.

✅ Variables are dynamically typed.

✅ Basic data types include int, float, str, bool, and None.

✅ print() displays output, while input() accepts user input.

✅ input() always returns a string.

✅ Use functions like int(), float(), and str() for type conversion.

✅ Comments improve code readability and maintainability.


Final Thoughts

The syntax may look different, but the core programming concepts remain familiar if you're coming from JavaScript.

In fact, you'll probably find Python more expressive and easier to read. That's one of the reasons it's become the preferred language for AI, machine learning, and data science.

These fundamentals may seem simple, but they're the building blocks for everything ahead—from data preprocessing to training machine learning models and building AI-powered applications.

Excellent! To keep your series consistent, here's the next section in the same style. Since this is a continuation of the previous article, you don't need another long introduction.


Operators in Python

Operators are symbols that perform operations on variables and values.

If you've worked with JavaScript before, most Python operators will feel familiar. However, Python introduces a few additional operators—such as membership and identity operators—that you'll frequently encounter when working with collections and AI datasets.

Let's explore them one by one.


Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

Operator Description Example
+ Addition 5 + 3
- Subtraction 5 - 3
* Multiplication 5 * 3
/ Division 10 / 2
// Floor Division 10 // 3
% Modulus (Remainder) 10 % 3
** Exponent 2 ** 3

Example:

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)

Output

13
7
30
3.3333333333333335
3
1
1000

💡 JavaScript Comparison

Almost every arithmetic operator is the same in JavaScript. The only operator that often surprises JavaScript developers is **, which is used for exponentiation.


Comparison Operators

Comparison operators compare two values and always return either True or False.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example

a = 10
b = 20

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)

Output

False
True
False
True
False
True

💡 JavaScript Comparison

JavaScript has both == and ===.

Python only has ==, and it behaves more like JavaScript's strict equality (===) in most common cases.


Logical Operators

Logical operators combine multiple conditions.

Operator Meaning
and Both conditions must be True
or At least one condition must be True
not Reverses the result

Example

age = 22
has_id = True

print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)

Output

True
True
False

💡 JavaScript Comparison

JavaScript uses:

  • &&

  • ||

  • !

Python replaces them with readable keywords:

  • and

  • or

  • not

This makes Python code read almost like plain English.


Assignment Operators

Assignment operators are used to assign and update values.

Operator Example Equivalent To
= x = 5 Assign
+= x += 2 x = x + 2
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x %= 2 x = x % 2

Example

score = 50

score += 10
score *= 2

print(score)

Output

120

These operators make code shorter and easier to read.


Membership Operators

One feature Python developers use all the time is checking whether a value exists inside a collection.

Python provides two operators for this:

Operator Meaning
in Value exists
not in Value does not exist

Example

fruits = ["Apple", "Banana", "Mango"]

print("Apple" in fruits)
print("Orange" in fruits)
print("Orange" not in fruits)

Output

True
False
True

🤖 Why This Matters for AI

Membership operators are extremely common when working with lists of labels, datasets, dictionaries, vocabularies, and filtering data during preprocessing.


Identity Operators

Identity operators check whether two variables refer to the same object in memory, not just whether they contain equal values.

Operator Meaning
is Same object
is not Different objects

Example

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)
print(a is c)

print(a == c)

Output

True
False
True

Notice something interesting:

  • a == c checks whether the values are equal.

  • a is c checks whether they are literally the same object.

💡 JavaScript Comparison

Think of is as checking object references, similar to how JavaScript compares objects using ===.

Two different arrays with identical contents are still different objects.


JavaScript vs Python

JavaScript Python
&& and
`
! not
includes() in
Object reference (===) is
% %
** **

Common Beginner Mistakes

❌ Using = instead of == inside conditions.

if age = 18:

✅ Correct

if age == 18:

❌ Using is to compare numbers or strings.

name is "Aditya"

✅ Correct

name == "Aditya"

Use is when checking object identity or when comparing against None.

user = None

if user is None:
    print("No user found")

Key Takeaways

✅ Arithmetic operators perform mathematical calculations.

✅ Comparison operators always return True or False.

✅ Python uses and, or, and not instead of &&, ||, and !.

✅ Assignment operators provide a shorter way to update variables.

✅ Membership operators (in, not in) are widely used for searching collections.

✅ Identity operators (is, is not) compare object identity rather than value equality.


Final Thoughts

Most operators in Python feel familiar if you're coming from JavaScript, making the transition smooth. The biggest differences are Python's emphasis on readability (and, or, not) and the addition of powerful operators like in and is, which you'll use regularly in real-world AI and data processing tasks.

As you continue learning Python, these operators will become second nature, especially when writing conditions, filtering datasets, and building machine learning pipelines.

In the next section, we'll dive into Control Flow (if, elif, else), where these operators become even more useful for making decisions in your programs.


Control Flow

Programs become truly useful when they can make decisions.

Imagine building an AI chatbot. It needs to decide:

  • Is the prompt empty?

  • Is the user authenticated?

  • Should it call an API?

  • Is the confidence score high enough?

These decisions are made using control flow.

Python provides several ways to control the execution of your program:

  • if

  • elif

  • else

  • Ternary Operator

Let's understand each one.


The if Statement

The if statement executes a block of code only if a condition is True.

JavaScript

let age = 20;

if (age >= 18) {
    console.log("You can vote.");
}

Python

age = 20

if age >= 18:
    print("You can vote.")

Notice something different?

Python doesn't use:

  • Curly braces { }

  • Parentheses ()

Instead, it relies on indentation.

Everything inside the if block must be indented.

💡 JavaScript Comparison

JavaScript uses braces to define blocks.

Python uses indentation, making the code cleaner and more readable.


The elif Statement

Sometimes one condition isn't enough.

The elif statement allows you to check multiple conditions one after another.

marks = 82

if marks >= 90:
    print("Grade A")

elif marks >= 75:
    print("Grade B")

elif marks >= 60:
    print("Grade C")

Output

Grade B

Python evaluates conditions from top to bottom and stops as soon as one becomes True.


The else Statement

The else block executes when none of the previous conditions are satisfied.

marks = 45

if marks >= 90:
    print("Grade A")

elif marks >= 75:
    print("Grade B")

else:
    print("Needs Improvement")

Output

Needs Improvement

The else block doesn't require a condition—it acts as the default case.


Nested if

An if statement can also contain another if.

age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Entry Allowed")

Output

Entry Allowed

Although nesting is useful, avoid deeply nested code whenever possible, as it becomes difficult to read.


Ternary Operator

Sometimes an entire if-else statement fits into a single line.

Python provides the Ternary Operator for this.

Syntax

value_if_true if condition else value_if_false

Example

age = 20

status = "Adult" if age >= 18 else "Minor"

print(status)

Output

Adult

JavaScript Comparison

JavaScript

let status = age >= 18 ? "Adult" : "Minor";

Python

status = "Adult" if age >= 18 else "Minor"

The idea is exactly the same—the syntax is simply reversed.


🤖 Why This Matters for AI

Decision-making is everywhere in AI.

For example:

  • Choosing whether to call an LLM

  • Validating user input

  • Filtering datasets

  • Selecting a machine learning model

  • Handling API errors

Without conditional statements, AI applications wouldn't be able to react intelligently.


Loops

Loops allow us to repeat a block of code multiple times.

Instead of writing the same code repeatedly, we let the loop do the work.

Python mainly provides two types of loops:

  • for

  • while


The for Loop

The for loop is commonly used when you already know how many times you want to iterate or when you're looping through a collection.

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

Output

0
1
2
3
4

Notice that range(5) starts from 0 and stops before 5.


Looping Through a List

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output

Apple
Banana
Mango

This style is much cleaner than manually accessing indexes.


JavaScript Comparison

JavaScript

const fruits = ["Apple", "Banana", "Mango"];

for (const fruit of fruits) {
    console.log(fruit);
}

Python

for fruit in fruits:
    print(fruit)

The while Loop

The while loop continues running until its condition becomes False.

count = 1

while count <= 5:
    print(count)
    count += 1

Output

1
2
3
4
5

Be careful.

If the condition never becomes False, the loop will run forever.

while True:
    print("Infinite Loop")

The range() Function

range() generates a sequence of numbers.

It is most commonly used with for loops.

for number in range(1, 6):
    print(number)

Output

1
2
3
4
5

You can also specify a step value.

for number in range(0, 11, 2):
    print(number)

Output

0
2
4
6
8
10

The syntax is:

range(start, stop, step)

The break Statement

The break statement immediately exits a loop.

for number in range(10):

    if number == 5:
        break

    print(number)

Output

0
1
2
3
4

Once Python encounters break, the loop stops completely.


The continue Statement

Unlike break, continue skips the current iteration and moves to the next one.

for number in range(6):

    if number == 3:
        continue

    print(number)

Output

0
1
2
4
5

Only the value 3 is skipped.


The pass Statement

Sometimes Python expects a block of code, but you haven't written it yet.

Instead of leaving it empty, use pass.

for number in range(5):

    if number == 3:
        pass

    print(number)

pass does nothing—it simply acts as a placeholder.

You'll often see it while building large projects or writing function templates.


🤖 Why Loops Matter for AI

Loops are everywhere in AI and machine learning.

You'll use them to:

  • Iterate through datasets

  • Train machine learning models over multiple epochs

  • Process thousands of text documents

  • Read CSV files

  • Generate embeddings

  • Call APIs for multiple prompts

  • Evaluate predictions

Even though libraries like NumPy and Pandas reduce the need for explicit loops, understanding them is essential before using higher-level tools.


JavaScript vs Python

JavaScript Python
if (condition) if condition:
else if elif
condition ? x : y x if condition else y
for...of for item in list
while(condition) while condition:
break break
continue continue

Common Beginner Mistakes

❌ Forgetting indentation.

if age >= 18:
print("Adult")

✅ Correct

if age >= 18:
    print("Adult")

❌ Creating an infinite loop accidentally.

count = 1

while count <= 5:
    print(count)

Since count never changes, the loop never ends.

✅ Correct

count = 1

while count <= 5:
    print(count)
    count += 1

Key Takeaways

✅ Use if, elif, and else to make decisions.

✅ Python uses indentation instead of braces.

✅ The ternary operator is useful for simple one-line conditions.

✅ Use for loops to iterate over collections or sequences.

✅ Use while loops when the number of iterations isn't known in advance.

✅ range() generates sequences of numbers.

✅ break exits a loop, continue skips an iteration, and pass acts as a placeholder.


Final Thoughts

Control flow and loops are the backbone of almost every Python program. Whether you're validating user input, processing files, or training AI models, you'll constantly rely on these constructs to make decisions and repeat tasks efficiently.

Now that you can control the flow of your programs, the next step is to organize your code into reusable blocks with Functions, making your programs cleaner, more modular, and easier to maintain.

JavaScript to Python for AI

Part 1 of 2

A step-by-step journey of learning Python from a JavaScript developer's perspective, with a focus on AI engineering. Each article covers Python fundamentals, practical examples, JavaScript comparisons, and how the concepts apply to building AI applications.

Up next

The JavaScript Developer's Guide to Learning Python - PART 2

🐍 Strings in Python: A JavaScript Developer's Guide Strings are everywhere in AI. Whether you're building chatbots, processing documents, cleaning datasets, or interacting with Large Language Models