Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

C to Python: Essential Constructs

Recommended resources

Welcome to your first lesson! We're kicking off your journey into machine learning by building a solid foundation in Python, the most widely used language in the field. Your background in C gives you a significant advantage, as you're already familiar with fundamental programming concepts like variables, loops, and functions. The goal of this first module, "Python Fundamentals for Data Science," is to get you comfortable and productive in Python by leveraging what you already know.

Today's lesson focuses on a direct translation of your C skills. We'll cover how to express basic programming constructs—conditionals, loops, and functions—using Python's syntax. We'll see that while the underlying logic is the same, Python often allows for more concise and readable code, prioritizing developer speed over the low-level control that C provides.

Let's begin by exploring the high-level differences and similarities between the two languages.

From C to Python: A Shift in Perspective

While C is a compiled, statically-typed language that gives you fine-grained control over memory, Python is an interpreted, dynamically-typed language that handles much of that complexity for you. This distinction is at the heart of why Python is so popular for scripting and data science.

To get a feel for this transition, let's watch a video created for programmers in your exact situation—moving from C to Python.

From C to Python by Ross Rheingans-Yoo

This video from CS50, "From C to Python," is designed to bridge the gap between the two languages. Please watch the first part of the video.

Watch from the beginning up to the discussion on dynamic typing and the absence of a main function. Pay attention to the initial comparison of a simple program in C and Python. Focus on: The concept of Python as an interpreted language (Python as a scripting language). The execution model: Python scripts run from top to bottom, without a required main() function (no main function). The lack of mandatory semicolons and explicit type declarations (semicolons and types).

As the video highlighted, three of the most immediate differences you'll encounter are:

  1. Dynamic Typing: You don't declare a variable's type. A variable is just a name pointing to an object, and you can reassign that name to an object of a different type.
  2. No main() Function: Code in a Python file is executed sequentially from the first line.
  3. Significant Whitespace: Instead of curly braces {} to define code blocks, Python uses indentation. This is a crucial rule that enforces readable code style.

Let's dig deeper into these points.


Variables, Operators, and the Power of Indentation

The shift from C's static typing to Python's dynamic typing is fundamental. Where in C you would write int x = 10;, in Python you simply write x = 10. The Python interpreter infers the type at runtime.

This flexibility is powerful but also requires a different mindset. Let's consult a resource that breaks this down.

[PDF] Python for C programmers

This document from Purdue University provides a concise comparison for C programmers learning Python.

Please read the section on "Variables and Types." Start from the initial comparison and continue through the examples showing how a variable x can be reassigned to different types. Pay close attention to the example of what happens when you try an illegal operation, like calling len() on a number.

This dynamic nature simplifies writing code, but it moves type-checking from compile-time to run-time.

Operators: Mostly Familiar Territory

The good news is that most operators you know from C work the same way in Python.

The six main comparison operators in Python, which are syntactically identical to their counterparts in C.

Arithmetic (+, -, *, /) and comparison (==, !=, <, >, etc.) operators are the same. The main difference lies in the logical operators. Instead of &&, ||, and !, Python uses the English words and, or, and not.

For example, a C condition like if (x > 0 && x < 10) becomes if x > 0 and x < 10 in Python. Notice the lack of parentheses, which are optional when they are not needed for grouping.

The Role of Indentation

As mentioned, Python uses indentation to group statements, whereas C uses curly braces. This is not just a stylistic suggestion; it is a strict syntactic rule. A block of code in a function, loop, or conditional statement must be indented relative to its parent statement. The standard convention is to use four spaces for each level of indentation.

Python and C - Comparisons and C - Rose-Hulman

This comparison table from Rose-Hulman Institute of Technology is an excellent cheat sheet for translating between C and Python. We will refer to it throughout the lesson.

In the table, find the rows for "Indentation and line breaks" and "A block of statements to be executed sequentially." Compare the Python and C columns for these two features. You can find them by looking for the keywords Indentation and A block of statements.


Translating Control Flow

With an understanding of indentation, we can now translate the control flow structures you are familiar with from C.

Conditional Statements (if, elif, else)

The logic is identical to C's if/else if/else, but the syntax changes.

  • if (...) becomes if ...:
  • else if (...) becomes elif ...: (a contraction of "else if")
  • else becomes else:

Let's see this side-by-side.

C Code:

if (x < 0) {
    printf("Negative");
} else if (x == 0) {
    printf("Zero");
} else {
    printf("Positive");
}

Python Code:

if x < 0:
    print("Negative")
elif x == 0:
    print("Zero")
else:
    print("Positive")

Note the colons (:) at the end of each conditional statement line and the indented blocks that follow.

The CS50 video you watched earlier also covers this. Let's revisit it for a quick visual reinforcement.

From C to Python by Ross Rheingans-Yoo

Let's quickly review the segment on conditionals.

Watch the short section explaining if, else, and the indented blocks, from the start of the if explanation.

Loop Structures (while and for)

while loops are a straightforward translation. The C syntax while (condition) { ... } becomes while condition: ... in Python.

for loops, however, represent a more significant conceptual shift. C's for loop is primarily a counter-based construct: for (i=0; i<10; i++). Python's for loop is designed to iterate over the items of any sequence, such as a list of numbers or characters in a string. This is often called a "for-each" loop in other languages.

To replicate the classic C-style counter loop, you use Python's built-in range() function.

  • range(10) generates a sequence of numbers from 0 up to (but not including) 10.
  • range(1, 11) generates a sequence from 1 up to 10.
  • range(0, 10, 2) generates a sequence from 0 to 10, incrementing by 2 (i.e., 0, 2, 4, 6, 8).

Let's see the comparison.

C Code:

int sum = 0;
for (int i = 1; i <= 10; i++) {
    sum += i;
}

Python Code:

sum = 0
for i in range(1, 11):
    sum += i

The "Python for C programmers" guide has a great section explaining this exact transition.

[PDF] Python for C programmers

Let's return to the Purdue guide to see how it explains control flow.

Focus on the "Control statements" section. Review the examples for If Statements and While Loops. Then, carefully read the entire subsection on For Loops, paying special attention to how it introduces the range() function to replicate C-style loops.


Defining and Using Functions

Functions in Python are defined with the def keyword. Like with variables, you do not specify the return type or the types of the parameters.

C Code:

int add(int a, int b) {
    return a + b;
}

Python Code:

def add(a, b):
    return a + b

A crucial concept in functions is scope—where variables live and can be accessed. You're familiar with this from C. Python handles scope through a system of namespaces. A function creates its own temporary local namespace for its parameters and any variables created inside it. When the function finishes, this namespace is destroyed. To send a value back to the main program, you use the return statement.

This next video offers a fantastic visual explanation of how Python defines, calls, and manages variables in functions.

Python Functions: Visually Explained

This video, "Python Functions - Visually Explained," provides a clear and animated breakdown of how functions work.

Please watch the entire video. It is broken down into intuitive chapters. Focus on: The basic syntax of def, parameters, and the function body (Defining and Calling). The difference between print inside a function and using return to send a value out (Return Statement). The explanation of global vs. local namespaces, which clarifies why variables inside a function are temporary (Variable Scope).


Let's Put It All Together

Now, let's consolidate everything we've learned by translating a simple C program that combines a function, a loop, and a conditional.

Here is a C function that calculates the sum of all even numbers from 0 up to a given number n.

C Code:




#include <stdio.h>

int sum_evens(int n) {
    int total = 0;
    for (int i = 0; i <= n; i++) {
        if (i % 2 == 0) {
            total += i;
        }
    }
    return total;
}

int main() {
    int result = sum_evens(10);
    printf("The sum is: %d\n", result); // Output: The sum is: 30
    return 0;
}

Your task is to write the equivalent Python code. Think about how to translate each piece:

  1. The sum_evens function definition.
  2. The for loop using range(). Remember that range(n) goes up to n-1.
  3. The if statement. The modulo operator % is the same in Python.
  4. The final call to the function and printing the result.

Take a moment to write your Python version before revealing the solution below.

Click to see the Python solution
def sum_evens(n):
    total = 0



    # We use n + 1 to make the range inclusive of n, matching the C loop's i <= n
    for i in range(n + 1):



        # The condition and assignment are very similar to C
        if i % 2 == 0:
            total += i
    return total




# Calling the function and printing the result
result = sum_evens(10)
print(f"The sum is: {result}") # Output: The sum is: 30

Conclusion

In this lesson, we have mapped the fundamental programming constructs from C to Python. You've seen that while the core logic remains the same, Python's syntax is often cleaner and more expressive.

Here are the key takeaways from our C-to-Python translation:

  • Syntax: Python uses colons (:) and indentation to define code blocks, not curly braces {}. Semicolons are not required.
  • Typing: Python is dynamically typed; you don't declare variable types.
  • Conditionals: if, else, and C's else if becomes elif.
  • Loops: while is very similar, but for loops are designed for iterating over sequences. The for i in range(n): pattern is the direct equivalent of C's for (int i=0; i<n; i++).
  • Functions: Defined with def, with no explicit return or parameter types. The return statement sends values back to the caller.

You've made the first crucial step in learning the language. By building on your C knowledge, you can bypass many of the initial hurdles that new programmers face.

In our next lesson, we will explore one of Python's most powerful features: its built-in data structures, particularly lists and dictionaries. These structures are the bread and butter of data manipulation and will be instrumental in every machine learning model you build.