Skip to content

PythonForProgrammers

Ben Levitt edited this page May 24, 2023 · 2 revisions

Python for Programmers

Ok, so you're already a programmer. Maybe you use JavaScript, C, Swift, or Z80 assembly. You're probably just looking to learn what's different about Python, how the basics work, and where to get more info.

Python uses colons and leading whitespace indentation (traditionally spaces) to indicate code blocks, instead of using curly braces.

a = 1
b = 2
if a < b:
    print("a is smaller")
else:
    print('b is smaller')

Python is more strict about types than JavaScript, but less so than C. You can define variables on the fly, and without type information, and change what types they hold as you go. But most functions and operators want specific types, and will complain (raise an error) if they get the wrong type.

x = None
print(x is None)  # True

x = 1
print(x+1)  # 2

x = "Hi"
print(x+1)  # TypeError: can only concatenate str (not "int") to str

Simple/immutable arguments to functions are passed by value, so changing the value of a simple argument inside a function does not change its value outside the functions. But bigger objects like lists and dictionaries that are mutable, are passed in as references, so changes to them inside a function will change the original.

Strings in Python are immutable, so anything you do that changes a string is actually giving you a new string.

Python also lets you get slices (sub-sections) of iterable things like lists and strings easily. You can use square brackets like for normal array indexing, but give 2 values separated by a colon, to give start and end indices. You can even omit the start or end value to mean from the start, or to the end.

s = "Hello" + " " + "World!"  # "Hello World!"
s[:2]  # "He"
s[7:9]  # "or"
"'" + s[1:]  # "'ello World!"

The python for loop is more like a foreach, where it loops through each item in a list.

ovals = [oval_1, oval_2, oval_3, oval_4]  # A list of CardStock oval objects
for oval in ovals:
    oval.fill_color = "red"

To get something more like a c-style for loop, you can loop through each item in a range of values.

for i in range(4):
    print(i)

gives you:

0
1
2
3

Or to get the same result with a while loop:

i = 0
while i < 4:
    print(i)
    i += 1   # Note the lack of a ++ operator.  It does not exist in python.

Another fun Python feature is list comprehension. It allows you to apply an expression to each element in a list (or even a dictionary).

a = [1,2,3,4,5]
print( [i*2 for i in a] )  # [2, 4, 6, 8, 10]

b = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
c = {v:k for k,v in b.items()}
print( c )  # {1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}

print( [c[i] for i in a]  )  # ["a", "b", "c", "d", "e"]

Python has a very rich set of modules to do almost anything you'll need. So, for example, if you need to parse some JSON, just search for python json parsing and you'll quickly be pointed to the built-in json module with examples like:

import json

x =  '{"name":"Alice", "age":25, "city":"Dallas"}'

y = json.loads(x)
# loads() loads json from a string, giving us a python dictionary in this case

print(y["city"])