Skip to main content

6. More Migration Guide: From Python to C

6.1 Common Syntax Differences

Feature Python C
Comments # This is a comment // This is a comment
Block Comments """Multi-line""" /* Multi-line */
Code Blocks Indentation { } braces
Statement End Line break ; semicolon
Boolean Values True, False 1, 0 (or true, false with <stdbool.h>)

6.2 Variable Declaration Migration

Python to C Translation Examples:

# Python
age = 25
height = 5.9
name = "Alice"
is_student = True
// C
int age = 25;
float height = 5.9f;
char name[] = "Alice";
int is_student = 1;  // or use bool with #include <stdbool.h>

6.3 Function Definition Migration (We will learn more about this on the next module)

Python:

def calculate_area(length, width):
    return length * width

result = calculate_area(5, 3)
print(result)

C:

#include <stdio.h>

// Function declaration (prototype)
int calculate_area(int length, int width);

int main() {
    int result = calculate_area(5, 3);
    printf("%d\n", result);
    return 0;
}

// Function definition
int calculate_area(int length, int width) {
    return length * width;
}

6.4 Common Pitfalls for Python Programmers

  1. Forgetting Semicolons:

    int x = 5  // ERROR: Missing semicolon
    int x = 5; // CORRECT
    
  2. Using = instead of == in conditions:

    if (x = 5) { ... }   // ERROR: Assignment, not comparison
    if (x == 5) { ... }  // CORRECT: Comparison
    
  3. Forgetting & in scanf():

    scanf("%d", x);   // ERROR: Missing &
    scanf("%d", &x);  // CORRECT
    
  4. Array Index Out of Bounds: (We will learn more about this on the next module)

    int arr[5];
    arr[5] = 10;  // ERROR: Index 5 is out of bounds (valid: 0-4)
    arr[4] = 10;  // CORRECT: Last valid index