A Brief Comparison of Python and C++ Syntax

These videos on algorithm analysis are well thought out and presented. At issue is that the simple code used for illustration is written in Python, a modern industrial language but not a prerequisite for this course. This page gives code snippets that compare Python with C++. C++ syntax is sufficiently similar to Java that you will readily see the relationship.

Brief Comparison of Python and C++ Syntax


The videos on algorithm analysis are well thought out and presented. At issue is that the simple code used for illustration is written in Python, a modern industrial language but not a prerequisite for this course. Shown below are code snippets that compare Python with C++. C++ syntax is suficiently similar to Java that you will readily see the relationship. CS101 is a prerequisit for this course so you are already familiar with C++ and Java.

Where C++ and Java use brackets, {...} to indicate code scope, Python uses indentation. For instance, code indented relative to "for" and "while" statements are within the scope of those statements only. The same is true of the "def" statement used to begin the definition of a function.

Here is function syntax written in Python compared to C++:

PYTHON FUNCTION SYNTAX

C++ FUNCTION SYNTAX

                

# The Function

def multiply(x, y):

  result = x * y

  return result

# Calling Statement

a = 3

b = 4

c = multiply(a, b)

print("Answer:", c)

                

// Necessary Setup

#include <iostream>

using namespace std;

// The Function

float multiply(float x, float y)

{

  float result;

  result = x * y;

  return result;

}

// Calling Statement

int main()

{

  float a, b, c;

  a = 3;

  b = 4;

  c = multiply(a, b);

  cout <<

"Answer: "<< c << "\n";

  return 0;

}



 Here is while-loop syntax in Python compare to C++:

PYTHON WHILE-LOOP SYNTAX

C++ WHILE-LOOP SYNTAX

                

a = 1

# While Loop

while a <= 5:

  print("Counter: ", a)

  a += 1

 

                

// Necessary Setup

#include <iostream>

using namespace std;

int main()

{

  int a;

  a = 1;

  // While Loop

  while (a <= 5)

  {

    cout << "Counter: " << a << "\n";

    a += 1;

  }

  return 0;

}

 

Here is for-loop syntax written in Python compared to C++:

PYTHON FOR-LOOP SYNTAX

C++ FOR-LOOP SYNTAX

                

# For Loop

for a in range(1, 6):

  print("Counter:", a)

 

 

                

// Necessary Setup

#include <iostream>

using namespace std;

int main()

{

  int a;

// For Loop

  for (a = 1; a < 6; a++)

  {

    cout << "Counter: " << a << "\n";

  }

  return 0;

}

 


Source: Peter Raeth
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.

Last modified: Thursday, May 20, 2021, 4:20 PM