Skip to main content

If Statement

The if statement is used to control the execution of code based on a condition. The if statement in Python and JavaScript has the same functionality, but there are significant syntax differences.


Design a program to determine whether a given number is positive, negative, or zero.

JavaScript implementation

const number = 100

if (number > 0) {
} else if (number < 0) {
} else {

Python implementation

number = 100

if number > 0:
elif number < 0:

Code Highlight

  • In Python, the if statement does not require parentheses around the condition, while in JavaScript, parentheses are needed.
  • In Python, a colon (:) is used to indicate the end of a condition, and indentation is used to denote a code block. In JavaScript, curly braces () are used to denote a code block.
  • In Python, elif is used to continue matching conditions, while in JavaScript, else if is used.
Code Indentation

Python uses strict code indentation (usually four spaces) to represent a code block. Adding or removing spaces can cause syntax errors. Unlike JavaScript, which uses paired curly braces, many IDEs often cannot automatically fix syntax errors caused by code indentation.

When there is no actual logic to be executed in a code block, you can use pass to indicate that nothing should be done, for example:

if some_condition:
pass # Do nothing

Difference Quick View

if statementif (condition) {code}if condition: code
else statementelse {code}else: code
else if statementelse if (condition) {code}elif condition: code
Nested if statementSameSame
Logical operators&&, `
Includeskey in myObj
key in my_dict
el in my_list
Greater than>>
Less than<<
Greater than or equal to>=>=
Less than or equal to<=<=
Conditional expressionlet estimation = score >= 60 ? 'Pass' : 'Fail'estimation = 'Pass' if score >= 60 else 'Fail'
Null Checking in Python

In Python, there are four ways to check if a value is null: is None, is not None, == None, and != None.


Python does not have a switch-case statement.