PYTHON FUNDAMENTALS

A concise, well-organized reference guide covering Python basics, following
official conventions and best practices.

  • Python Extension Pack: Bundles essential tools (Python, Django, Jinja support)
  • Pylance: Advanced language support, IntelliSense, type checking
  • vscode-icons (optional): Visual file-type icons in the explorer
  • Sublime Text Keymap (optional): Additional keyboard shortcuts for productivity

Command:

Use ipython for interactive coding, debugging, and rapid prototyping.

Operator Description Example Result

modulo % : 5%2 = 1
division entiere // : 5//2=2
puissance ** : (3²)² = 3**2*2 = 81

String literals

text = “Hello”

Concatenation

full = “Hello” + ” ” + “World” # “Hello World”

Repetition (shallow copy)

repeat = “Hi ” * 3 # “Hi Hi Hi “

== Equal to 5 == 5 -> True
!= Not equal to 5 != 3 -> True

>= Greater than or eq 10 >= 5 -> True
<= Less than or eq 3 <= 3 -> True
> Greater than 6 > 5 -> True
<= Less than 5 > 6 -> True

a = 25
b = 16

id(a) : Gets memory address (e.g., 140234567890)
id(a)==id(b) false : We can compare

For any value between -5 and 256 characters, python caches the values and therefore the ids will be the same if not different

a=-4 b=-4
id(a)==id(b) true

a=257 b=257
id(a)==id(b) false

Simple assignment
a = 1

Multiple assignment
a, b, c = 24, 67, 15

Swap values
a, b = b, a

Augmented assignments
a += 10 # a = a + 10
a -= 10 # a = a – 10
a *= 10 # a = a * 10
a /= 2 # a = a / 2 (float result)
a //= 2 # a = a // 2 (floor division)
a **= 2 # a = a ** 2 (exponentiation)

  • Use letters, digits, and underscores (_)
  • Cannot start with a digit
  • Case-sensitive (age != Age)

Style………………Example………………………….Typical Use
……………………………………………………………………………………………………………………………..
snake_case……user_age, total_count……Variables, functions, modules
camelCase…….userName, totalCount…..Less common; used in some APIs
PascalCase…….UserProfile, DataBase…….Class names

BEST PRACTICE: Use snake_case for variables/functions, PascalCase for classes

Type………….. Example………….Description
……………………………………………………………………………………….
int……………… 42, -7………………….Integer numbers
float…………….3.14, -0.5……………Floating-point numbers
str………………..”Hello”, ‘World’….Text strings
bool…………….True, False………..Boolean values
complex……..2+3j……………………Complex numbers
NoneType…..None…………………Represents absence of value

Check type

type(42) # <class ‘int’>

Convert types

int(“100”) # 100
str(42) # “42”
float(“56.46”) # 56.46
complex(5) # (5+0j)

Boolean conversion

bool(“str”) : Returns true if string is valide
bool(“False”) –> true

Falsy values in Python

These values evaluate to False in boolean context:

bool(False) # False
bool(0) # False
bool(0.0) # False
bool(“”) # False
bool([]) # False
bool({}) # False
bool(None) # False

name = “John”
surname = “Lys”
age = 14

1. Concatenation (+)

full = surname + ” ” + name –> “Lys John”

2. print() with commas

print(name, surname) –> John Lys

3. Concatenation with casting

print(name + ” ” + surname + ” is ” + str(age) + ” years old”)

4. print() with mixed types

print(name, surname, “is”, age, “years old”)

5. Old-style % formatting

print(“%s %s is %d years old” % (name, surname, age))

6. str.format() – positional

print(“{} {} is {} years old”.format(name, surname, age))

7. str.format() – indexed

print(“{2} {1} is {0} years old”.format(age, surname, name))

8. str.format() – named

print(“{n} {s} is {a} years old”.format(n=name, s=surname, a=age))

9. f-strings (Python 3.6+) – RECOMMENDED

print(f”{name} {surname} is {age} years old”)

BEST PRACTICE: Use f-strings for readability and performance.

if condition

if age >= 19:
…print(“You are an adult!”)
elif 14 < age < 19:
…print(“You are a teenager!”)
elif 5 < age <= 14:
…print(“You are a child!”)
else:
…print(“You are a baby!”)

TIP: Use elif for mutually exclusive branches; keep conditions clear and ordered.

WHILE Loop

name = input(“Enter your name please !”)
loop=true

while loop:
…if name:
……print(f”Hello {nom}, how are you today ?”)
……loop = false
…else:
……nom = input(“Enter your name please !”)

For condifiton

for i in range(10):
…print((i+1)**2)

NOTE: range(n) generates integers from 0 to n-1.

Lists

Can contain any type of data

l=[] # empty list
l=[“Ted”, 34, True, range(15)]

print(l)
print(l[0])

for item in items:
…if isinstance(item, str):
……print(item.upper())
…elif isinstance(item, int):
……print(item ** 2)
…else:
……print(item)

Tuples

Like lists but can’t be modified once created and use ( ) instead of [ ]

data = (“Ted”, 34, True, range(15))

TIP: Use lists for mutable collections; tuples for fixed, hashable data.

def greet(name, age=-1):
…”””Print a greeting message. Age is optional.”””
…print(f”Hello {name}, you are {age} years old!”)

greet(“John”) —–> Hello John, you are -1 years old!
greet(“Anna”, 25) —–> Hello Anna, you are 25 years old!

NOTE: Functions return None by default if no return statement is used.

List unpacking

names = [“Jean”, “Marie”, “Prune”]

a, b, c = names —–> a=”Jean”, b=”Marie”, c=”Prune”
a, *others = names —–> a=”Jean”, others=[“Marie”, “Prune”]
*others, c = names —–> c=”Prune”, others=[“Jean”, “Marie”]

Dictionary unpacking

data = {“name”: “Jean”, “first”: “Marie”}

print(*data) —–> name first (keys)
print(*data.values()) —–> Jean Marie
print(*data.items()) —–> (‘name’, ‘Jean’) (‘first’, ‘Marie’)

Function argument unpacking

def hello(first, name):
…print(f”Hello {first} {name}”)

Unpack list

args = [“Jean”, “Marie”]

hello(*args) —–> Hello Jean Marie

Unpack dict (keys must match parameter names)

hello(**{“first”: “Marie”, “name”: “Jean”}) —–> Hello Marie Jean

TIP: Use * for positional unpacking, ** for keyword unpacking.

Basic lambda

add = lambda a, b: a + b

add(3, 4) —–> 7

Use in sorting

words = [“Anne”, “Joe”, “Boubacar”]

Sort by length, then alphabetically :

words.sort(key=lambda w: (len(w), w))

print(words) —–> [‘Joe’, ‘Anne’, ‘Boubacar’]

TIP: Lambdas are for short, single-expression functions. Prefer def for complex logic.

def is_adult(age):
…return True if age >= 18 else False

More concise:

def is_adult(age):
…return age >= 18

TIP: Use ternary expressions for simple conditional assignments.

*args: arbitrary positional arguments

def total(*args):
…return sum(args)

total(1, 2, 3) —–> 6

**kwargs: arbitrary keyword arguments

def create_profile(**kwargs):
…print(kwargs)

create_profile(name=”Jean”, age=14, role=”DevOps”)

—–> {‘name’: ‘Jean’, ‘age’: 14, ‘role’: ‘DevOps’}

TIP: Use *args for flexible positional inputs; **kwargs for named parameters.