Porting from Python to C#

Decided to work on porting at least part of the Python program I had done with the video on Youtube into C#, and am really happy with getting the original core part working.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TryingStuff1
{
    class Program
    {
        static void Main(string[] args)
        {
            string user_input= "";

            while (user_input != "quit")
            {
                int calculation_to_units = 24;
                string name_of_unit = "hours";
                
                Console.Write("Enter the number of days.  Enter 'quit' to exit the program: ");
                user_input = Console.ReadLine();
                Console.Clear();
                if (user_input.ToLower() == "quit")
                {
                    System.Environment.Exit(0);
                }
                else if (int.TryParse(user_input, out int number))
                {
                    int user_input_int;
                    if (int.Parse(user_input) <= 0)
                    {
                        Console.WriteLine("Please enter a positive integer.");
                    }
                    else
                    {
                        user_input_int = int.Parse(user_input);
                        int total_time = user_input_int * calculation_to_units;
                        string conversion_output = String.Format("{0} days are {1} {2}", user_input_int, total_time, name_of_unit);
                        Console.WriteLine(conversion_output);
                        continue;
                    }
                }
                else
                    Console.WriteLine("Please enter an integer or 'quit'.");
            }
        }
    }
}

Code language: C# (cs)

The C# code does not have the functions like the Python code, or the sets being used, but is still doing almost all of the same work.

#! /bin/python

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(validated_days):
    try:
        print(days_to_units(int(validated_days)))
    except ValueError:
        print("Please enter a positive integer value...")

user_input = 0
while user_input != "quit":
    user_input = input("""Enter the number of days (comma separated lists are accepted (e.g. 10, 20, 30).\nEnter 'quit' to exit the program: """)
    if user_input.lower() == "quit":
        quit()
    list_of_days = user_input.split(", ")
    for num_of_days in set(list_of_days):
        validate_and_execute(num_of_days)
Code language: Python (python)

Moving functions to modules.

Learned how to move the functions in my little program out to a separate module file, and then call the functions inside of it as needed. Nice thing is that you do not have to actually import any functions that you do not need, such as ones that are only used by other functions in the same module.

The main part of the program below calls the function validate_and_execute, as well as the variable user_input_message, from the helper.py file in the functions sub-directory.

from functions.helper import validate_and_execute, user_input_mesage
#import functions.helper

user_input = 0
while user_input != "quit":
    user_input = input(user_input_mesage)
    if user_input.lower() == "quit":
        quit()
    days_and_unit = user_input.split(":")
    #print(days_and_unit)
    days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
    #print(days_and_unit_dictionary)
    validate_and_execute(days_and_unit_dictionary)
Code language: Python (python)

The file below is the actual helper.py file.

def days_to_units(number_of_days, conversion_unit):
    if conversion_unit == "hours":
        calculation_to_units = 24
    elif conversion_unit == "minutes":
        calculation_to_units = 24*60
    else:
        return("Invalid conversion unit...")
        
    if number_of_days > 0: 
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {conversion_unit}."
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(days_and_unit_dictionary):
    try:
        print(days_to_units(int(days_and_unit_dictionary["days"]), str(days_and_unit_dictionary["unit"])))
    except ValueError:
        print("Please correct your input...")

user_input_mesage = """Enter the number of days and conversion to unit (10:minutes or 20:hours).\nEnter 'quit' to exit the program: """
Code language: Python (python)

Pretty cool stuff, and can see how it would make the code more organized.

Using Dictionaries in Python

I have updated the program that I have been writing while following the video I have been watching. I am still having to do some of my own tinkering, as my code is structured slightly different than the one in the video, but works mostly the same, and has a little more entry validation in it. I am pretty sure it could use some more cleaning up, as evolving code usually does, but that can wait until later.

def days_to_units(number_of_days, conversion_unit):
    if conversion_unit == "hours":
        calculation_to_units = 24
    elif conversion_unit == "minutes":
        calculation_to_units = 24*60
    else:
        return("Invalid conversion unit...")
        
    if number_of_days > 0: 
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {conversion_unit}."
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    try:
        print(days_to_units(int(days_and_unit_dictionary["days"]), str(days_and_unit_dictionary["unit"])))
    except ValueError:
        print("Please correct your input...")

user_input = 0
while user_input != "quit":
    user_input = input("""Enter the number of days and conversion to unit (10:minutes or 20:hours).\nEnter 'quit' to exit the program: """)
    if user_input.lower() == "quit":
        quit()
    days_and_unit = user_input.split(":")
    #print(days_and_unit)
    days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
    #print(days_and_unit_dictionary)
    validate_and_execute()
Code language: Python (python)

More learning the differences…

Decided to start doing small projects to see the differences in how C, C++, C# and Python handle doing the same thing. Started off with a simple enter your name, and then print Hello and the name, since that is one of the more basic things that everyone should know how to do.

// C
#include <stdio.h>
int main()
{
    char name[40];
    printf("Enter your name please: ");
    scanf("%s",name);
    printf("Hello %s.\n", name);
    return 0;
}
Code language: C++ (cpp)
// C++
#include <iostream>
using namespace std;

int main() 
{
    string name;
    cout << "Enter your name please: ";
    cin >> name;
    cout << "Hello " << name << ".\n";
    return 0;
}
Code language: C++ (cpp)
// C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace print_enter
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;
            Console.Write("Enter your name please: ");
            name = Console.ReadLine();
            Console.WriteLine("Hello {0}.\n", name);
        }
    }
}
Code language: C# (cs)
# Python
username = input("Enter your name please: ")
print("Hello " + username + ".")
Code language: Python (python)

Adding list entry to the Python script

Next up is adding the ability to enter a comma separated list to the script, so that multiple values can be processed at once. The list will still be validated, and if there are values that are not positive integers they will be ignored.

calculation_to_units = 24
name_of_unit = "hours"


def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(validated_days):
    if validated_days == "quit":
        quit()
    try:
        print(days_to_units(int(validated_days)))
    except ValueError:
        print("Please enter a positive integer value...")

days_entry = 0
while days_entry != "quit":
    days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
    for num_of_days in days_entry.split(","):
        validate_and_execute(num_of_days)
Code language: Python (python)

Even more Python in the mix

Added a very simple while loop to the script, as well as a check for the word ‘quit’ which will exit the program cleanly. It will still catch any negative, 0, string or null (enter key with no value) and prompt to enter an integer again.

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    days_entry = 0
    try:
        days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
        print(days_to_units(int(days_entry)))
    except ValueError:
        if days_entry == "quit":
            quit()
        else:    
            print("Please enter a positive integer value...")

while True:
    validate_and_execute()
Code language: Python (python)

Getting the hang of Python

Following a Python video on Youtube, and think I am doing pretty good so far. Finally got the following compacted as much as I can do for now, but really happy with it.

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    try:
        days_entry = int(input("Enter the number of days: "))
        print(days_to_units(days_entry))
    except ValueError:
        print("Please enter a positive integer value...")

validate_and_execute()
Code language: Python (python)

The differences between languages…

I’ve been learning how a few different languages can do the same task, so decided to put up the examples below.

#!/usr/bin/python

number = 5
counter = 1
while (counter <=10):
    if counter < number:
        print (counter, ' is less than ', number)
    elif counter == number:
        print (counter, ' equals ', number)
    else:
        print (counter, ' is greater than ', number)
    counter = counter + 1
Code language: Python (python)
#powershell

$numValue = @(1..10)
$counter = 0

while ($counter -lt $numValue.length){
if ($numValue[$counter] -lt 5){
    write-host "Less than`n"
}
elseif ($numValue[$counter] -eq 5) {
    write-host "Equal`n"
}
else {
    write-host "Greater than`n"
}
$counter += 1
}Code language: PowerShell (powershell)
//C++
#include <iostream>
using namespace std;

int main()
{
    int counter = 1;
    while (counter <= 10) {
        if (counter > 5) { cout << "Greater than\n"; }
        else if (counter == 5) { cout << "Equal\n"; }
        else { cout << "Less than\n"; }
        counter++;
    }
    system("pause>0");
}

Code language: C++ (cpp)