Profile picture

Co-founder @ RMOTR

Python in Under 10 Minutes

Last updated: May 4th, 20192019-05-04Project preview

Python in under 10 minutes

Ok, so this will techincally take us more than 10 minutes, but you get the idea: this is a very high level overview of the Python programming language. Specially for those of you that already know some other programming language (R, Javascript, Ruby, etc) and want to do the switch to Python.

👉 If you want to learn Python and programming, check out our online Data Science course.

The high level

Python is a interpreted, high level programming language created by Dutch programmer Guido van Rossum and released in 1991.

As I always say, Python is old. It gained a lot of traction around 2006, with its popularity being driven its beauty and simplicity to do Web Development (its main Web Development Framework, Django, was released in 2006). From there, it took off as one of the most popular scripting languages.

Python is multi-paradigm: you can write code using Object Oriented, Functional and/or Imperative programming. Python is interpreted and uses a dynamic type system, although considered strongly typed.

It has an extensive builtin standard library with features that ranges from time management, to http servers, concurrency and async programming.

Python is Open Source and is managed by a non-profit organization: the Python Software Foundation.

Python 3 vs Python 2

You might have heard that there are two main versions of Python around: Python 2 and Python 3. Well, I'll keep it simple for you:

👍 Python 3: YES!

🙅 Python 2: NO!

Python 2 will be deprecated in 2020. So stick to Python 3, it's the present and the future of the language (at least until we start planning Python 4 😅, just kidding).

A quick note about different "implementations"

Finally, all what I'm saying here technically applies to "CPython", Python's main implementation. Don't worry if this doesn't make sense. It's just for the curious ones. If you're interested, we've written an entire post about it: A quick guide about Python implementations.

Syntax Overview

The following paragraphs will be dedicated to Python's syntax and technical details. There are more to Python than just syntax, as its community, events, email lists, etc. But after all, this is just a technical introduction.

Indentation based

This might feel weird at first, but in Python we do NOT use curly braces to denote blocks of code. We use "indentation" instead. This is similar to Ruby. For example, this is a very simple add_numbers function in javascript:

function add_numbers(x, y){
    return x + y
}

In Python, we'd write it in this way:

In [ ]:
def add_numbers(x, y):
    return x + y

An if-else block in Javascript:

let language = "Python"

if (language === "Python"){
    console.log("Let the fun begin");
} else {
    console.log("You sure?");
}

In Python:

In [ ]:
# try changing "Python" to something else.
# Don't remove the quotes.
language = "Python"

if language == "Python":
    print("Let the fun begin!")
else:
    print("You sure?")

Comments

You've seen comments in the previous block of code: they're prefixed with a pound/hashtag sign:

In [ ]:
# this is a comment
In [ ]:
# it doesn't produce any output
In [ ]:
# can be above...
print("Hello World")  # next to...
# or below your code

Variables

We've defined a variable language in one of our previous examples. In Python, you can set a variable at any time, in any block of code, by just assigning a valid name to any value you want:

In [ ]:
name = "Mary"
print(name)
In [ ]:
age = 30
print(age)

Variables, once set, will be preserved:

In [ ]:
print(name, "is", age, "years old")

Data Types

Python supports the most common data types, the usual suspects we could say:

Integers, type int:

Integers have unlimited magnitude.

In [ ]:
# an int
age = 30
In [ ]:
age
In [ ]:
type(age)

Floats, type float:

The standard floating point number

In [ ]:
# a float
price = 2.50
In [ ]:
price
In [ ]:
type(price)

Remember that floats sometimes exhibit "extraneous" behavior:

In [ ]:
0.1 * 3

If you need decimal fixed point precision, you can use the decimal module:

In [ ]:
from decimal import Decimal
In [ ]:
Decimal('0.1') * 3

Strings, type str

Strings are used to store text. Technically, they're "immutable sequences of Unicode code points". Which means that Python supports Unicode:

In [ ]:
# Create them with double quotes:
print("Hello unicode 👋")
In [ ]:
# single quotes:
print('Omelette Du Fromage 🧀')
In [ ]:
type('Hello World')
In [ ]:
len("Hello")

You can use double or single quotes, it's the same. We also have "multi-line" strings, that are created with a pair of 3 quotes (simple or double, either works):

In [ ]:
joke = """
Me: What’s the best thing about Switzerland?
Friend: I don't know. What?
Me: I don’t know, but the flag is a big plus.
F: 😒
"""

print(joke)

Booleans, type bool

Python booleans are as simple as they get: True and False, capitalized.

In [ ]:
True
In [ ]:
type(False)

None, type NoneType

As other languages have null, in Python we have None, which pretty much represents the absence of value:

In [ ]:
x = None
In [ ]:
x
In [ ]:
print(x)
In [ ]:
type(None)

int, float, str and bool objects and functions

You'll often see some of these "keywords/names" used both as functions and as individual objects. When used as functions, their usage is to transform/cast objects into its corresponding type. Example:

In [ ]:
age_as_string = "28"
In [ ]:
type(age_as_string)
In [ ]:
int(age_as_string)
In [ ]:
age = int(age_as_string)
In [ ]:
type(age)

Their use as objects is mainly associated with their type:

In [ ]:
type(13) == int

Functions

We've seen a couple of functions defined already, but let's dig a little bit deeper. Functions in Python are very intuitive. Let's start with an example of a function without parameters:

In [ ]:
def hello():
    return "Hello World"

The def keyword indicate the definition of a function, followed by a name and a list of arguments (which this function doesn't receive). The return statement is used to break the flow of the function and return a value back to the caller:

In [ ]:
result = hello()
In [ ]:
result

If a function doesn't explicitly include a return statement, Python will return None by default:

In [ ]:
def empty():
    x = 3
In [ ]:
result = empty()
In [ ]:
print(result)

Receiving parameters

There's a lot that can be done with Python parameters; including default and named parameters, and even variable/dynamic ones. But for now, we'll just focus on the basics. Function parameters are listed at the function definition, and they're part of the function's local scope:

In [ ]:
def add(x, y):
    return x + y
In [ ]:
add(2, 3)

We can also define functions that accept variable number of arguments, using the star args *:

In [ ]:
def add(*args):
    return sum(args)
In [ ]:
add(1, 1, 1)
In [ ]:
add(1)

Operators

Both arithmetic and boolean operators are available, for example:

Arithmetic operators

In [ ]:
3 + 3
In [ ]:
11 % 7
In [ ]:
2 ** 4

Precedence can be consulted on the official docs. But, for the most part, the precedence is similar to the usual in arithmetic:

In [ ]:
3 + 4 * 5
In [ ]:
3 + 4 * 2**3

Boolean operators

Regular comparison operators are available:

In [ ]:
7 > 3
In [ ]:
8 >= 8

We said that Python is strongly typed, so comparison between different types will fail if these types are not compatible:

In [ ]:
8 > "abc"

Python also has other common boolean operators like and, or, not, etc. They are short circuited, as most modern programming languages:

In [ ]:
True and True
In [ ]:
not False
In [ ]:
False or True

Control Flow

Python supports the most common control flow blocks. Keep in mind they're defined with indentation.

If/else/elif statements

In [ ]:
days_subscribed = 28
In [ ]:
if days_subscribed >= 30:
    print("Loyal customer")
elif days_subscribed >= 15:
    print("Halfway there")
elif days_subscribed >= 1:
    print("Building confidence")
else:
    print("Too early")

For loops

For loops in Python are different than other languages, specially those C/Java-inspired languages. In Python, for loops are designed to iterate over collections (we'll see collections later). But keep that in mind.

In [ ]:
names = ['Monica', 'Ross', 'Chandler', 'Joey', 'Rachel']
In [ ]:
for name in names:
    print(name)

While loops

While loops are seldom used in Python. For loops are the preferred choice 99% of the time. Still, they're available and are useful for some situations:

In [ ]:
count = 0
In [ ]:
while count < 3:
    print("Counting...")
    count += 1

There's another block to mention, try/except, but it's in the Exceptions section.

Collections

Python has multiple versatile collection types, each with different features and capabilities. These are the most common collections we'll explore:

  • Lists
  • Tuples
  • Dictionaries
  • Sets

Even though they all have different capabilities, there is one common property to all of them, and it's that Python collections are heterogeneous, that is, you can mix multiple types. That doesn't mean we should mix types, usually it's better to have a consistent collection. But it's still possible.

Lists

Lists are mutable, ordered sequences. We could argue, the most common collection type.

In [ ]:
l = [3, 'Hello World', True]
In [ ]:
len(l)

List elements are accessed using sequential indices (starting from 0):

In [ ]:
l[0]
In [ ]:
l[1]

Negative indices are also supported:

In [ ]:
l[-1]
In [ ]:
l[-2]

Lists have many useful methods to add/remove elements:

In [ ]:
l.append('Python 🐍')
In [ ]:
l
In [ ]:
'Python 🐍' in l
In [ ]:
'Ruby ♦️' in l

Tuples

Tuples are very similar to lists, but with a huge difference: they're immutable. That means, once a tuple is created, it can't be further modified:

In [ ]:
t = (3, 'Hello World', True)

Indexing them works in the same way:

In [ ]:
t[0]
In [ ]:
t[-1]
In [ ]:
'Hello World' in t

But there's no way of modifying them.

Dictionaries

Dictionaries are map-like collections that store values under a user-defined key. The key must be an immutable object; we usually employ strings for keys. Dictionaries are mutable, and more importantly, unordered.

In [ ]:
user = {
    "name": "Mary Smith",
    "email": "mary@example.com",
    "age": 30,
    "subscribed": True
}
In [ ]:
user

Access is by key, also using square brackets:

In [ ]:
user['email']
In [ ]:
'age' in user
In [ ]:
'last_name' in user

Sets

Sets are unordered collection which the unique characteristic that they only contain unique elements:

In [ ]:
s = {3, 1, 3, 7, 9, 1, 3, 1}
In [ ]:
s

Adding elements is done with the add method:

In [ ]:
s.add(10)

Removing elements can be done with pop():

In [ ]:
s.pop()

Iterating collections

As mentioned in the control flow section, Python's for loop is specially designed to iterate over collections:

In [ ]:
l = [3, 'Hello World', True]
In [ ]:
for elem in l:
    print(elem)
In [ ]:
for key in user:
    print(key.title(), '=>', user[key])

Modules

One of the best features of Python as a language, is its rich builtin library. To use external modules, you must first import them:

In [ ]:
import random
In [ ]:
random.randint(0, 99)

Exceptions

Exceptions are raised at runtime when an abnormal situation is produced in your program. Exceptions can also be constructed and raised by your code. Example of an exception:

In [ ]:
age = "30"
In [ ]:
if age > 21:
    print("Allowed entrance")

Exceptions can be handled at runtime with a try/except block:

In [ ]:
try:
    if age > 21:
        print("Allowed entrance")
except:
    print("Something went wrong")

The except portion can receive also be parametrized with the expected exception:

In [ ]:
try:
    if age > 21:
        print("Allowed entrance")
except TypeError:
    print("Age is probably of a wrong type")

We're just getting started

As you can imagine, there's a lot more to add about such a versatile and powerful language as Python. We're still missing many important topics like OOP, File Management, Networking, Concurrency, etc.

If you're eager to learn more about Python, we've compiled a list of 3 recommended free Python books to get started.

Notebooks AI
Notebooks AI Profile20060