Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -



Introduction to Python

From Juneday education
Revision as of 01:19, 20 May 2022 by Rikard (Talk | contribs) (First notes)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Some notes while learning Python

Funny thing. I decided to learn how to use pointers in Python in order to implement a swap function. Python is call-by-value so the following wouldn't work:

def swap(a, b):
    tmp = a
    a = b
    b = tmp

Since Python is call-by-value, the parameters are local variables whose values are copied on calling a function.

But there must be a library for pointers, I thought, and found ctypes:

>>> from ctypes import *
>>> def swap(a, b):
...     tmp = a[0]
...     a[0] = b[0]
...     b[0] = tmp
... 
>>> a = c_int(1)
>>> b = c_int(2)
>>> swap(pointer(a),pointer(b))
>>> a.value
2
>>> b.value
1
>>>

That works as you can see. Then I read a little more about Python and discovered that you can also swap to variables like so:

a = 1
b = 2
a, b = b, a