Icon
A Better Way to Learn Python
  •  

Getting Started With Python

Outline

As an experienced programmer, the hardest part of learning a new language is just recognizing how they implement things we already know how to do. You might be starting a project from scratch, but it's more likely you are doing some maintenance on an existing Python app. In this section, we will try to call out the basics of what makes Python work for scripting, functional, and object-oriented programming

A quick way to get started and see what you can do in Python is to run the Python interpreter and enter some code right into it. or use the command window on your repl.it window.

Try out the Python interpreter
$ python     ## Run the Python 3.x interpreter
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 10           ## set a variable for this session of the interpreter
>>> foo                ## retrieve the value
10
>>> foo + 10
20
>>> foo = 'bar'        ## 'foo' can hold a string value
>>> foo
'bar'
>>> len(foo)           ## call a function on the string
3
>>> bar = 'foo'
>>> foo + bar          ## Simple string manipulation
'barfoo'
>>> print(f'Full sentence using {bar} and {foo}.')          ## f string interpolation using the variables
Full sentence using foo and bar.
>>> >>> foo + len(foo)          ## try something that doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> foo + str(len(foo))         ## now fix it
'bar3'
>>> ^D        ## press CTRL+d to exit (CTRL+z in Windows/DOS terminal)

The Python.org documentation reviews the standard types that are built into the interpreter.

The Basics

Python Enhancement Proposal (PEP 8), is Python's style guide. It's a set of rules for how to format your Python code to maximize its readability. Reading through some of these rules will give you some insights into how Python works under the hood and ways to improve the performance of your code.

Python is more concerned with making it easy to write good programs than difficult to write bad ones. - Steve Holden

Check out The Zen of Python

From the Python interpreter type in: import this

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

Variables / Objects - Same Thing

  • Variables in python are implicitly typed by being assigned a value. Once they are out of scope they are automatically destroyed
  • Variables inside a function are private to that function by default. Variables outside a function are global by default.
  • A collection of values can be assigned to variables in a single statement.

Everything in Python is an Object.

We bind a name to an object <name> = <object> when we assign a value to a variable. We can understand this more in the interpreter:

>>> x = 'foo'
>>> y = 'foo'
>>> print(id(x))
4333360496
>>> print(id(y))
4333360496
>>> print(x is y)
True

Strings are immutable therefore we've just given that value in memory a new name. When we change x = 'foobar' a new string gets created and and x now points to a new memory ID. When we assign them to a mutable object, like a list, we get a different behavior:

>>> x = [10, 20, 30]
>>> y = [10, 20, 30]
>>> print(id(x))
4331900296
>>> print(id(y))
4332315080
>>> print(x is y)
False

It's important that you know this behavior in Python so that you understand when your code doesn't behave as you expected. The above code created two separate lists. If we want to create a pointer in Python to a mutable object we would write the following:

>>> x = [10, 20, 30]
>>> y = x
>>> print(x is y)
True
>>> x
[10, 20, 30]
>>> y
[10, 20, 30]
>>> x.pop(0)          # Removes the item from the array and returns it.
10
>>> y
[20, 30]
>>> x
[20, 30]

Pass by object reference instead of pass by value or pass by reference

>>> def foo(x):
...     print(id(x))
...     x = 'a new value'
...     print(id(x))
... 
>>> bar = 'an old value'
>>> print(id(bar))
4333455472
>>> foo(bar)
4333455472
4333455920
>>> print(bar)
an old value

By default, passing a variable to a function in Python is done by object reference. Just like in the previous section, there is a difference between passing mutable and immutable objects. Take a look at the code above. When bar is passed into the foo(x) function, it is done by object reference. Thus the id's are the same. From the previous section, we know that when x = "q new value", because it's an immutable string, a new object was created and x is no longer a pointer to bar. When we pass a mutable object into the function we get different behavior. Creating a file passbyref.py and then using the interpreter to import it we get:

def foo(x):
    x[-1] = "'goodbye'"

phrase = 'You had me at \'hello\''
bar = phrase.split()

print(bar)
foo(bar)
print(bar)

# result
>>> from passbyref import *
['You', 'had', 'me', 'at', "'hello'"]
['You', 'had', 'me', 'at', "'goodbye'"]
>>> 

Beautiful is better than ugly.

Here are some things to remember as you are diving into your Python application:

  • Use single = for assignments, double == for comparisons
  • To continue lines, use "\", except if you are inside brackets and parenthesis
  • Use the ":" to denote the beginning of a code block
  • Best practice is to use 4 spaces to indent code inside the blocks.
  • Two line returns between Class and Function declarations
  • End the file with a line return
  • All lines a maximum of 79 characters
  • Use two underscores before the name of a class, function or method to make it private
  • Two underscores before and after are used for Builtin classes, attributes, etc.
  • Null value is the string "None"

Let's dig into some strings and things.

 

I finished! On to the next chapter