Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert Vba to Python
#1
How would this statement in Vba For divisor = 2 to number /2
Next Divisor be converted to Python?
Reply
#2
That depends. What does it do?
Reply
#3
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
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020