Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
First steps with Python.NET
#2
Another example.
  1. Get first number from the user (as string).
  2. Convert to double.
  3. Get second number from the user (as string).
  4. Convert to double.
  5. Create Python scope.
  6. In scope, define a Python function 'add'.
  7. Create C# var 'sum', equal to the return value of scope.add(firstNumber, secondNumber).
  8. Print 'sum'.
 
Code:
Copy      Help
/*/ nuget PyNet\PythonNet; /*/
using Python.Runtime;

PythonEngine.Initialize();
using (Py.GIL()) {
    // NOTE: this doesn't validate input
    if (!dialog.showInput(out string firstCsharpNumber, "Enter first number:")) return;
    PyObject firstNumber = Convert.ToDouble(firstCsharpNumber).ToPython();
    
    if (!dialog.showInput(out string secondCsharpNumber, "Enter second number:")) return;
    PyObject secondNumber = Convert.ToDouble(secondCsharpNumber).ToPython();
    
    dynamic scope = Py.CreateScope();
    scope.Exec("def add(a, b): return a + b");
    var sum = scope.add(firstNumber, secondNumber);
    print.it("Sum: " + sum);
}
PythonEngine.Shutdown();


Messages In This Thread
First steps with Python.NET - by burque505 - 06-17-2023, 09:16 PM
RE: First steps with Python.NET - by burque505 - 06-17-2023, 10:23 PM
RE: First steps with Python.NET - by Gintaras - 06-18-2023, 05:58 AM
RE: First steps with Python.NET - by burque505 - 06-18-2023, 12:27 PM
RE: First steps with Python.NET - by Gintaras - 08-01-2023, 06:38 PM
RE: First steps with Python.NET - by Gintaras - 08-01-2023, 06:40 PM
RE: First steps with Python.NET - by burque505 - 08-01-2023, 07:42 PM
RE: First steps with Python.NET - by Davider - 01-29-2024, 01:10 AM
RE: First steps with Python.NET - by Gintaras - 01-29-2024, 09:15 AM
RE: First steps with Python.NET - by Davider - 01-29-2024, 01:49 PM

Forum Jump:


Users browsing this thread: 6 Guest(s)