Python and C - Comparisons and Contrasts

This document describes some corresponding features (or lack of corresponding features) in Python and C.
It is a work in progress.We welcome comments or suggestions (especially suggestions for additional entries) from students

Sample Code:

# Simple Python program

year = 2007
print "Hello World!" 
print "CSSE 120 changed a lot in %d." % (year)}
/* Simple C program */

#include <stdio.h>

int main() {
	int year = 2007;
	printf("Hello World!\n"); 
	/* Notice that C's printf does not automatically put in a newline */
	printf("CSSE 120 changed a lot in %d.\n", year);
	return 0;
}
Concept/feature Python C Comments
case-sensitivity is case-sensitive.  Y is not the same as y. is case-sensitive.  Y is not the same as y. Python and C are the same here.
In both languages, the names of standard functions are usually all lower-case.
Eclipse - creating source files New .. PyDev module.  Do not put the .py on the module name New ... C Source file.  You must put the .c at the end of the file name.  
Eclipse - running programs right-click the file you want to run right-click the project you want to run Python: Can run any file in the project
C: Must have one and only one source code file in the project that defines a main() function.
Where does execution start? Executes the code in order from beginning to end of the file.
main() is optional, and has no special meaning in Python.
Executes the body of main() and anything that main() calls. That means that C starts in the file in the project containing main(), but main() can call functions from other files.
Comments From # to the end of the line Begin with /* and end with */, may span multiple lines. C comments may not be nested. The following is illegal:
/* cannot have /* comment inside */ comment */

Many C compilers(including ours) allow single-line comments that begin with //

Semicolons at the end of simple statements Allowed, but only needed between two statements on the same line. Required, as in
x = f(a, b);
 
Indentation and line breaks essential to the syntax of the language ignored by the compiler It's still a good idea to have good, consistent indentation.
Using code form other files import module or from module import * #include <stdio.h>  or #include "myHeader.h"  
Variable types Variables are untyped; a given variable (label) can be stuck on values of different types at different times during the execution of a program. The type of a variable must be declared when it is created, and only values of that type can be assigned to it. In C, we may not write x = 5.6; unless x has been previously declared:
double x; 
...
x = 5.6;             /* legal */
x = "String value"; 
/* This is illegal in C;
   types don't match*/
Variable declaration with assignment. Python has no declarations int n = 5;
double x=7.3, y=8.2, z;
All variable definitions inside a function definition must occur at the beginning of a block of code, before any other statements.
Simultaneous assignment x, y = 3, x-y   Not allowed in C
chained assignments x = y = 0 x = y = 0;  
Assignment with operators x += 2 x += 2; Identical in Python and C
Increment operator   x++;    ++x; Not available in Python. 
Exponentiation operator  x**3   No exponentiation operator in C: instead, use pow(x,3) defined in <math.h>
comparison operators <  <=    >  >=  ==  != <  <=    >  >=  ==  !=  
Boolean values False True 0 1 Actually, in C, any non-zero value is considered to be a true value, and zero false. There is no special Boolean type in C.

Digging a little bit deeper into Python shows that False and True also mostly behave like the integers 0 and 1:
>>> False + 1
1
>>> True - False
1
>>> True == False + 1
True
>>> type(True)
<type 'bool'>
>>> type(False + 1)
<type 'int'>

Boolean operators and  or  not  &&  ||  ! The meanings are essentially the same, but the notation is different. We say "essentially" because the C operators produce integer values instead of special True and False values.
for loop standard form sum = 0
for i in range(5):
   sum += i
   print i, sum
int i, sum=0;
for (i=0; i<5; i++) {
   sum += i;
   printf("%d %d\n", i, sum);
}
These two programs do the same thing.
More details of for loop syntax for <variable> in <list:>:
     <one or more indented statements>
for (<initialization> ; <test>; <update>) {
       <zero or more body statements>
}
initialization: usually gives initial value to loop variable(s)
test:  If the value of the test is true, the loop continues.
update:  After each execution of the loop body, this code is executed, and the test is run again.
A block of statements to be executed sequentially indicated by indentation level surrounded by { ... } In C, a block can be used anywhere a single statement can be used.
refined C for-loop definition   for (<initialization> ; <test>; <update>)
       <statement>
Parentheses required. <statement> may be a single statement or a block of statements surrounded by { ... }
do-nothing statement pass ; In C, a single semicolon with nothing in front of it, indicates an empty statement.  Just like Python's pass, used where the syntax requires a statement, but there is nothing to do there.
while loop syntax while <condition>:
    <one or more indented statements> 
while ( <condition> )
       <statement>
<statement> may be a single statement or a block of statements surrounded by { ... }
break statement break break; immediately end the execution of the current loop
continue statement continue continue; immediately end the execution of this time through the current loop, then continue the loop's next execution.
basic if syntax if <condition>:
    <one or more indented statements> 
if ( <condition> )
       <statement>
Parentheses required. <statement> may be a single statement or a block of statements surrounded by { ... }
if with else if <condition>:
    <one or more indented statements> 
else:
    <one or more indented statements> 
if ( <condition> )
       <statement>
else
  
 <statement>
As in above cases, <statement> may be a single statement or a block of statements surrounded by { ... }
if with multiple cases if <condition>:
    <one or more indented statements> 
elif
<condition>:
    <one or more indented statements> 
else:
    <one or more indented statements> 
if ( <condition> )
       <statement>
else if ( <condition> )
       <statement>
else
  
 <statement>
C has no special syntax that is similar to Python's elif
switch statement.  Test a simple variable (for example, an integer), and choose which block of code to execute based on its value.  If none of the specific cases match, execute the default code.  If no default code and no cases match, do nothing.   switch (<variable>) {
  case
<value1> :
    
<statement1>
          break;
  case <value2> :
    
<statement2>
          break;
   ...
    default:
       <statement>
Python has nothing that is like C's switch statement. 

If there are multiple statements for a given case, no curly braces are needed. 

Don't forget the  break; at the end of each case (except the last)

long integer types Basic int type is 32-bit;  if an operation produces a value too big for int, a long value (which can be an arbitrarily large integer) is automatically produced. int type is typically 32-bit.
long type is typically 64 bit. 
no automatic conversion of values.
C does not have a built-in type that represents arbitrarily large integer values
constant array or list initialization numList = [1, 3, 5, 7, 9] int numlist[] = {1, 3, 5, 7};  
list/array element assignment. numList[2] = 8 numList[2] = 8;  
array/list operators numList.append(5), numList.pop() C has no comparable array operations. We would need to write our own versions of pop() and append(), using malloc() for C arrays
simple function definition

from math import *

def printRootTable(n):
  for i in range(1,n):
    
print " %2d  %7.3f" % (i, sqrt(i))

def main():
    printRootTable(
10)

main()

#include <stdio.h>
#include
<math.h>

void printRootTable(int n) {
 
int i;
  
for (i=1; i<=n; i++) {
    printf(
" %2d  %7.3f\n", i, sqrt(i));
  }
}

int main() {
      printRootTable(10);
     
return 0;
}

If a C function  does not return a value, you must declare its return type as void.
reading numbers as input m,n = input("Enter two numbers: ")
print m, n

int m, n;
printf(
"Enter two numbers: ");
fflush(stdout);
/* needed due to
                  an Eclipse bug 
                */

scanf(
"%d %d", &m, &n);
printf(
"%d %d\n", m, n);

If you don't use the & (address-of) operator, for each variable, it will not work.
iterating over arrays using indexing
nums = [1, 2, 3, 4, 5]
for i in range(len(nums)):
	nums[i] *=2
int size = 5;
int nums[] = {1, 2, 3, 4, 5};
int i;
for (i=0; i < size; i++) {
	nums[i] *= 2;
}
The pointer iteration below might be faster, but using indexing as shown in this row is much less error prone.
iterating over arrays using pointers No real equivalent in Python.
int size = 5;
int nums[] = {1, 2, 3, 4, 5};
int *p;
int *last = p + size;
for (p=nums; p < last; p++) {
	*p += 1;
}
If you do much C programming in the future, you will probably see code that uses pointers to ints, like p here, to loop over arrays. See the slides on Arrays and Pointers for more details.