Profile picture

Python Under 10 Minutes

Last updated: September 1st, 20202020-09-01Project preview

rmotr


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.

purple-divider

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.

green-divider

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 was 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.

green-divider

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 [1]:
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 [2]:
# 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?")
Let the fun begin!

green-divider

Comments

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

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

green-divider

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 [6]:
name = "Mary"
print(name)
Mary
In [7]:
age = 30
print(age)
30

Variables, once set, will be preserved:

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

green-divider

Data Types

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

Integers, type int:

Integers have unlimited magnitude.

In [9]:
# an int
age = 30
In [10]:
age
Out[10]:
30
In [11]:
type(age)
Out[11]:
int

Floats, type float:

The standard floating point number

In [12]:
# a float
price = 2.50
In [13]:
price
Out[13]:
2.5
In [14]:
type(price)
Out[14]:
float

Remember that floats sometimes exhibit "extraneous" behavior:

In [15]:
0.1 * 3
Out[15]:
0.30000000000000004

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

In [16]:
from decimal import Decimal
In [17]:
Decimal('0.1') * 3
Out[17]:
Decimal('0.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 [18]:
# Create them with double quotes:
print("Hello unicode 👋")
Hello unicode 👋
In [19]:
# single quotes:
print('Omelette Du Fromage 🧀')
Omelette Du Fromage 🧀
In [20]:
type('Hello World')
Out[20]:
str
In [21]:
len("Hello")
Out[21]:
5

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 [22]:
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)
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: 😒

Booleans, type bool

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

In [23]:
True
Out[23]:
True
In [24]:
type(False)
Out[24]:
bool

None, type NoneType

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

In [25]:
x = None
In [26]:
x
In [27]:
print(x)
None
In [28]:
type(None)
Out[28]:
NoneType

green-divider

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 [29]:
age_as_string = "28"
In [30]:
type(age_as_string)
Out[30]:
str
In [31]:
int(age_as_string)
Out[31]:
28
In [34]:
age = int(age_as_string)
In [35]:
type(age)
Out[35]:
int

Their use as objects is mainly associated with their type:

In [36]:
type(13) == int
Out[36]:
True

green-divider

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 [37]:
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 [38]:
result = hello()
In [39]:
result
Out[39]:
'Hello World'

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

In [40]:
def empty():
    x = 3
In [41]:
result = empty()
In [42]:
print(result)
None

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 [43]:
def add(x, y):
    return x + y
In [44]:
add(2, 3)
Out[44]:
5

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

In [45]:
def add(*args):
    return sum(args)
In [46]:
add(1, 1, 1)
Out[46]:
3
In [47]:
add(1)
Out[47]:
1

green-divider

Operators

Both arithmetic and boolean operators are available, for example:

Arithmetic operators

In [48]:
3 + 3
Out[48]:
6
In [49]:
11 % 7
Out[49]:
4
In [50]:
2 ** 4
Out[50]:
16

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

In [51]:
3 + 4 * 5
Out[51]:
23
In [52]:
3 + 4 * 2**3
Out[52]:
35

Boolean operators

Regular comparison operators are available:

In [53]:
7 > 3
Out[53]:
True
In [54]:
8 >= 8
Out[54]:
True

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

In [55]:
8 > "abc"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-55-9f94e2e4c974> in <module>
----> 1 8 > "abc"

TypeError: '>' not supported between instances of 'int' and 'str'

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

In [56]:
True and True
Out[56]:
True
In [57]:
not False
Out[57]:
True
In [58]:
False or True
Out[58]:
True

green-divider

Control Flow

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

If/else/elif statements

In [59]:
days_subscribed = 28
In [60]:
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")
Halfway there

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 [61]:
names = ['Monica', 'Ross', 'Chandler', 'Joey', 'Rachel']
In [62]:
for name in names:
    print(name)
Monica
Ross
Chandler
Joey
Rachel

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 [63]:
count = 0
In [64]:
while count < 3:
    print("Counting...")
    count += 1
Counting...
Counting...
Counting...

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

green-divider

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 [65]:
l = [3, 'Hello World', True]
In [66]:
len(l)
Out[66]:
3

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

In [67]:
l[0]
Out[67]:
3
In [68]:
l[1]
Out[68]:
'Hello World'

Negative indices are also supported:

In [69]:
l[-1]
Out[69]:
True
In [70]:
l[-2]
Out[70]:
'Hello World'

Lists have many useful methods to add/remove elements:

In [71]:
l.append('Python 🐍')
In [72]:
l
Out[72]:
[3, 'Hello World', True, 'Python 🐍']
In [73]:
'Python 🐍' in l
Out[73]:
True
In [74]:
'Ruby ♦️' in l
Out[74]:
False

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 [75]:
t = (3, 'Hello World', True)

Indexing them works in the same way:

In [76]:
t[0]
Out[76]:
3
In [77]:
t[-1]
Out[77]:
True
In [78]:
'Hello World' in t
Out[78]:
True

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 [82]:
user = {
    "name": "Mary Smith",
    "email": "mary@example.com",
    "age": 30,
    "subscribed": True
}
In [83]:
user
Out[83]:
{'name': 'Mary Smith',
 'email': 'mary@example.com',
 'age': 30,
 'subscribed': True}

Access is by key, also using square brackets:

In [84]:
user['email']
Out[84]:
'mary@example.com'
In [85]:
'age' in user
Out[85]:
True
In [86]:
'last_name' in user
Out[86]:
False

Sets

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

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

Adding elements is done with the add method:

In [89]:
s.add(10)

Removing elements can be done with pop():

In [90]:
s.pop()
Out[90]:
1

Membership operation:

In [91]:
9 in s
Out[91]:
True

green-divider

Iterating collections

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

In [92]:
l = [3, 'Hello World', True]
In [93]:
for elem in l:
    print(elem)
3
Hello World
True
In [94]:
user
Out[94]:
{'name': 'Mary Smith',
 'email': 'mary@example.com',
 'age': 30,
 'subscribed': True}
In [95]:
for key in user:
    print(key.title(), '=>', user[key])
Name => Mary Smith
Email => mary@example.com
Age => 30
Subscribed => True
In [98]:
for key, value in user.items():
    print(key, value)
name Mary Smith
email mary@example.com
age 30
subscribed True
In [99]:
for i in range(5):
    print(i)
0
1
2
3
4

green-divider

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 [100]:
import random
In [109]:
random.randint(0, 99)
Out[109]:
85

green-divider

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 [110]:
age = "30"
In [111]:
if age > 21:
    print("Allowed entrance")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-111-31f2672e1932> in <module>
----> 1 if age > 21:
      2     print("Allowed entrance")

TypeError: '>' not supported between instances of 'str' and 'int'

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

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

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

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

green-divider

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.

purple-divider

Notebooks AI
Notebooks AI Profile20060