Python — C++ — 4

Structs and Classes

Alright! where finally here! Structs are (as the name implies) a structure of different values, for example, integers. Classes are also like a structure or a “class”. They can also store different values, just like a struct.

One thing to note about structs and classes is that you can store values of different types in it, even in C++, but you can’t add more values later. Think of it as a box that has room to store, say, 2 integers and 1 string. If you have this box, you can only add at most 2 integers and only 1 string, you cant swap one of the integers for a string and you can’t add more strings, you can only change the original 2 integers and the 1 string.

Struct-box
Illustration 1: Struct box visualization

Python classes

In python, there are really no structs, although there are classes, which are the same thing as structs, they just have a different name. The syntax for python classes is as follows.

class name: # create a class named "name"
    def __init__(self):
        self.x = 10
        # the "self." before "x" (the variable name) is required,
        # (otherwise it is deleted when the class is created)
        self.y = "Hello, World!"

In python, you can also pass in parameters, for example.

class example:
    def __init__(self, x): # adding parameters to the init function
        self.x = x # set "self.x" to the value passed in as "x"

Classes and Structs in C++

C++ has both classes and structs, although they are pretty much the same. Usually, structs are used for simpler structures of values, and classes are used for complicated structs with functions, although you can have functions in structs, too.

This is how you create a struct in C++

struct Car {
    int x;
}; // note the semicolon

Example programs

Structs are useful if you have a program that, for example, stores models of cars. Then you could create a “Car” struct with an integer value “age” and a string called “name”. Here is the example program.

# main.py
class Car:
    def __init__(self):
        self.age = 0 # you have to set default value in python
        self.name = "" # you have to set default value in python

my_car = Car()

my_car.age = 5
my_car.name = "volvo"
// main.cpp
#include  // for std::string

struct Car {
    int age; // create the age integer
    std::string name; // create the name string
}; // you have to add a semicolon att the end here

int main() {
    Car my_car;

    my_car.age = 5;
    my_car.name = "volvo";
}

Then we could create a list or vector to store many cars.

# main.py

...
insert the Car class here
...

my_car = Car()
all_cars = [] # create list of cars

for i in range(10):
    my_car.age = int(input("Please enter car age:  ")) # set car age
    my_car.name = input("please enter car name: ") # set car name
    
    all_cars.append(my_car) # add car to list of all cars

// main.cpp
#include 
#include 
#include 

...
insert the Car struct here
...

int main() {
    Car my_car;
    std::vector<Car> all_cars; // create vector of all cars
    
    int age_input;
    std::string name_input;
    for (int i = 0; i < 10; i++) { // loop 10 times to get 10 cars
        std::cout << "please enter car age" << std::endl;
        std::cin >> age_input; // get age input
        std::cout << "please enter car name" << std::endl;
        std::cin >> name_input; // get name input

        my_car.age = age_input; // set my_car's age
        my_car.name = name_input; // set my_car's name
        
        all_cars.push_back(my_car); // add my_car to all_cars
    }
}

If you want to see more of this, or maybe something else programming related, feel free to comment down below about anything you’d like me to cover. If you want more programming things, check out hmicode.wordpress.com (yes, I know I’m kinda spamming it… so sorry for linking to it twice in a row 🙂) I might write something about Rails on that site, so keep an eye out for that 🙂

← previous

Advertisements

Python — C++ — 3

Functions

Alright! Let’s get into functions! How about I just show you how it works, here:

# main.py

# def keyword starts a function, then comes the name and arguments
def add(a, b):
    # return the added values
    return a + b

print(add(5, 3))


// main.cpp

#include  // for std::cout

/* a function is created by first writing the return type, int
in this case, then write the function name and then the arguments,
but you have to declare the type of each argument */
int add(int a, int b) { // open the function body
    // return a + b
    return a + b;
} // close the function body

// and then open the main function
int main() {
    std::cout << add(5, 3) << std::endl;
}

So, once again, C++ requires you to specify the variable type, but it’s overall kinda similar to the python function.

One cool thing with functions in C++ is that this function:

int add(int a, int b);

is not the same as this one:

int add(float a, float b);

meaning you can have multiple versions of a function depending on what attribute types are passed into it! However, you can not change the return type.

I’m gonna end this post right about here, but I’ll make a new one soon (I think🙂) that will talk about structs and classes, so stick around for that one!

Also, if you have any questions or anything, please comment down below 🙂

← previousnext →

python — C++ — 2

Ok, in this post we’re gonna cover some basic loops and if statements, so let’s get started!

Part1 — If statements

If statements in C++ are very similar to those in python.

# main.py

num_1 = input()
num_2 = input()
if num_1 == num_2:
    print(num_1, 'and', num_2, 'are the same.')
// main.cpp

#include  // for std::cout

int main() {
    int num_1;
    int num_2;
    std::cin >> num_1 >> num2;
    if (num_1 == num_2) {
        std::cout << num_1 << " and " << num_2
            << " are the same." << std::endl;
    }
}

Part2 — Loops

Loops can be used for repeating code many times or to loop through, for example, an array.

While loops in C++ are just like python’s for loops, although the syntax is a little different, here’s an example.

# main.py

var = 0
# true in python starts with a upercase letter
while True:
    var += 1
    if var > 10:
        break
// main.cpp

int main() {
    int var = 0;
    // Note that C++ requires parentheses after a while statement
    while (true) {   // true in C++ starts with a lowercase letter
        var++; // is equivalent to var += 1;
        
        // Again note that the parentheses are required
        if (var > 10) {
            break;
        }
    }
}

For loops, on the other hand, are different in C++ and python, here are 2 different programs in Python and C++ that do the same thing:

# main.py

list = [1, 2, 3, 4, 5] # create a list called 'list'
for item in list:
    print(item)        # print each item
// main.cpp

#include  // for std::cout
#include    // include the std::vector class

int main() {
    // create a vector of ints called 'list'
    std::vector<int> list = {1, 2, 3, 4, 5};

    for (int i = 0; i < list.size(); i++) {
        std::cout << list[i] << std::endl;
    }
}

Note the std::vector class? We will cover that in more detail in a later post. Everything you have to know about it now is:

  1. They are statically typed:
    • This means that you have to set a type that this vector can contain, and then you can only add values of that type to that vector, for example:
    • std::vector<int> vector; // creates a vector with only ints
  2. .size()
    • returns the number of elements of the vector.
    • list.size(); // returns the number of elements in list

← previousnext →

python — C++

Ok, let’s get started with C++.

This post is mostly for people who know python but don’t know C++.

Introduction — Things to know before you get started

Some things you have to know when you start with C++ is that it is astatically typed language. This means that you have to specify what kind of value a variable has. But it also means that you can’t change what type it is, for example, look att code-box 1 bellow, we create a python variable that holds a number (or int) and then is assigned a string. Recreating this in C++ is not possible because it is statically typed, although I will not get into that in this post.

# main.py
var = 10      # assign the integer 10 to the variable var
var = 'Hello' # assign the string 'Hello' to the variable var

code-box 1   —   this program is hard to recreate in C++ and requires the use of templates

Part 1 — Main

In python, you may know, there is no main function, everything you write in your file will be run. But in C++ however, when you run a program, only your main function will be called.

Your first program:

Let’s compare a “Hello, World!” program in python and C++.

I have written some notes in the program which I recommend you to read.

# main.py

print('Hello, World'!)
// main.cpp

#include  // Include the iostream lib (for std::cout)
// Note: C++ does not use '#' for comments, it uses '//'
// '#' is used for the include command (it's like python's import)

// Create the main function. Note the 'int' in front of it,
// it tells the program that this function returns an integer.
// Everything between the '{' and '}' are inside the function
int main() {
    std::cout << "Hello, World!" << std::endl;
}

Part2 — Compiling

As you might know, python is an interpreted language. This means that the computer runs a program that is made to run python files. what this program does is that it reads your file and then tells the computer what to do.

C++, on the other hand, is a compiled language, meaning it has a compiler that translates your C++ file to machine language. This has the advantage over interpreters that it is much faster. This is because the computer does not have to translate the program to machine code every time it runs, only once when it is compiled.

In order to compile your program, you have to have a compiler installed.

If you run a Linux system, you probably already have  g++ installed, you can try it out by opening a terminal and writing ‘g++’. If you have it installed, you can run ‘g++ main.cpp -o main’ and then it will compile your program for you. You can run this new file by typing ‘./main’ in the terminal

If you have a windows or a mac, or if you have a Linux, but g++ did not work for you, I would recommend Code::blocks. To install code::blocks, go to codeblocks.org and go to their downloads page. here’s codeblock’s wiki on how to install it: tutorial.
next →

python – Ruby – start

OK, let’s get started with our python to Ruby / Ruby to python page.

Strings:

syntax:

python:

string = "My string"   ->   "My string"
string = 'My string'   ->   'My string'

Ruby:

string = "My string"   ->   "My string"
string = 'My string'   ->   'My string