Python Forum
Convert Vba to Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Convert Vba to Python (/thread-9589.html)



Convert Vba to Python - jackhj - Apr-17-2018

How would this statement in Vba For divisor = 2 to number /2
Next Divisor be converted to Python?


RE: Convert Vba to Python - nilamo - Apr-17-2018

That depends. What does it do?


RE: Convert Vba to Python - ljmetzger - Apr-19-2018

Quote:How would this statement in Vba For divisor = 2 to number /2

The VBA statement is probably not correct because:
a. The '/' division operator is usually used for floating point math and 5/2 becomes 2.5 (and you probably want 3).
b. The '\' symbol is used for integer division and rounds down (e.g. 19\10 becomes 1, similar to the '//' division operator in Python 2 and Python 3).
NOTE: Python 3 uses floating point results which would generate a Traceback error if the '/' operator were used.


Sub BadExample()
    'Excel VBA code - not Python code
    number = 9
    For divisor = 2 To number / 2
        Debug.Print divisor   'Output to Immediate Window ('Ctrl G' in the debugger)
    Next divisor
End Sub
Output:
2 3 4
You probably want in VBA:
Sub GoodExample()
    'Excel VBA code - not Python code
    number = 9
    For divisor = 2 To (number + 1) \ 2
        Debug.Print divisor   'Output to Immediate Window ('Ctrl G' in the debugger)
    Next divisor
End Sub
Output:
2 3 4 5

In Python:
a. Variables are case sensitive.
b. for loops stop prior to the last index.
c. Values inside the range() function MUST be integers.

Python equivalent code would be (works in both Python 2 and Python 3):
number = 9
hi_index = (number + 3) // 2
print("hi_index = {}".format(hi_index))
#
for divisor in range(2, hi_index):
    print("divisor = {}".format(divisor))
Output:
hi_index = 6 divisor = 2 divisor = 3 divisor = 4 divisor = 5
Lewis