├── CONTRIBUTING.md ├── LICENCE.md ├── README.md ├── cover.png ├── images ├── cover.jpg ├── geany.png ├── msword-paragraph.png └── vba-references.png ├── learn.md ├── meta.yml ├── overview.md ├── software.md ├── software.yml └── worksheet.md /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | All contributions are assumed to be licensed under the same license as the source, i.e. CC BY-SA. This license must remain in all derivatives of this work. 4 | 5 | ## Issues 6 | 7 | If you find a mistake, bug or other problem, please [open an issue](https://github.com/raspberrypilearning/python-for-vb-programmers/issues) in this repository. 8 | 9 | ## Pull Requests 10 | 11 | If you fix a mistake, bug or problem or have something to contribute, please create a pull request for each modification. Please consider grouping modifications sensibly, i.e. don't bundle typo fixes in the same pull request as code changes, instead file them separately. 12 | 13 | Please note that sometimes things are done for pedagogical reasons so changes which make sense from a software engineering perspective (reducing duplication or making use of more advanced programming language features) may not be suitable to maintain the intended educational value. 14 | 15 | ## Derivatives 16 | 17 | The licence must remain in all derivatives of this work. 18 | 19 | ## Licence 20 | 21 | Unless otherwise specified, everything in this repository is covered by the following licence: 22 | 23 | ![Creative Commons License](http://i.creativecommons.org/l/by-sa/4.0/88x31.png) 24 | 25 | ***Python for Visual Basic Programmers*** by the [Raspberry Pi Foundation](http://raspberrypi.org) is licenced under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). 26 | 27 | Based on a work at https://github.com/raspberrypilearning/python-for-vb-programmers 28 | 29 | -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | # Licence 2 | 3 | Unless otherwise specified, everything in this repository is covered by the following licence: 4 | 5 | ![Creative Commons License](http://i.creativecommons.org/l/by-sa/4.0/88x31.png) 6 | 7 | ***Python for Visual Basic Programmers*** by the [Raspberry Pi Foundation](http://raspberrypi.org) is licenced under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). 8 | 9 | Based on a work at https://github.com/raspberrypilearning/python-for-vb-programmers 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python for Visual Basic programmers 2 | 3 | **This is an archived resource.** The repo will remain available but the resource will no longer be maintained or updated. Some or all parts of the resource may no longer work. To see our latest resources, please visit [raspberrypi.org](http://www.raspberrypi.org). 4 | 5 | A Python introduction for Visual Basic programmers. 6 | 7 | ![](./images/cover.jpg "Cover") 8 | 9 | ## Worksheet 10 | 11 | - [Worksheet](worksheet.md) 12 | -------------------------------------------------------------------------------- /cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raspberrypilearning/python-for-vb-programmers/7f6e8782e08b4f7518ef14ce4c811c91c8ce669f/cover.png -------------------------------------------------------------------------------- /images/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raspberrypilearning/python-for-vb-programmers/7f6e8782e08b4f7518ef14ce4c811c91c8ce669f/images/cover.jpg -------------------------------------------------------------------------------- /images/geany.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raspberrypilearning/python-for-vb-programmers/7f6e8782e08b4f7518ef14ce4c811c91c8ce669f/images/geany.png -------------------------------------------------------------------------------- /images/msword-paragraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raspberrypilearning/python-for-vb-programmers/7f6e8782e08b4f7518ef14ce4c811c91c8ce669f/images/msword-paragraph.png -------------------------------------------------------------------------------- /images/vba-references.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/raspberrypilearning/python-for-vb-programmers/7f6e8782e08b4f7518ef14ce4c811c91c8ce669f/images/vba-references.png -------------------------------------------------------------------------------- /learn.md: -------------------------------------------------------------------------------- 1 | By reading this resource you will learn: 2 | 3 | - How to set up a Python programming environment 4 | - What indentation is for 5 | - The equivalent Python for Visual Basic: 6 | - Data types 7 | - Arithmetic operators 8 | - Comparison operators 9 | - While loops 10 | - For loops 11 | - Collections and arrays 12 | - Functions 13 | - Error handling 14 | - Object oriented programming 15 | - How to handle libraries and references (e.g. DLLs) 16 | 17 | This resource covers elements from the following strands of the [Raspberry Pi Digital Making Curriculum](https://www.raspberrypi.org/curriculum/): 18 | 19 | -------------------------------------------------------------------------------- /meta.yml: -------------------------------------------------------------------------------- 1 | title: Python For Visual Basic Programmers 2 | category: learn 3 | -------------------------------------------------------------------------------- /overview.md: -------------------------------------------------------------------------------- 1 | This introduction is intended to help a Visual Basic programmer apply their existing programming knowledge and experience to the world of Python on the Raspberry Pi. 2 | -------------------------------------------------------------------------------- /software.md: -------------------------------------------------------------------------------- 1 | Raspbian does not come with Geany so you have to install it. 2 | 3 | To do this open up LXTerminal and enter the command below: 4 | 5 | ```bash 6 | sudo apt-get install geany -y 7 | ``` 8 | 9 | After the installation has completed you should find Geany inside the 'Programming' folder of the launcher menu. 10 | -------------------------------------------------------------------------------- /software.yml: -------------------------------------------------------------------------------- 1 | - Geany 2 | -------------------------------------------------------------------------------- /worksheet.md: -------------------------------------------------------------------------------- 1 | # Python for Visual Basic programmers 2 | 3 | **This is an archived resource.** The repo will remain available but the resource will no longer be maintained or updated. Some or all parts of the resource may no longer work. To see our latest resources, please visit [raspberrypi.org](http://www.raspberrypi.org). 4 | 5 | Python is a widely-used high level programming language. Its elegant syntax allows you to clearly define application behaviour using fewer lines of code than would be required in other languages like VB. It supports multiple programming paradigms including imperative, functional and object oriented styles, allowing a wide range of tasks to be performed. 6 | 7 | As a Visual Basic programmer, the first thing you will notice is the lack of the form designer; Python is programmed in text only. You could still write desktop applications with buttons and menus, but the form layout must be described in code. This is, however, outside the scope of this document. Programs written in Python often don’t require a desktop interface, as will be discussed later. 8 | 9 | This introduction is intended to help a Visual Basic programmer apply their existing programming knowledge and experience to the world of Python on the Raspberry Pi. This is by no means an exhaustive guide to Python. For comprehensive documentation please visit: http://docs.python.org/2.7/ 10 | 11 | ## Choosing a programming environment 12 | 13 | ### Desktop 14 | 15 | You may already have a preferred programming environment (the program to write code in); if you do not, Geany is recommended. 16 | 17 | [![](images/geany.png)](http://www.geany.org/) 18 | 19 | You should find Geany inside the 'Programming' folder of the launcher menu. To start a new Python program go to File > New (with Template) > main.py 20 | 21 | Geany populates this with some template text (a copyright statement) and some function blocks at the bottom, but you can delete everything except the first line to start afresh. The first line is important because it denotes the file as a Python program. The cogs icon at the top is the familiar run button (F5) similar to Visual Basic. 22 | 23 | Enter the following code and press the run button. 24 | 25 | ```python 26 | print "hello world" 27 | ``` 28 | 29 | ### Command line 30 | 31 | If you prefer the command line you can easily create a Python program using nano or vim; these are terminal-based text editors. For example, enter the following command: 32 | 33 | ```bash 34 | nano test.py 35 | ``` 36 | 37 | Enter the following lines of code into the file. The first line specifies that the file is a Python program. 38 | 39 | ```python 40 | #!/usr/bin/python 41 | print "hello world" 42 | ``` 43 | 44 | Press `Ctrl + O` to save then `Ctrl + X` to quit. Next, mark the file as executable and then run it. 45 | 46 | ```bash 47 | chmod +x test.py 48 | ./test.py 49 | ``` 50 | 51 | You only need to use the `chmod` command once per Python file. It will remain executable even if you make copies of it. 52 | 53 | ## Basic data types 54 | 55 | Python supports a wide range of data types; see the table below. Whereas Visual Basic requires variables to be defined along with their type, Python does not. 56 | 57 | Data type | Visual Basic | Python 58 | --- | --- | --- 59 | Integer number | `Dim count As Integer` | `count = 1` 60 | Floating point number | `Dim distance As Double` | `distance = 2.5` 61 | Boolean | `Dim active as Boolean` | `active = False` 62 | String | `Dim name as String` | `name = "Dave"` 63 | 64 | In Python, simply placing the whole number 1 or the fraction 2.5 into a variable will define it as an Integer or a Float. Because of this you should always initialise (put data into) variables as you define them. 65 | 66 | A # character in Python denotes a comment; text on the same line after this character will be ignored. 67 | 68 | ```python 69 | counter = 1 # Integer 70 | distance = 2.5 # Floating point 71 | active = False # Boolean 72 | name = "Dave" # String 73 | 74 | print counter 75 | print distance 76 | print active 77 | print name 78 | ``` 79 | 80 | This should produce the following output: 81 | 82 | ``` 83 | 1 84 | 2.5 85 | False 86 | Dave 87 | ``` 88 | 89 | ## Indentation 90 | 91 | Python does not use begin and end tags to group lines of code into functions, loops or if-statements. It uses white space indentation only and this is rigidly enforced. Compare the two code samples below: 92 | 93 | - Visual Basic: 94 | 95 | ```vb 96 | Dim count As Integer 97 | count = 1 98 | 99 | If count > 0 Then 100 | MsgBox "Hello" 101 | End If 102 | ``` 103 | 104 | - Python: 105 | 106 | ```python 107 | count = 1 108 | 109 | if count > 0: 110 | print "Hello" 111 | ``` 112 | 113 | The colon in the Python code after the `if` statement is mandatory; it can help to think of it as similar to the `then` keyword in Visual Basic. 114 | 115 | Programs like Geany help you with indentation; pressing enter after the colon will automatically indent the cursor. If you're using the command line, however, you'll need to ensure the indentation is correctly entered. 116 | 117 | You can either use multiple space characters or a tab character for indentation. If you prefer to use spaces then the number of spaces in the indentation can be variable, as long as they remain constant in each code block. Compare the examples below. 118 | Most Python programmers use 4 spaces in their code. While it is not strictly enforced, it is a widely accepted convention. 119 | 120 | - This will work: 121 | 122 | ```python 123 | count = 1 124 | 125 | if count > 0: 126 | print "hello" 127 | print "good morning" 128 | else: 129 | print "goodbye" 130 | print "good night" 131 | ``` 132 | 133 | - This will produce an error: 134 | 135 | ```python 136 | count = 1 137 | 138 | if count > 0: 139 | print "hello" 140 | print "good morning" 141 | else: 142 | print "goodbye" 143 | print "good night" 144 | ``` 145 | 146 | Understanding the rules of indentation is fundamental to Python; it can be a stumbling block for pupils. Pupils often do not understand what white space is; they therefore need to be shown that spaces and tabs are real text characters which are normally invisible in text editors. They serve a purpose and are saved along with the text in a document file. Pupils could be asked how the computer remembers where the white space is in a text file. 147 | 148 | ![](./images/msword-paragraph.png "Microsoft Word Paragraph Button") 149 | 150 | It can also be helpful to offer a quick demonstration in Microsoft Word where some code is typed out and the paragraph toolbar button (above) is used to show the hidden characters. Space characters then show as a dot and tab characters show as an arrow. 151 | 152 | Below is an example of two nested if-statements in Visual Basic and Python for comparison. Tab characters are used because the resulting code looks neater and more readable. 153 | 154 | - Visual Basic: 155 | 156 | ```vb 157 | Dim count As Integer 158 | Dim active As Boolean 159 | 160 | count = 1 161 | active = False 162 | 163 | If count > 0 Then 164 | If active Then 165 | MsgBox "Hello" 166 | End If 167 | End If 168 | ``` 169 | 170 | - Python: 171 | 172 | ```python 173 | count = 1 174 | active = False 175 | 176 | if count > 0: 177 | if active: 178 | print "Hello" 179 | ``` 180 | 181 | ## Arithmetic operators 182 | 183 | The usual range of arithmetic operators are present in Python. Examples of their use are shown in the table below along with Visual Basic code for comparison. 184 | 185 | Operator | Visual Basic | Python 186 | --- | --- | --- 187 | Add | `c = a + b` | `c = a + b` 188 | Subtract | `c = a - b` | `c = a - b` 189 | Multiply | `c = a * b` | `c = a * b` 190 | Divide (true) | `c = a / b` | `c = a / b` 191 | Divide (floor) | `c = a \ b` | `c = a // b` 192 | Modulus division | `c = a Mod b` | `c = a % b` 193 | Exponent | `c = a ^ b` | `c = a ** b` 194 | 195 | **Note**: In Python2 the division operator `/` will actually perform a floor division if the variables being divided are both integers. So whole numbers `10 / 3` gives `3` whereas floating point `10.0 / 3.0` gives `3.33` recurring. You can also force floor division using the `//` operator if needed. 196 | 197 | ## Comparison operators 198 | 199 | Again, the usual range of comparison operators are found in Python; examples are shown in the table below. Notice that both `<>` and `!=` can be used to test for inequality in Python and that equality uses the double equal `==` sign. 200 | 201 | - Visual Basic: 202 | 203 | ```vb 204 | If a = b Then 'Equality 205 | MsgBox "a is equal to b" 206 | End If 207 | 208 | If a <> b Then 'Inequality 209 | MsgBox "a not equal to b" 210 | End If 211 | 212 | If a > b Then 'Greater 213 | MsgBox "a greater than b" 214 | End If 215 | 216 | If a < b Then 'Less 217 | MsgBox "a less than b" 218 | End If 219 | 220 | If a >= b Then 'Greater or equal 221 | MsgBox "a greater or equal to b" 222 | End If 223 | 224 | If a <= b Then 'Less or equal 225 | MsgBox "a less than or equal to b" 226 | End If 227 | ``` 228 | 229 | - Python: 230 | 231 | ```python 232 | if a == b: # Equality 233 | print "a is equal to b" 234 | 235 | if a != b: # Inequality 236 | print "a not equal to b" 237 | 238 | if a <> b: # Inequality 239 | print "a not equal to b" 240 | 241 | if a > b: # Greater 242 | print "a greater than b" 243 | 244 | if a < b: # Less 245 | print "a less than b" 246 | 247 | if a >= b: # Greater or equal 248 | print "a greater or equal to b" 249 | 250 | if a <= b: # Less or equal 251 | print "a less than or equal to b" 252 | ``` 253 | 254 | ## While loops 255 | 256 | The Python while loop is similar to the 'do while' loop in Visual Basic. 257 | 258 | - Visual Basic: 259 | 260 | ```vb 261 | Dim counter As Integer 262 | counter = 1 263 | 264 | Do While counter <= 10 265 | MsgBox counter 266 | counter = counter + 1 267 | Loop 268 | ``` 269 | 270 | - Python: 271 | 272 | ```python 273 | counter = 1 274 | 275 | while counter <= 10: 276 | print counter 277 | counter = counter + 1 278 | ``` 279 | 280 | Execution does not enter the loop unless the while condition is met. If the counter variable in the example above was already set to 11 then the entire loop would be skipped. 281 | 282 | ## For loops 283 | 284 | The `for` loop in Python is extremely versatile and can be used to iterate over all manner of data such as lists (arrays), strings and dictionary objects. There is no equivalent of the standard Visual Basic for loop in Python; there is only an equivalent of the `for each` loop. 285 | 286 | Below is an example of a simple count from 1 to 3. In Visual Basic the standard for loop is used; in Python, however, we must create a list of numbers to iterate over. 287 | 288 | - Visual Basic: 289 | 290 | ```vb 291 | Dim i As Integer 292 | 293 | For i = 1 To 3 294 | MsgBox i 295 | Next i 296 | ``` 297 | 298 | - Python: 299 | 300 | ```python 301 | nums = range(1, 4) 302 | 303 | for i in nums: 304 | print i 305 | ``` 306 | 307 | Notice the use of the `in` keyword on the Python side. The variable `nums` is actually a list containing the integers 1 to 3. It's created by the `range` function by passing in the number to start from and the number to stop at; stopping at 4, therefore, leaves 3 as the final number. 308 | 309 | A more accurate comparison would be the code below: 310 | 311 | - Visual Basic: 312 | 313 | ```vb 314 | Dim col As Collection 315 | Set col = New Collection 316 | 317 | col.Add 1 318 | col.Add 2 319 | col.Add 3 320 | 321 | For Each num In col 322 | MsgBox num 323 | Next num 324 | ``` 325 | 326 | - Python: 327 | 328 | ```python 329 | nums = range(1, 4) 330 | 331 | for num in nums: 332 | print num 333 | 334 | # A shorter way to do the same 335 | for num in range(1, 4): 336 | print num 337 | ``` 338 | 339 | ## Collections and arrays 340 | 341 | In Python, lists are somewhat similar to collections in Visual Basic. They have a number of built in functions to allow you to manipulate them. 342 | 343 | - Visual Basic: 344 | 345 | ```vb 346 | Dim col As Collection 347 | Set col = New Collection 348 | 349 | col.Add "Cat" 350 | col.Add "Dog" 351 | col.Add "Rabbit" 352 | 353 | col.Remove 1 354 | 355 | MsgBox col.count 356 | ``` 357 | 358 | - Python: 359 | 360 | ```python 361 | animals = [] # An empty list 362 | 363 | animals.append("Cat") 364 | animals.append("Dog") 365 | animals.append("Rabbit") 366 | 367 | animals.remove("Cat") 368 | 369 | print len(animals) 370 | ``` 371 | 372 | Python lists can also be initialised with data on a single line of code, in a similar manner to Visual Basic variant arrays. The Python code below will produce an identical list to the example above, which was built using the append method. Either way is valid; which method you choose is a matter of personal preference. 373 | 374 | - Visual Basic: 375 | 376 | ```vb 377 | Dim vArray As Variant 378 | vArray = Array("Cat", "Dog", "Rabbit") 379 | 380 | MsgBox vArray(0) 381 | MsgBox vArray(1) 382 | ``` 383 | 384 | - Python: 385 | 386 | ```python 387 | animals = ["Cat", "Dog", "Rabbit"] 388 | 389 | print animals[0] 390 | print animals[1] 391 | ``` 392 | 393 | Notice the use of square brackets in the Python code. Square brackets `[n]` are used to both define and index Python lists, whereas curved brackets `(n)` are used in Visual Basic. 394 | 395 | ## Functions 396 | 397 | Function blocks in Python are more straightforward compared to Visual Basic. In VB there are two types, `Sub` and `Function`, along with two modes of parameter, `ByVal` and `ByRef`. In Python there is only one way to define a function which is the `def` keyword; parameters are always passed by reference, and they are not typed. 398 | 399 | Below is a comparison between a `Sub` function in Visual Basic (a function where there is no return value) and the equivalent Python code. 400 | 401 | - Visual Basic: 402 | 403 | ```vb 404 | Sub print_me(ByRef s As String) 405 | MsgBox s 406 | End Sub 407 | 408 | print_me "first time" 409 | print_me "second time" 410 | 411 | ``` 412 | 413 | - Python: 414 | 415 | ```python 416 | def print_me(s): 417 | print s 418 | 419 | print_me("first time") 420 | print_me("second time") 421 | ``` 422 | 423 | When a value needs to be returned in Visual Basic the `Function` keyword is used instead of `Sub`. In Python there is no difference in how a function is defined. In VB the return value is set by assigning to the function name, `Sum = a + b`; Python uses the `return` command to do this, `return a + b`. Compare the code below. 424 | 425 | - Visual Basic: 426 | 427 | ```vb 428 | Function Sum(ByRef a As Integer, ByRef b As Integer) As Integer 429 | Sum = a + b 430 | End Function 431 | 432 | MsgBox Sum(5, 10) 433 | MsgBox Sum(10, 20) 434 | ``` 435 | 436 | - Python: 437 | 438 | ```python 439 | def sum(a, b): 440 | return a + b 441 | 442 | print sum(5, 10) 443 | print sum(10, 20) 444 | ``` 445 | 446 | Optional function parameters are also possible in Python in the same way as Visual Basic. In VB the `Optional` keyword is used and a default value is supplied (`= 0`). In Python only the default value is required to make the parameter optional. 447 | 448 | - Visual Basic: 449 | 450 | ```vb 451 | Sub ShowInfo(ByRef name As String, Optional ByRef age As Integer = 0) 452 | MsgBox name 453 | If age > 0 Then 454 | MsgBox age 455 | End If 456 | End Sub 457 | 458 | ShowInfo "John" 459 | ShowInfo "John", 30 460 | ``` 461 | 462 | - Python: 463 | 464 | ```python 465 | def show_info(name, age=0): 466 | print name 467 | 468 | if age > 0: 469 | print age 470 | 471 | show_info("John") 472 | show_info("John", 30) 473 | ``` 474 | 475 | ## Error handling 476 | 477 | In Python runtime errors are called exceptions; Python exception handling is more sophisticated than the error handling in Visual Basic. In VB the `On Error GoTo Label` statement is used along with an `Exit` to stop execution from going past the label. Python uses a `try` block with one or more `except` clauses to test for different kinds of error. The `else` clause runs if no exception occurs. The `finally` block will always run regardless of what errors occur, and is therefore ideal for closing files. 478 | 479 | - Visual Basic: 480 | 481 | ```vb 482 | On Error GoTo ErrLabel 483 | 484 | Dim fso As New FileSystemObject 485 | Dim f As TextStream 486 | 487 | Set f = fso.CreateTextFile("test.txt") 488 | 489 | f.Write("Test Data") 490 | f.Close 491 | 492 | Exit Sub/Function 493 | 494 | ErrLabel: 495 | f.Close 496 | MsgBox "Error:" & Err.Description 497 | ``` 498 | 499 | - Python: 500 | 501 | ```python 502 | try: 503 | f = open("test.txt", "w") 504 | f.write("Test Data") 505 | except IOError as e: 506 | print "IO error:", e 507 | except Exception: 508 | print "unknown error" 509 | else: 510 | print "success" 511 | finally: 512 | f.close() 513 | ``` 514 | 515 | While technically possible, it is advised not to used "except:" without specifying anything, since it can introduce subtle bugs. "except Exception:" is more robust. 516 | 517 | ## Module and Class files 518 | 519 | In Visual Basic modules and classes, `.mod` and `.cls`, are clearly separated out by the tree view of the development environment. They represent separate files that contain code. Module files hold one or more utility functions and class files contain the definition of a single OO object. 520 | 521 | In Python there is no direct equivalent of this structure since all Python files have the `.py` extension. However, it is possible to organise your code into numerous files and access them all from one place. This is done using the `from` keyword. 522 | 523 | Consider the example below. The file `mymodule.py` contains one function called `get_animals`. 524 | 525 | ```python 526 | def get_animals(): 527 | animals = [] # An empty list 528 | 529 | animals.append("Cat") 530 | animals.append("Dog") 531 | animals.append("Rabbit") 532 | return animals 533 | ``` 534 | 535 | If you have multiple files, the convention in Python is to name the entry point of the program (the file to be executed) `main.py`. In `main` we want to access the `get_animals` function which is in `mymodule.py`. The `from import ` syntax is used. Notice that the `.py` is not required here. 536 | Importing several "things" can be done by listing the things, using commas to separate them, like `from import thing1, thing2, thing3`. 537 | 538 | ```python 539 | from mymodule import get_animals 540 | 541 | for animal in get_animals(): 542 | print animal 543 | ``` 544 | 545 | Note that you will see `.pyc` files appearing with the same file name as the imported files (such as `mymodule.pyc`). This is a Python byte code file and is essentially a compiled version of the source code. 546 | 547 | ## Object oriented programming 548 | 549 | Python has excellent object oriented programming capabilities. Classes are also kept in `.py` files in the same way as the module example above (and can be imported in the same way). However, their syntax structure is quite different to Visual Basic. Below is a comparison between two 'person' classes. 550 | 551 | - Visual Basic `clsPerson.cls` 552 | 553 | ```vb 554 | Private m_name As String 555 | 556 | Private Sub Class_Initialize() 557 | 'Start up code here if needed 558 | m_name = "" 559 | End Sub 560 | 561 | Public Property Let Name(value As String) 562 | m_name = value 563 | End Property 564 | 565 | Public Property Get Name() As String 566 | Name = m_name 567 | End Property 568 | 569 | Public Sub Display() 570 | MsgBox Me.Name 571 | End Sub 572 | ``` 573 | 574 | In VB the `Me` keyword can be used to access the current object or form properties. Notice it is used above in the `Display` method. 575 | 576 | The following VB code would then be used to create an instance of the person class. 577 | 578 | ```vb 579 | Dim obj As New clsPerson 580 | obj.Name = "David" 581 | obj.Display 582 | ``` 583 | 584 | In Python a class first needs to be defined with the `class` statement followed by a name, as in the example below. The first function `__init__` is the same as `Class_Initialize` in Visual Basic. It runs when a new instance of the class is created in memory. Notice the `self` statement; this is equivalent to the Visual Basic `Me` keyword and allows you to access properties of the current object. 585 | 586 | When you define functions inside a class the `self` object must always be specified as the first parameter. You don't have to explicitly specify it when calling the functions; Python does this behind the scenes for you. 587 | 588 | There is also no concept of `Public` or `Private` class members in Python. Everything is public, therefore the `set_name` and `get_name` functions below are redundant; they remain only for comparison to the Visual Basic code. 589 | 590 | - Python `person.py` 591 | 592 | ```python 593 | class Person: 594 | def __init__(self): 595 | # Start up code here if needed 596 | self.name = "" 597 | 598 | def set_name(self, value): 599 | self.name = value 600 | 601 | def get_name(self): 602 | return self.name 603 | 604 | def display(self): 605 | print self.name 606 | ``` 607 | 608 | Instead of a private variable `m_name` with public get and set functions you can define a variable as a member of self, `self.name = ""`; it will then be publicly accessible outside of the object. 609 | 610 | ```python 611 | from person import * 612 | 613 | obj = Person() 614 | obj.name = "David" # or also; obj.set_name("David") 615 | obj.display() 616 | ``` 617 | 618 | If you require code to run as a property is being set or read then you will need to use a set or get function. For example, you may need this if you wanted to prevent negative numbers from being set on an age property for the person class below. 619 | 620 | - Visual Basic: 621 | 622 | ```vb 623 | Private m_age As Integer 624 | 625 | Public Property Let Age(value As Integer) 626 | If value >= 0 Then 627 | m_age = value 628 | End If 629 | End Property 630 | ``` 631 | 632 | - Python: 633 | 634 | ```python 635 | def set_age(self, value): 636 | if value >= 0: 637 | self.age = value 638 | ``` 639 | 640 | Despite the setAge function constraining how `self.age` is set inside the class, it is possible to use `obj.age = -1` from outside the class and bypass this logic. 641 | 642 | However, there is a convention in Python to indicate that a variable should not be touched from outside a class. This is done using a double underscore, for example `self.__age`. This generally warns users of your code to avoid that variable, despite the fact that they're not prevented from using it. 643 | 644 | ## Libraries and References (DLLs) 645 | 646 | ![](./images/vba-references.png "VB Project References") 647 | 648 | In Visual Basic it's common practice to access pre-made code from dynamic link libraries through the Tools / References menu option as above. DLL files are a Microsoft-specific paradigm, and are not used in Python on the Raspberry Pi due to its Linux-based OS. Instead Python comes with numerous code libraries (also written in the Python language), which you can import into your program and cover a wide range of requirements. 649 | 650 | On the Raspberry Pi these libraries are found in the `/usr/lib/pyshared` and `/usr/lib directories`. They can be easily accessed from your code using the `import` statement; you can have as many import statements in your program as required. Here are some examples: 651 | 652 | ```python 653 | import random 654 | 655 | print random.randint(0,9) # Between 0 and 9 656 | ``` 657 | 658 | ```python 659 | import datetime 660 | 661 | a = datetime.datetime.now() 662 | b = a + datetime.timedelta(1,0,0,0) # Add one whole day 663 | print b 664 | ``` 665 | 666 | ```python 667 | import math 668 | 669 | x = 5 670 | y = 10 671 | hypotenuse = math.sqrt((x * x) + (y * y)) 672 | ``` 673 | 674 | ```python 675 | import MySQLdb 676 | 677 | db = MySQLdb.connect("localhost", "appuser", "", "TestDB") 678 | cursor = db.cursor() 679 | cursor.execute("SELECT - FROM TABLE") 680 | ``` 681 | 682 | For a more extensive list of Python modules please visit this page: https://wiki.python.org/moin/UsefulModules 683 | --------------------------------------------------------------------------------