Skip to content

1.2 Python to C

To learn C from a Python background, here are key steps to help you transition:

  • Understand Syntax Differences:

    • C is statically typed (you need to declare variable types), while Python is dynamically typed.
    • Example:
      int x = 10;
  • Memory Management:

    • C requires manual memory management using malloc() and free() for dynamic memory allocation, while Python handles this automatically.
  • Pointers:

    • C uses pointers to reference memory locations. Grasp how to use pointers and understand pointer arithmetic.
  • Functions and Libraries:

    • C standard libraries like <stdio.h> and <stdlib.h> are used for I/O and memory management. Functions need explicit return types and argument declarations.
  • Build Process:

    • C requires compiling with a compiler like gcc, while Python is interpreted. Learn to compile, link, and execute C code.
  • Debugging:

    • Unlike Python, C can lead to segmentation faults due to memory misuse. Learn to use debugging tools like gdb or valgrind.
  • Practical Projects:

    • Start with simple programs like basic calculators, file I/O operations, and eventually implement data structures.
  • Resources:

    • Books like “The C Programming Language” by Kernighan and Ritchie.
    • Online platforms like Learn-C.org or Exercism.

1. Hello World

Python C
def func ()
print ("Hello World!")
void func ()
{
printf ("Hello World!\n");
}

2. Use of Semicolon ;

The semicolon (;) is treated differently in Python and C:

In C:

  • Semicolon is required to terminate statements: Each statement in C must end with a semicolon to indicate the end of the command.

    Example:

    int x = 5; // Semicolon required
    printf("%d\n", x); // Semicolon required

    Without a semicolon, the compiler throws an error.

In Python:

  • No semicolons are required: Python uses newlines and indentation to define the end of a statement or block of code. Semicolons are optional but rarely used.

    Example:

    x = 5 # No semicolon needed
    print(x) # No semicolon needed
  • Optional use: You can use semicolons to write multiple statements on a single line, but this is not typical Python style.

    Example:

    x = 5; print(x) # Multiple statements on one line using a semicolon

3. User Input

Python C
def userInput ():
# Integer input
var_int = int(input ())
# Double ( real number )
var_dbl = float(input())
# String
var_str = input ()
void userInput ()
{
int var_int;
double var_dbl;
char var_str [101];
/* String with max length of
100 characters */
/* Integer */
scanf ("%d", &var_int );
/* Double */
scanf ("%f", &var_dbl );
/* String */
scanf ("%s", var_str );
/* `&` is not needed
since `var_str` an array */
}

3.1 Control Structures

Control structures are constructs in programming that dictate the flow of execution based on conditions, loops, and decision-making. They help manage how and when specific parts of the code are executed.

3.1.1 If Statement

  • Python: Uses indentation to define code blocks.
  • C: Uses braces {} to group code blocks
Python C
def func (a):
if a == 10:
print ("It is 10")
elif a > 10:
print (" Greater than 10")
else :
print ("Not high enough")
void func (int a)
{
if(a == 10)
{
printf ("It is 10");
}
else if(a > 10)
{
printf (" Greater than 10");
}
else
{
printf ("Not high enough ");
}
}

3.1.2 For Loop

  • Python: Uses for item in range().
  • C: Uses initialization, condition, and increment in a more explicit form.
Python C
def func ():
# 0 -10 Inclusive
for i in range (11):
print (i)
void func ()
{
/* 0 -10 Inclusive */
int i;
for (i = 0; i < 11; i++)
{
printf ("%d\n", i);
}
}

3.1.3 While Loop

  • Both languages use while, but C requires braces {} for blocks.
Python C
def func ():
var = 0
while var >= 0:
print ("Enter value")
var = int(input())
void func ()
{
int var = 0;
while ( var >= 0)
{
printf ("Enter value\n");
scanf ("%d", &var);
}
}

3.1.4 Swtich Statement

  • C: Includes switch-case for multi-branch decision-making, which Python doesn’t have directly.
Python C
# Note that python has no actual switch statement
def func ( grade ):
if grade == 'A':
print ("Excellent")
elif grade == 'B' or
grade == 'C':
print ("Well Done")
elif grade == 'D':
print ("You Passed")
elif grade == 'F':
print ("Try again")
else :
print ("Invalid Grade")
void func (char grade)
{
switch (grade)
{
case 'A':
printf ("Excellent");
break ;
case 'B' : case 'C':
printf ("Well Done");
break ;
case 'D':
printf ("You Passed");
break ;
case 'F':
printf ("Try again");
break ;
default :
print ("Invalid Grade")
}
}

3.1.5 Ternary Operator

  • Python: Uses conditional expressions, which are more readable but serve a similar purpose.
  • C: Supports the ternary operator ? :, a shorthand for if-else.
Python C
y = 10 if x > 5 else 0
int y = (x > 5) ? 10 : 0;

3.2 Function Calls

3.2.1 Main Function

Python C
if __name__ == " __main__ ":
print ("Argument Count:",
len(sys . argv ))
print ("Arguments:\n")
for arg in sys . argv :
print (arg)
int main (int argc , char * argv [])
{
int i;
printf ("Argument Count: %d\n",
argc );
printf ("Arguments:\n");
for (i = 0; i < argc ; i ++)
{
printf ("%s\n", argv [i]);
}
return 0;
}

3.2.2 Returning Values

Python C
def func3(x):
# Do something
pass
def func2():
return 5
def func1():
a = func2()
func3(a)
void func3(int x)
{
/* Do something */
}
int func2()
{
return 5;
}
void func1()
{
int a = func2();
func3(a);
}