From Architecture to IT

Programming Language Syntax: Python & C Comparison

Because I first learned Python and then I wanted to learn C, I found it very difficult to even have a basis for comparison between the 2. So here it is, a side by side syntax comparison between Python and C !

A few mentions before we start: in C, you first include libraries, but then everything is written in the function “main”: for example : int main(){your code here}. Indentation is fundamental in Python, while in C it only matters as a coding Style ( you can read it easier). C has extra syntax because it has Pointers and Memory allocation and de-allocation, whilst Python resolves these problems automatically. C has extra variable types as well ( char, int, float, long, double, etc)

 

 PythonC
Descriptions## This is a description// This is a description
print “Hello”print('Hello, World!')// Everywhere where we have a print function , we have to
// include this library:
#include <stdio.h>
printf ( "Hello, World! \n" ) ;
For loop
for i in range(0,n):
print('Hello, World!')
#include <stdio.h>
for (int i=0; i<n, i++){
printf ( "Hello, World! \n" ) ;
}
While loop
while n < 5:
print('Loop number: ', n)
n = n + 1
#include <stdio.h>
int n = 0;
while ( n < 5 ){
printf("Loop number: %d\n", n);
n++;
}
If else
statements
if n <= 5:
print('n is less or equal to 5')
else:
print('n is bigger than 5')
if ( n <= 5 ){
printf ( "n is less or equal to 5\n" );
}else{
printf ( "n is bigger than 5\n" );
}
List
declaration
## Lists can hold any type of data,
## even other lists or dictionaries
aList = [4, 73, 'aWord', 'txt']
// A list can contain either integers, either chars,
// but not combined!
int aList[] = {400, 2, 3, 7, 50};
List
access
## Gets the item at index 1 and stores it in
## firstNum
firstNum = aList[1]
// Same Syntax
firstNum = aList[1];
Strings## Pyhton knows that greeting is a string
greeting = 'Hello'
// String is actually an array of type ‘char’
// Can be also: char hello[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
char greeting[] = "Hello";
String
Concatenation
txt1 = 'Hello '
txt2 = 'World'
greeting = txt1 + txt2
char txt1[] = "Hello ";
char txt2[] = "World";
char greeting[] = strcat( txt1, txt2)
String Lengthlen(greeting)strlen(greeting)
String
Compare
if (txt1 == txt2):
print('The texts are the same!')
if ( strcmp( txt1, txt2 ) == 0 ){
printf ( "The texts are the same!\n" );
}
Functions
def sum(num1, num2):
result = 0
result = num1 + num2
return result
int sum(int num1, int num2) {
int result = 0;
result = num1 + num2;
return result;
}
 

 

 

error: Content is protected !!