Learn Python in 15 Minutes


But only if you can read and learn really fast.

This article will cover only the most basics of Python. For full list of methods on objects you can consult the official documentation, or try out some online course/book.

You can find the whole script in this gist.

############################
# Obligatory Hello, World! #
############################
print('Hello, World!')

#############################
# Primitives and Operations #
#############################
7  # int
7.0  # float
'Hello, World!'  # str
True  # bool

7 + 5  # -> 13
7 * 3  # -> 21
7 / 2  # -> 3.5 (division)
7 // 2  # -> 3 (integer division)
7 % 2  # -> 1 (modulo)
7 ** 2  # -> 49 (exponent)
7 * (2 + 1)  # -> 21

'he' + 'llo'  # -> 'hello'
'*' * 5  # -> '*****'
'hi'[0]  # -> 'h' (string is indexed, index starts from 0)
'value'[-1]  # -> 'e'
'slice me'[1:5]  # -> 'lice' (slice syntax)

True and False  # -> False
True or False  # -> True
not True  # -> False

1 == 1  # -> True
1 != 0  # -> True
1 > 2  # -> False
1 >= 1  # -> True
1 <= 10  # -> True
1 < 0  # -> False
7 < 21 <= 50  # -> True i.e. 21 is in (7,50]

############################################
# Built-in Functions and String Formatting #
############################################
# You can call this functions without importing anything
print('This is the most basic built-in function')
int('12')  # -> 12
float('12')  # -> 12.0
bool(1)  # -> True

# len() can be used on strings and lists
len('Hello, World!')  # -> 13

type(True)  # -> <class 'bool'>

# String formatting and string methods
'I have %s%d' % ('$', 7)  # -> 'I have $7'
'I have {}{}'.format('$', 7)
'john'.capitalize()  # -> 'John'
'LOWER'.lower()  # -> 'lower'
'upper'.upper()  # -> 'UPPER'
dir('string')  # list attributes of an object

#############################
# Variables and Collections #
#############################
price = 10
vat = 1.2
total = price * vat

# List are used to store collection of items
# items in the list don't have to be of the same type
numbers = [1, 4, 6, 7, 0, 10]
sum(numbers)  # -> 28
len(numbers)  # -> 6

# Objects can be mutated
numbers.append(7)  # -> this returns None
# however original list is modified
print(numbers)  # -> [1, 4, 6, 7, 0, 10, 7]

# You can access the list items same as you would
# access the string items, slice notation works too
numbers[0]  # -> 1
numbers[-1]  # -> 7
numbers[1:3]  # -> [4, 6]

# Full slice notation is [start:end:step], and you can
# also use this to revert the string/list
numbers[::2]  # -> [1, 6, 0, 7]
numbers[::-1]  # -> [7, 10, 0, 7, 6, 4, 1]

# Lists are mutable
numbers[0] = 99
print(numbers)  # -> [99, 4, 6, 7, 0, 10, 7]

# Tuples are similar to lists, but immutable
sequence = (1, 3, 5, 6)
sequence[0] = 99  # this will raise TypeError

# If you want to define a tuple with one item
# you have to add trailing comma
tpl = (1,)

# You can also test if something is in the list/tuple
99 in numbers  # -> True
99 in sequence  # -> False

# You can also do this
[0] * 3  # -> [0, 0, 0]
[1] + [2]  # -> [1, 2]

# You also have available a number of methods
new_numbers = [21, 7, 15, 4]
new_numbers.sort()  # print(new_numbers) -> [4, 7, 15, 21]
new_numbers.pop()  # -> 21
new_numbers.reverse()  # print(new_numbers) -> [15, 7, 4]

additional_numbers = [7, 11, 22, 5]
new_numbers.extend(additional_numbers)
print(new_numbers)  # -> [15, 7, 4, 7, 11, 22, 5]

# equivalent is not same as identical
7 == 7  # Test equivalency (is it a same value?)

lst1 = [1, 2, 3]
lst2 = lst1
lst1 is lst2  # Test identity (is it a same object?)
# Check IDs of objects to verify identity
id(lst1)
id(lst2)

# Bonus string formatting (Python 3.6 or greater) (f-strings)
person = 'John'
money = 100
f'{person} received ${money}'

# sets - same as sets in math
rgb_pallete = {'red', 'green', 'blue'}
random_pallete = {'magenta', 'cyan', 'black', 'red'}

# Union
rgb_pallete | random_pallete
# -> {'red', 'cyan', 'green', 'magenta', 'black', 'blue'}

# Difference
rgb_pallete - random_pallete  # -> {'green', 'blue'}

# Intersection
rgb_pallete & random_pallete  # -> {'red'}

# Sets can be useful to check if list items are unique
random_list = [1, 2, 3, 4, 5]
len(random_list) == len(set(random_list))  # -> True

# Dictionaries are hash tables
user = {'name': 'John', 'last_name': 'Smith', 'age': 20}
user['age']  # -> 20 (get value)
user.get('name', None)  # -> 'John' (get method with default)
user.get('occupation', 'unknown')  # -> 'unknown'
user['occupation'] = 'Developer'  # set new key/value pair
'occupation' in user  # -> True
user.update({'language': 'Python'})

list(user.keys())
# -> ['name', 'last_name', 'age', 'occupation', 'language']
list(user.values())
# -> ['John', 'Smith', 20, 'Developer', 'Python']
list(user.items())
"""
Will return:
[
    ('name', 'John'),
    ('last_name', 'Smith'),
    ('age', 20),
    ('occupation', 'Developer'),
    ('language', 'Python')
]

btw this is a multiline string, it is usually used for
multiline comments in functions and classes. This string
is called docstring (implying its primary use)
"""

################
# Control Flow #
################
# From here on remember: indentation matters
# and it's equal four spaces
number = 20
if number >= 18:
    print('You can register to vote')
elif 0 <= number < 18:
    print(f'You can vote in {18 - number} years')
else:
    print('You have to be born first')

counter = 10
while counter >= 0:
    print(counter)
    counter = counter - 1  # this is how we decrement in Python

# This is how we do for each
colors = ['red', 'green', 'blue']
for color in colors:
    print(color)

# We can also print the index with enumerate()
for index, color in enumerate(colors):
    print(index, color)

# You can easily iterate through dict keys, values, or items
users = {1: 'john', 2: 'jane'}
for key in users.keys():
    print(key)

for name in users.values():
    print(name)

for key, value in users.items():
    print(key, value)

#############
# Functions #
#############
def add(a, b):
    return a + b

add(7, 3)  # -> 10

def convert_kelvin(kelvin):
    celsius = kelvin - 273.15
    fahrenheit = celsius * (9 / 5) + 32
    return celsius, fahrenheit

# You can unpack the tuple from return
celsius, fahrenheit = convert_kelvin(0)

# You can also use default value
def append_one(lst=None):
    if not lst:
        lst = []
    lst.append(1)
    return lst

append_one()  # -> [1]
append_one([1, 2, 3])  # -> [1, 2, 3, 1]

# Variable arguments
def give_me_back(*args):
    return args

give_me_back(1, 2, 3)  # (1, 2, 3)

# Keyword arguments
def give_me_back(**kwargs):
    return kwargs

give_me_back(name='John', age=20)  # -> {'name': 'John', 'age': 20}

# You can combine all of those e.g.
def fun(value, default=0, *args, **kwargs):
    pass

# Functions can be used to mutate values also
def mutate_list(lst):  # -> returns None but mutates input
    lst.append(1)

lst = []
mutate_list(lst)
print(lst)  # -> [1]

# In Python functions are first-class objects
# so you can assign them to variables also
def power(x):
    def exponentiate(y):
        return y ** x
    return exponentiate

square = power(2)
square(7)  # -> 49

cube = power(3)
cube(4)  # -> 64

##############
# Exceptions #
##############
try:
    int('s')
except ValueError:
    # deal with exception
    print('Invalid value')
finally:
    # This is executed always
    # You can cleanup resources here
    print('Closing db connection')

###########
# Modules #
###########
import random

# You can create a new list using list comprehension
numbers = [random.randint(1, 10) for _ in range(10)]
random.choice(numbers)  # pick a random number from a list

# You can import specific thing from a module as
from math import sqrt

sqrt(9)  # -> 3

# You can also import everything from a module
# but this is a bad practice!
from math import *

# Sometimes you want to abbreviate module name
# You can see this commonly for numpy (np) or pandas (pd)
import random as rand
rand.randint(1, 100)

# Do not name your modules same as modules from Python standard
# lib. Module in Python is actually a file that contains your code
# A package is a collection of modules (i.e. directory that contains
# __init__.py file)

############################################
# File I/O and Context Managers (suppress) #
############################################
# There are several modes in which you can access a file
# r - read, w - write, rb - read binary, wb - write binary,
# a - appending, ab - append in binary file, and of course
# read/write modes: r+, w+, a+, rb+, wb+, ab+
f = open('text.txt', 'r')
f.readlines()  # returns all lines of a file as a list
f.close()  # close connection to the file

# It's too easy to forget to close a file when opened
# use context manager instead - it will close a file for you
with open('text.txt', 'r') as f:
    f.readlines()

# Remember try/except? It's really common to have pass in the
# except block (sometimes we don't need to deal with exceptions)
mixed = ['a', 1, 'b', '2', 3]
sum_only_numbers = 0
for element in mixed:
    try:
        sum_only_numbers += int(element)
    except ValueError:
        pass

# Well, Python standard lib also has a context manager to replace
# try/except/pass idiom
from contextlib import suppress

sum_only_numbers = 0
for element in mixed:
    with suppress(ValueError):
        sum_only_numbers += int(element)

#####################################################################
# Classes (basic, inheritance, multiple inheritance, magic methods) #
#####################################################################
# Q: How do I read __init__.py?
# A: Dunder init. Same applies for __str__, __repr__, etc.

# Q: What are magic methods?
# A: Those are the "dunder" methods

class Person:
    # A class variable - shared among all
    # objects of the same type
    population = 0

    # this is a constructor of the class
    # there are number of dunder methods available, e.g.
    # __str__, __repr__, __getattr__, __getattribute__, etc.
    def __init__(self, name):
        # instance attribute - belongs to one
        # concrete object residing in the memory
        self.name = name
	    # self represent the instance, so self.name is the
        # instance attribute with the value of the name

        Person.population += 1

    def kill(self):
        print('{} has died :('.format(self.name))

        Person.population -= 1

        if Person.population <= 0:
            print('The last one has died...')
            Person.population == 0
        else:
            print('Current population: {}'.format(Person.population))

    def hello(self):
        print('Hello, my name is {}.'.format(self.name))

    # regular methods on the class are called instance methods
    # there are also class methods, such as this, that can be
    # called on a particular class - class methods are shared
    # by all instances (if you want to dive deeper, there are
    # also static methods, and you can use @property decorator
    # if you want to have getter and setter methods for an
    # attribute)
    @classmethod
    def current_population(cls):
        print('Total population is: {}'.format(cls.population))

# When you want to execute the module, use __name__ == '__main__'
# __name__ is the name of the module, it's usually equal to the
# file name of the module (when you import it), but if you execute
# it with "python3 person.py" from the command line, it's __name__
# will be set to the special value '__main__'. In essence this means
# that the code below would not be executed if you imported this
# module somewhere else from the code.
if __name__ == '__main__':
    john = Person('John')

    john.current_population()
    # or
    Person.current_population()

    jane = Person('Jane')
    jane.hello()
    john.hello()
    jane.current_population()

    john.kill()
    jane.kill()

# Simple inheritance
class Animal:

    def feed(self, food):
        print(f'nom nom nom {food}')

class Cat(Animal):

    def __init__(self, name):
        self.name = name
    
    def meow(self):
        print(f"{self.name} meows at you, it's hungry")
    
if __name__ == '__main__':
    kitty = Cat('Kitty')
    kitty.meow()
    kitty.feed('milk')

# Python also supports multiple inheritance. Methods are inherited
# left to right in Python classes, e.g. if you're adding a mixin
# you would put the base class of your new class at the end of
# inheritance list. For more info see:
# http://python-history.blogspot.com/2010/06/method-resolution-order.html
from abc import ABC, abstractmethod

class Form(ABC):
    """
    We will make this class abstract. ABC means Abstract Base Class.
    """
    
    def __init__(self, name, email):
        self.name = name
        self.email = email

    @abstractmethod
    def validate_email(self):
        raise NotImplementedError


class UserMixin:
    """Add this mixin when you need a method to update user input"""

    def clean_name(self):
        return self.name.strip().capitalize()


class UserForm(UserMixin, Form):
    """
    Finally, you construct the form for the User, by using a base Form,
    and adding your mixin for additional functionality.
    """

    def validate_email(self):
        return '@' in self.email

if __name__ == '__main__':
    user_form = UserForm('  john\t\t\t', 'john@example.com')
    name = user_form.clean_name()  # -> 'John'
    email_valid = user_form.validate_email()  # -> True
python 

We're not spammers, and you can opt-out at any moment. We hate spam as much as you do.

powered by TinyLetter

See also