Last updated: 2026-05-21

Python Basics

Python's syntax is designed to be clean and readable. If you are coming from JavaScript, the most immediate differences are visible right away: no curly braces, no semicolons, and indentation that is not cosmetic but structural. This topic covers the foundational syntax and concepts you need before writing any meaningful Python code.


Comments

A comment is text in the code that Python ignores during execution. Use comments to explain intent, leave notes, or temporarily disable code.

Single-line comments

# This is a single-line comment
age = 25  # Inline comment

Multi-line comments

Python has no dedicated multi-line comment syntax. The convention is to use consecutive single-line comments:

# This is a longer comment
# that spans multiple lines
# using consecutive # symbols

Triple-quoted strings are sometimes used as multi-line comments, but they are technically string literals — they are not ignored by the interpreter in the same way. Use # for genuine comments.


Variables and Assignment

In Python, variables are created the moment you assign a value to them. No declaration keyword is needed.

name = "Wariz"
age = 20
is_active = True

Multiple assignment

Python supports assigning multiple variables in one line:

x, y, z = 1, 2, 3
a = b = c = 0      # All three set to 0

Variable naming rules

  • Must start with a letter or underscore — not a number.
  • Can contain letters, numbers, and underscores.
  • Case-sensitive — name, Name, and NAME are three different variables.
  • Cannot be a Python reserved keyword (if, for, while, class, etc.).

Naming convention

Python follows snake_case for variable and function names — all lowercase with words separated by underscores:

user_name = "Wariz"
total_price = 99.99
is_logged_in = False

This contrasts with JavaScript's camelCase (userName, totalPrice). The convention is not enforced by the language but is universally adopted in the Python community and defined in PEP 8 — Python's official style guide.


Data Types

Python is dynamically typed — you do not declare types explicitly. Python infers the type from the value assigned.

Checking the type

type(42)          # <class 'int'>
type(3.14)        # <class 'float'>
type("hello")     # <class 'str'>
type(True)        # <class 'bool'>
type(None)        # <class 'NoneType'>

The core types

int — Integers

Whole numbers, positive or negative, with no size limit in Python:

age = 25
year = 2024
negative = -10
large = 1_000_000    # Underscores improve readability for large numbers

float — Floating-point numbers

Numbers with decimal points:

price = 9.99
pi = 3.14159
temperature = -0.5

Be aware that floating-point arithmetic is not always exact due to how computers represent decimals in binary:

0.1 + 0.2    # 0.30000000000000004 — not exactly 0.3

For precise decimal arithmetic (financial calculations, etc.), use Python's decimal module.

str — Strings

Text data, enclosed in single or double quotes — both are equivalent in Python:

name = "Wariz"
city = 'Lagos'
empty = ""

Triple quotes create multi-line strings:

message = """
This is a
multi-line string.
"""

bool — Booleans

is_active = True
has_paid = False

Note the capital first letter — True and False, not true and false as in JavaScript.

None — The absence of a value

None is Python's equivalent of null in JavaScript — it represents the intentional absence of a value:

result = None
user = None

Type Conversion

Python is strongly typed — it will not automatically convert between incompatible types. You must convert explicitly:

# String to int
age = int("25")         # 25

# Int to string
label = str(100)        # "100"

# String to float
price = float("9.99")   # 9.99

# Int to float
x = float(5)            # 5.0

# Float to int (truncates — does not round)
n = int(3.9)            # 3

Attempting an invalid conversion raises a ValueError:

int("hello")    # ValueError: invalid literal for int() with base 10: 'hello'

Strings in Depth

Strings are one of the most used types in Python. A few important properties and patterns:

f-strings (formatted string literals)

The modern, preferred way to embed values inside strings — introduced in Python 3.6:

name = "Wariz"
age = 20
print(f"Hello, {name}. You are {age} years old.")
# Hello, Wariz. You are 20 years old.

Any Python expression can go inside the {}:

print(f"2 + 2 = {2 + 2}")          # 2 + 2 = 4
print(f"Uppercase: {name.upper()}") # Uppercase: WARIZ

String indexing and slicing

Strings are sequences — each character has an index starting from 0:

name = "Wariz"
name[0]      # "W"
name[-1]     # "z" — negative index counts from the end
name[1:4]    # "ari" — slice from index 1 up to (not including) 4
name[:3]     # "War" — from start to index 3
name[2:]     # "riz" — from index 2 to end

Common string methods

"hello".upper()          # "HELLO"
"HELLO".lower()          # "hello"
"  hello  ".strip()      # "hello" — removes leading/trailing whitespace
"hello world".split()    # ["hello", "world"]
"hello".replace("l", "r") # "herro"
"hello".startswith("he") # True
"hello".endswith("lo")   # True
"hello".find("ll")       # 2 — index of first occurrence
len("hello")             # 5 — length

String concatenation

first = "Wariz"
last = "Labs"
full = first + " " + last    # "Wariz Labs"

Operators

Arithmetic operators

10 + 3     # 13   — addition
10 - 3     # 7    — subtraction
10 * 3     # 30   — multiplication
10 / 3     # 3.333... — division (always returns float)
10 // 3    # 3    — integer (floor) division
10 % 3     # 1    — modulo (remainder)
2 ** 3     # 8    — exponentiation

Note: / in Python always returns a float, even if both operands are integers (10 / 25.0). Use // for integer division.

Comparison operators

5 == 5     # True  — equality
5 != 3     # True  — not equal
5 > 3      # True  — greater than
5 < 3      # False — less than
5 >= 5     # True  — greater than or equal
5 <= 4     # False — less than or equal

Unlike JavaScript, Python has only one equality operator (==) — no loose vs. strict distinction. Python always compares both value and type.

Logical operators

True and False    # False
True or False     # True
not True          # False

Python uses English words (and, or, not) instead of symbols (&&, ||, !).

Assignment operators

x = 10
x += 5     # x = 15
x -= 3     # x = 12
x *= 2     # x = 24
x /= 4     # x = 6.0
x //= 2    # x = 3.0
x **= 2    # x = 9.0
x %= 4     # x = 1.0

Python has no ++ or -- operators. Use += 1 and -= 1.

Identity and membership operators

Python has two operators with no direct JavaScript equivalent:

# Identity — checks if two variables point to the same object
x = [1, 2, 3]
y = x
z = [1, 2, 3]

x is y     # True  — same object in memory
x is z     # False — equal values, different objects
x is not z # True

# Membership — checks if a value is in a sequence
"a" in "Wariz"        # False
"W" in "Wariz"        # True
3 in [1, 2, 3, 4]     # True
5 not in [1, 2, 3]    # True

The in operator is one of Python's most expressive features — it works on strings, lists, tuples, sets, and dictionaries.


Input and Output

Output — print()

print("Hello, World!")
print("Name:", name, "Age:", age)
print(f"Hello, {name}!")
print("Line one\nLine two")     # \n is a newline
print("a", "b", "c", sep="-")  # a-b-c — custom separator
print("Loading", end="...")     # Suppress the default newline

Input — input()

input() reads a line of text from the user. It always returns a string — convert if you need a number:

name = input("Enter your name: ")
print(f"Hello, {name}!")

age = int(input("Enter your age: "))
print(f"You are {age} years old.")

Indentation — Python's Most Important Rule

In Python, indentation defines code blocks. It is not cosmetic — it is syntax. A block is a group of statements that belong together, such as the body of an if statement, a loop, or a function.

if True:
    print("This is inside the block")   # Indented — part of the if block
    print("So is this")
print("This is outside the block")     # Not indented — executes regardless

The standard is 4 spaces per level of indentation (defined in PEP 8). Do not mix tabs and spaces — Python 3 raises an error if you do.

A wrong indentation level is a syntax error:

if True:
print("This will cause an IndentationError")  # ❌ Missing indentation

This is the single biggest adjustment for developers coming from JavaScript or other curly-brace languages. Once it becomes habitual, it is not a limitation — it enforces the readable formatting that the language was designed around.


Summary

ConceptPython
Comments# single line
Variable declarationname = "value" — no keyword needed
Naming conventionsnake_case
Integerint
Floatfloat
Stringstr — single or double quotes
BooleanboolTrue / False (capitalised)
Null equivalentNone
Type checkingtype(value)
Type conversionint(), str(), float(), bool()
f-stringsf"Hello, {name}"
Logical operatorsand, or, not
No increment operatorUse += 1 instead of ++
Division/ always returns float; use // for integer division
Identity operatoris / is not
Membership operatorin / not in
Code blocksDefined by indentation — 4 spaces per level