Basic Syntax
The fundamentals you need to start coding
Python Basics: Syntax and Fundamentals
Now that Python is installed, it’s time to get familiar with its syntax and core concepts. This tutorial will walk you through the essentials of Python: variables, data types, operators, and control flow structures.
Python is known for its clear, readable syntax, which emphasizes simplicity and consistency. That’s one of the reasons it makes an excellent first programming language.
Python Syntax
The first thing to understand about Python is its distinctive syntax.
Indentation and Code Blocks
Unlike many languages that use curly braces {} to delimit code blocks, Python uses indentation (typically 4 spaces):
# Example of indentation in Python
if condition:
# This block is indented with 4 spaces
instruction1
instruction2
if autre_condition:
# Nested block - 8 spaces
instruction3
# Back to the main level - no indentation
instruction_suivante
This approach makes code naturally more readable, but it also means that whitespace matters in Python!
Comments
Comments let you add explanatory notes to your code:
# This is a single-line comment
"""
This is a comment
spanning multiple lines (docstring)
"""
Variables and Data Types
In Python, you don’t need to declare a variable’s type before using it. The type is determined automatically when the value is assigned.
Variable Assignment
# Simple assignment
nom = "Alice"
age = 30
# Multiple assignment
x, y, z = 1, 2, 3
# Assigning the same value to several variables
a = b = c = 0
Naming Conventions
- Variable names are case-sensitive (
nomandNomare different) - They must start with a letter or an underscore
- They can contain letters, digits, and underscores
- By convention, Python variables use
snake_case
# Good naming
user_name = "Alice"
age_utilisateur = 30
_variable_privee = "secret"
# Bad naming (to avoid)
UserName = "Alice" # CamelCase style (reserved for classes)
1variable = 10 # Starts with a digit (syntax error)
nom-utilisateur = "Bob" # Contains a hyphen (syntax error)
Basic Data Types
Python has several built-in data types:
1. Numbers
# Integers (int)
age = 30
code_postal = 75000
# Floating-point numbers (float)
prix = 19.99
pi = 3.14159
# Complex numbers
complexe = 3 + 4j
2. Strings (str)
# Simple strings
prenom = "Marie"
nom = 'Dupont'
# Multiline strings
description = """Ceci est une chaîne
qui s'étend sur plusieurs
lignes."""
# String formatting (f-strings - Python 3.6+)
message = f"Bonjour {prenom} {nom}, vous avez {age} ans."
# Useful string methods
print(prenom.upper()) # MARIE
print(nom.lower()) # dupont
print(" texte ".strip()) # "texte"
print(",".join(["a", "b"])) # "a,b"
print("abc,def".split(",")) # ["abc", "def"]
3. Booleans (bool)
# Boolean values
est_majeur = True
est_inscrit = False
# Conditional expressions that produce booleans
a = 5
b = 10
print(a < b) # True
print(a == b) # False
print(a >= 5) # True
4. The None Value
None is the equivalent of null in other languages, representing the absence of a value:
resultat = None
# Check whether a variable is None
if resultat is None:
print("Aucun résultat disponible")
Type Checking
To find out a variable’s type, use the type() function:
x = 10
print(type(x)) # <class 'int'>
y = "bonjour"
print(type(y)) # <class 'str'>
Type Conversion (Casting)
# Convert to integer
age_str = "30"
age = int(age_str) # 30 (integer)
# Convert to string
nombre = 42
nombre_str = str(nombre) # "42" (string)
# Convert to float
prix = float("19.99") # 19.99 (float)
# Convert to boolean
valeur = bool(0) # False (0, "", [], {}, None evaluate to False)
Operators
Arithmetic Operators
a = 10
b = 3
addition = a + b # 13
soustraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333... (always returns a float)
division_entiere = a // b # 3 (floor division)
modulo = a % b # 1 (remainder of the division)
puissance = a ** b # 1000 (a raised to the power of b)
Comparison Operators
a = 10
b = 5
egal = a == b # False
different = a != b # True
superieur = a > b # True
inferieur = a < b # False
superieur_ou_egal = a >= b # True
inferieur_ou_egal = a <= b # False
Logical Operators
x = True
y = False
et = x and y # False (both must be True)
ou = x or y # True (at least one must be True)
non = not x # False (inverts the value)
Assignment Operators
x = 10
x += 5 # x = x + 5 (x is now 15)
x -= 3 # x = x - 3 (x is now 12)
x *= 2 # x = x * 2 (x is now 24)
x /= 4 # x = x / 4 (x is now 6.0)
x //= 2 # x = x // 2 (x is now 3.0)
x %= 2 # x = x % 2 (x is now 1.0)
x **= 3 # x = x ** 3 (x is now 1.0)
Membership Operators
liste = [1, 2, 3, 4, 5]
print(3 in liste) # True (3 is in the list)
print(6 not in liste) # True (6 is not in the list)
Identity Operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is c) # True (a and c reference the same object)
print(a is b) # False (a and b are different objects)
print(a == b) # True (a and b have the same value)
Control Structures
Control structures let you direct the flow of execution of your program.
Conditional Statements (if, elif, else)
age = 18
if age < 18:
print("Mineur")
elif age == 18:
print("Tout juste majeur")
else:
print("Majeur")
Conditional Expression (Ternary Operator)
# structure: value_if_true if condition else value_if_false
statut = "majeur" if age >= 18 else "mineur"
Loops
The for Loop
The for loop in Python is a “for each” loop that iterates over a sequence:
# Iterating over a list
fruits = ["pomme", "banane", "cerise"]
for fruit in fruits:
print(fruit)
# Iterating over a range of numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# range with start and stop
for i in range(2, 6): # 2, 3, 4, 5
print(i)
# range with step
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Enumeration (index and value)
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
The while Loop
The while loop continues as long as the condition is true:
compteur = 0
while compteur < 5:
print(compteur)
compteur += 1
Loop Control
# break - exits the loop
for i in range(10):
if i == 5:
break # Exit the loop when i reaches 5
print(i) # Prints 0, 1, 2, 3, 4
# continue - skips to the next iteration
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints 1, 3, 5, 7, 9
# else in loops - runs if the loop finishes normally (without break)
for i in range(5):
print(i)
else:
print("Boucle terminée sans break")
Basic Input and Output
Output (Standard Output)
# Simple output
print("Bonjour, monde!")
# Output with variables
nom = "Alice"
print("Bonjour,", nom)
# Formatting with f-strings (Python 3.6+)
age = 30
print(f"{nom} a {age} ans.")
# Multiple arguments
print("Nom:", nom, "Age:", age)
# Controlling the separator and line ending
print("a", "b", "c", sep="-", end="!\n") # Prints "a-b-c!"
Reading User Input
# Read user input (always returns a string)
nom = input("Entrez votre nom: ")
print(f"Bonjour, {nom}!")
# Convert the input to a number
age_str = input("Entrez votre âge: ")
age = int(age_str) # Convert to integer
Complete Example
Here is an example that uses several of the concepts we’ve learned:
# Program that calculates the average of a list of numbers
def calculer_moyenne(nombres):
"""Calcule la moyenne d'une liste de nombres."""
if not nombres: # If the list is empty
return 0
return sum(nombres) / len(nombres)
# Ask for the number of values
try:
n = int(input("Combien de nombres voulez-vous entrer? "))
# Collect the numbers
nombres = []
for i in range(n):
valeur = float(input(f"Entrez le nombre {i+1}: "))
nombres.append(valeur)
# Calculate and display the average
moyenne = calculer_moyenne(nombres)
print(f"La moyenne des nombres entrés est: {moyenne:.2f}")
# Show whether each number is above or below the average
print("\nComparaison avec la moyenne:")
for i, nombre in enumerate(nombres):
if nombre > moyenne:
relation = "supérieur à"
elif nombre < moyenne:
relation = "inférieur à"
else:
relation = "égal à"
print(f"Nombre {i+1} ({nombre}) est {relation} la moyenne.")
except ValueError:
print("Erreur: Veuillez entrer un nombre valide.")
This program:
- Defines a function to calculate the average
- Asks the user how many numbers they want to enter
- Collects those numbers
- Calculates and displays their average
- Compares each number to the average
Best Practices and Tips
To write clean, readable Python code, follow these guidelines:
-
Consistent indentation: Always use 4 spaces for indentation (no tabs).
-
Descriptive naming: Choose names that clearly explain what your variables are for.
-
Docstrings: Document your functions with documentation strings.
-
DRY (Don’t Repeat Yourself): Avoid repetition by using functions and loops.
-
KISS (Keep It Simple, Stupid): Favor simplicity and clarity over cleverness.
-
One line, one statement: Avoid putting multiple statements on the same line.
-
Error handling: Use try/except to handle potential errors.
-
PEP 8: Follow the Python style conventions (PEP 8) for consistency.
Practice Exercises
To solidify your knowledge, try these exercises:
-
Write a program that converts a temperature from Celsius to Fahrenheit (formula: F = C * 9/5 + 32).
-
Create a program that determines whether a number entered by the user is even or odd.
-
Write a program that displays the multiplication table for a number entered by the user.
-
Create a program that counts down from 10 to 1, then displays “Liftoff!”.
-
Write a program that asks for the user’s age and displays a different message depending on the age group.
Conclusion
In this tutorial, we covered the fundamentals of Python:
- Syntax and indentation
- Variables and data types
- Operators (arithmetic, comparison, logical)
- Control structures (if/elif/else, for, while)
- Basic input/output
These concepts are the foundation on which you will build your understanding of Python. As you progress, you’ll discover how these elements fit together to create more complex and powerful programs.
In the next tutorial, we’ll explore data structures in Python: lists, tuples, dictionaries, and sets, which will let you organize and manipulate your data efficiently.
Need to review the Python installation? Check out our installation guide.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion