Python for C Programmers: Complete Learning
Guide
Section 1: Core Concepts and Syntax Differences
1.1 Variables and Data Types
C Approach:
// Must declare type explicitly
int age = 25;
float salary = 50000.50;
char name[50] = "John";
Python Approach:
# Types are inferred automatically
age = 25 # int
salary = 50000.50 # float
name = "John" # str
# You can check type using type()
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
# Variables can change types
x = 10 # int
x = "hello" # now str
x = [1,2,3] # now list
Key Takeaway:
• C: Static typing (declare once, type fixed)
• Python: Dynamic typing (type determined at runtime)
1.2 Control Structures
If Statements
// C version
if (score >= 90) {
printf("Grade A");
} else if (score >= 80) {
printf("Grade B");
} else {
printf("Grade C");
}
1
# Python version
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
Loops
// C for loop
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
// C while loop
int i = 0;
while (i < 10) {
printf("%d ", i);
i++;
}
# Python for loop - iterating over range
for i in range(10):
print(i, end=" ")
# Python for loop - iterating over list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Python while loop
i = 0
while i < 10:
print(i, end=" ")
i += 1
1.3 Functions
C Functions:
// Must specify return type and parameter types
int add(int a, int b) {
return a + b;
}
float divide(float a, float b) {
2
if (b != 0) {
return a / b;
}
return -1; // Error indicator
}
Python Functions:
# No need to specify types
def add(a, b):
return a + b
def divide(a, b):
if b != 0:
return a / b
return None # or raise an exception
# Python supports multiple return values
def get_name_age():
return "John", 25
name, age = get_name_age()
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
Section 2: Data Structures Comparison
2.1 Arrays vs Lists
C Arrays:
// Fixed size, same type
int numbers[5] = {1, 2, 3, 4, 5};
numbers[0] = 10; // Modify element
// Size must be known at compile time
int size = 5;
int arr[size]; // This works in C99+
Python Lists:
3
# Dynamic size, mixed types allowed
numbers = [1, 2, 3, 4, 5]
numbers[0] = 10 # Modify element
# Can grow and shrink
numbers.append(6) # Add element
numbers.remove(3) # Remove element
numbers.insert(1, 99) # Insert at position
# Mixed types
mixed = [1, "hello", 3.14, [1, 2, 3]]
# List comprehensions (powerful feature)
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
2.2 Structures vs Dictionaries/Classes
C Structures:
// Define structure
struct Person {
char name[50];
int age;
float salary;
};
// Use structure
struct Person p1;
strcpy(p1.name, "John");
p1.age = 30;
p1.salary = 50000.0;
// Access members
printf("Name: %s, Age: %d", p1.name, p1.age);
Python Dictionaries (Similar to C structs):
# Dictionary approach
person = {
"name": "John",
"age": 30,
"salary": 50000.0
}
# Access and modify
print(f"Name: {person['name']}, Age: {person['age']}")
4
person["age"] = 31 # Modify
person["city"] = "New York" # Add new field
Python Classes (More object-oriented):
class Person:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def introduce(self):
return f"Hi, I'm {self.name}, {self.age} years old"
def get_annual_salary(self):
return self.salary * 12
# Usage
p1 = Person("John", 30, 50000.0)
print(p1.introduce())
print(f"Annual salary: ${p1.get_annual_salary()}")
Section 3: Memory Management
C Memory Management:
#include <stdlib.h>
// Manual memory allocation
int *ptr = (int*)malloc(10 * sizeof(int));
if (ptr == NULL) {
// Handle allocation failure
return -1;
}
// Use the memory
for (int i = 0; i < 10; i++) {
ptr[i] = i * 2;
}
// Must free memory manually
free(ptr);
ptr = NULL; // Good practice
5
Python Memory Management:
# Automatic memory management
numbers = [i * 2 for i in range(10)] # Memory allocated automatically
# When 'numbers' goes out of scope or is reassigned,
# memory is automatically freed by garbage collector
numbers = None # Optional: explicitly remove reference
# No need for malloc/free!
# Python handles everything automatically
Section 4: String Handling
C Strings:
#include <string.h>
char str1[50] = "Hello";
char str2[50] = " World";
char result[100];
// String operations require functions
strcpy(result, str1); // Copy
strcat(result, str2); // Concatenate
int len = strlen(result); // Length
printf("Result: %s, Length: %d", result, len);
Python Strings:
str1 = "Hello"
str2 = " World"
# Simple operations
result = str1 + str2 # Concatenation
length = len(result) # Length
# Many built-in methods
upper_str = result.upper() # "HELLO WORLD"
words = result.split() # ["Hello", "World"]
replaced = result.replace("o", "0") # "Hell0 W0rld"
# String formatting
name = "Alice"
age = 25
formatted = f"Name: {name}, Age: {age}" # f-string (Python 3.6+)
6
print(f"Result: {result}, Length: {length}")
Section 5: Error Handling
C Error Handling:
#include <errno.h>
int divide(int a, int b, int *result) {
if (b == 0) {
return -1; // Error code
}
*result = a / b;
return 0; // Success
}
// Usage
int result;
int status = divide(10, 0, &result);
if (status != 0) {
printf("Error: Division by zero");
} else {
printf("Result: %d", result);
}
Python Error Handling:
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Usage with try/except
try:
result = divide(10, 0)
print(f"Result: {result}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("This always executes")
7
Section 6: Advanced Python Features for C Programmers
6.1 List Comprehensions (No C equivalent)
# Instead of:
squares = []
for i in range(10):
if i % 2 == 0:
squares.append(i**2)
# Write:
squares = [i**2 for i in range(10) if i % 2 == 0]
6.2 Multiple Assignment
# Swap variables (no temp variable needed)
a, b = b, a
# Multiple return values
def get_coordinates():
return 10, 20
x, y = get_coordinates()
6.3 Powerful Built-in Functions
numbers = [1, 5, 3, 9, 2]
# Built-in functions
total = sum(numbers) # Sum all elements
maximum = max(numbers) # Find maximum
minimum = min(numbers) # Find minimum
sorted_list = sorted(numbers) # Sort (returns new list)
numbers.sort() # Sort in-place
# Enumerate for index and value
for index, value in enumerate(['a', 'b', 'c']):
print(f"Index {index}: {value}")
Section 7: Quick Reference Cheat Sheet
Operation C Python
Print printf("Hello
print(f"Hello {name}")
%s",
name);
8
Operation C Python
Input scanf("%d",num = int(input("Enter
&num); number: "))
Array/List int arr = [1, 2, 3, 4, 5]
arr[5] =
{1,2,3,4,5};
String length strlen(str)len(str)
Loop over array for(int for item in array:
i=0;
i<size;
i++)
Function int def func(a): return
func(int a*2
a) {
return
a*2; }
Next Steps for Learning:
1. Practice the basics: Convert simple C programs to Python
2. Learn Python-specific features: List comprehensions, decorators, gen-
erators
3. Explore Python libraries: NumPy (for numerical computing), Pandas
(for data analysis)
4. Object-oriented programming: Classes, inheritance, polymorphism in
Python
5. File handling: Reading/writing files in Python vs C
6. Exception handling: Master Python’s try/except mechanism
Remember: Python’s philosophy is “There should be one obvious way to do it”
- often Python code is shorter and more readable than equivalent C code!