Learn Python 3 in 1 Hour

By Xah Lee. Date: . Last updated: .

This is a Python 3 tutorial. This page is a summary of the basics for beginners. Examples on this page are based on Python 3.2.3.

For python 2, see: Python 2 Basics.

Strings

Use single quote or double quote to quote string.

# -*- coding: utf-8 -*-
# python 3

# single and double quotes are same in Python
a = "tiger ♥"
b = 'rabbit ♥'

print(a, b)   # tiger ♥ rabbit ♥

You can use \n for linebreak, and \t for tab, etc.

Note: in python 3, you don't need the # -*- coding: utf-8 -*- at the top of the file. However, it's still nice to have, because it's a standard way to indicate what encoding is used for the file across many editors.

Triple Quotes for Multi-Line String

To quote a string of multiple lines, use triple quotes. Example:

# -*- coding: utf-8 -*-
# python 3

d = """this
will be printed
in 3 lines"""

print(d)

Quoting Raw String 「r"…"」

You can add r in front of the quote symbol. This way, backslash characters will NOT be interpreted as escapes.

# -*- coding: utf-8 -*-
# python 3

c = r"this\n and that"

print(c) # prints a single line

more detail: Python 3: Quoting String

substring, length

Substring extraction is done by appending a bracket str[begin_index:end_index]. Index can be negative, which counts from the end.

# -*- coding: utf-8 -*-
# python 3

b="01234567"
print(b[1:4]) # prints “123”

Length of the string is len().

a="this"
print(len(a)) # 4

Strings can be joined by a plus sign +.

print("this" + " that")

String can be repeated using *.

print("this" * 2)

Arithmetic

# -*- coding: utf-8 -*-
# python 3

print(3 + 4) # 7
print(3 - 4) # -1
print(3 + - 4)   # -1
print(3 * 4) # 12

print(2 ** 3) # 8 power

print(11 / 5) # 2.2  (in python 2, this would be 2)
print(11 // 5)    # 2 (quotient)
print(11 % 5) # 1 remainder (modulo)

print(divmod(11, 5))  # (2, 1) quotient and remainder

Convert to {int, float, string}

Python doesn't automatically convert between {int, float, string}.

Assignment Operators

# -*- coding: utf-8 -*-
# Python 3

# add and assign
c = 0
c += 1
print(c)    # 1

# substract and assign
c = 0
c -= 2
print(c)    # -2

# multiply and assign
c = 2
c *= 3
print(c)    # 6

# exponent and assign
c = 3
c **= 2
print(c)    # 9

# divide and assign
c = 7
c /= 2
print(c)    # 3.5

# modulus (remainder) and assign
c = 13
c %= 5
print(c)    # 3

# quotient and assign
c = 13
c //= 5
print(c)    # 2

Note: Python doesn't support ++ or --.

Warning: ++i may not generate any error, but it doesn't do anything.

For bitwise and other operators, see: Python 3: Operators.

True and False

False like things, such as False, 0, empty string, empty array, …, all evaluate to False.

The following evaluate to False:

# -*- coding: utf-8 -*-
# python 3

my_thing = []

if my_thing:
    print("yes")
else:
    print("no")

Conditional: if then else

#-*- coding: utf-8 -*-
# python 3

# Examples of if

x = -1
if x<0:
    print('neg')
elif x==0:
    print('zero')
elif x==1:
    print('one')
else:
    print('other')

# the elif can be omitted.

Loop, Iteration

Example of a “for” loop.

# -*- coding: utf-8 -*-
# python 3

a = list(range(1,5)) # creates a list from 1 to 4. (does NOT include the end)

for x in a:
    if x == 3:
        print(x)

# prints 3

The range(m, n) function gives a list from m to n-1.

Python also supports break and continue to exit loop.

#-*- coding: utf-8 -*-
# python 3

for x in range(1,9):
    print('yay:', x)
    if x == 5:
        break
# prints up to 5

Example of a “while” loop.

#-*- coding: utf-8 -*-
# python 3

x = 1
while x <= 5:
    print(x)
    x += 1

List

Creating a list.

a = [0, 1, 2, "more", 4, 5, 6]
print(a)

Counting elements:

a = ["more", 4, 6]
print(len(a)) # prints 3

Getting a element. Use the syntax list[index]. Index start at 0. Negative index counts from right. Last element has index -1.

a = ["more", 4, 6]
print(a[1]) # prints 4

Extracting a sequence of elements (aka sublist, slice): list[start_index:end_index].

a = ["zero", "one", "two", "three", "four", "five", "six"]
print(a[2:4])   # prints ["two", "three"]

WARNING: The extraction is not inclusive. For example, mylist[2:4] returns only 2 elements, not 3.

Modify element: list[index] = new_value

xx = ["a", "b", "c"]
xx[2] = "two"
print(xx) # → ['a', 'b', 'two']

A slice (continuous sequence) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

# -*- coding: utf-8 -*-
# python 3

xx = [ "b0", "b1", "b2", "b3", "b4", "b5", "b6"]

xx[0:6] = ["two", "three"]

print(xx)   # ['two', 'three', 'b6']

Nested Lists. Lists can be nested arbitrarily. Append extra bracket to get element of nested list.

a = [3, 4, [7, 8]]

print(a[2][1])    # returns 8

List Join. Lists can be joined with plus sign.

b = ["a", "b"] + [7, 6]
print(b)    # prints ['a', 'b', 7, 6]

Python: List Basics

Tuple

Python has a “tuple” type. It's like list, except it's immutable (that is, the elements cannot be changed, nor added/deleted).

Syntax for tuble is using round brackets () instead of square brackets. The brackets are optional when not ambiguous, but best to always use them.

# -*- coding: utf-8 -*-
# python 3

# tuple
t1 = (3, 4 , 5) # a tuple of 3 elements. paren optional when not ambiguous
print(t1) # (3, 4 , 5)
print(t1[0])    # 3
# -*- coding: utf-8 -*-
# python 3

# nested tuple
t2 = ((3,8), (4,9), ("a", 5, 5))
print(t2[0])   # (3,8)
print(t2[0][0])    # 3
# -*- coding: utf-8 -*-
# python 3

# a list of tuples
t3 = [(3,8), (4,9), (2,1)]
print(t3[0])   # (3,8)
print(t3[0][0])    # 3

[see Python: Difference Between Tuple and List]

Python Sequence Types

In Python, {string, list, tuple} are called “sequence types”. They all have the same methods. Here's example of operations that can be used on sequence type.

# -*- coding: utf-8 -*-
# python 3

# operations on sequence types

# a list
ss = [0, 1, 2, 3]

# length
print(len(ss)) # 4

# ith item
print(ss[0]) # 0

# slice of items
print(ss[0:3])    # [0, 1, 2]

# slice of items with jump step
print(ss[0:10:2]) # [0, 2]

# check if a element exist
print(3 in ss)    # True. (or False)

# check if a element does NOT exist
print(3 not in ss) # False

# concatenation
print(ss + ss)   # [0, 1, 2, 3, 0, 1, 2, 3]

# repeat
print(ss * 2)    # [0, 1, 2, 3, 0, 1, 2, 3]

# smallest item
print(min(ss))    # 0

# largest item
print(max(ss))    # 3

# index of the first occurrence
print(ss.index(3))   # 3

# total number of occurrences
print(ss.count(3))   # 1

Dictionary: Key/Value Pairs

A keyed list in Python is called “dictionary” (known as Hash Table or Associative List in other languages). It is a unordered list of pairs, each pair is a key and a value.

#-*- coding: utf-8 -*-
# python 3

# define a keyed list
aa = {"john":3, "mary":4, "jane":5, "vicky":7}
print(aa)

# getting value from a key
print("mary is:", aa["mary"])   # mary is: 4

# add a entry
aa["pretty"] = 99

# delete a entry
del aa["vicky"]

print(aa)  # {'jane': 5, 'john': 3, 'mary': 4, 'pretty': 99}

# get keys
print(list(aa.keys())) # ['jane', 'john', 'mary', 'pretty']

# get values
print(list(aa.values()))   # [5, 3, 4, 99]

# check if a key exists
print("is mary there:", "mary" in aa) # output 「is mary there: True」

Loop Thru List/Dictionary

Here is a example of going thru a list by element.

# -*- coding: utf-8 -*-
# python 3

myList = ['one', 'two', 'three', '∞']

for x in myList:
     print(x)

You can loop thru a list and get both {index, value} of a element. Example:

# -*- coding: utf-8 -*-
# python 3

myList = ['one', 'two', 'three', '∞']
for i, v in enumerate(myList):
     print(i, v)

# 0 one
# 1 two
# 2 three
# 3 ∞

Loop thru Dictionary

# -*- coding: utf-8 -*-
# python 3

myDict = {"john":3, 'mary':4, 'jane':5, 'vicky':7}

for k, v in list(myDict.items()):
     print(k, v)

# output

# jane 5
# john 3
# mary 4
# vicky 7

[see Python: Map Function to List]

Using Library

A library in Python is called a module.

# -*- coding: utf-8 -*-
# python 3

# import the standard module named os
import os

# example of using a function
print('current dir is:', os.getcwd())
# -*- coding: utf-8 -*-
# python 3

import os

# print all names exported by the module
print(dir(os))

[see Python: List Modules, Search Path, Loaded Modules]

Defining a Function

The following is a example of defining a function.

# -*- coding: utf-8 -*-
# python 3

def myFun(x,y):
     """myFun returns x+y."""
     result = x+y
     return result

print(myFun(3,4)) # prints 7

A string immediately following the function definition is the function's documentation.

A function can have optional parameters. If no argument is given, a default value is assumed. Example:

# -*- coding: utf-8 -*-
# python 3

def myFun(x, y=1):
    """myFun returns x+y.
    Parameter y is optional and default to 1"""
    return x+y

print(myFun(3))  # output 4

[see Python: Function Optional Parameter]

Classes and Objects

# -*- coding: utf-8 -*-
# python 3

# class and object, basics

# define a class.
# by convention, class name starts with a cap letter
class X1:
    "A class example"

    ii = 1 # a member variable

    # define a method. There MUST always be a 「self」 in the arg spec as first item.
    # this method takes no argument.
    def ff(self):
        return 3

    # This method defines 1 parameter, the x.
    def gg(self, x):
        return x + 1

    # method named __init__ are called when class is instantiated
    # this is the constructor
    def __init__(self,x):
  # to create true instance variable, declare it inside constructor and start it with “self.”
        self.jj = x # jj is instance variable

# create a object of the class X1
# This is called “instantiating a class”.
xx = X1(7)

# Data or functions defined in a class are called the class's attributes or methods.
# To access them, append a dot and their name after the object's name.

# access a class variable
print (xx.ii)   # 1

# access a instance variable
print (xx.jj)   # 7

# call a method
print (xx.gg(4))    # 5

Example of extending a class:

# -*- coding: utf-8 -*-
# python 3

# example of extending a class. inheritance

class X1:
    "A class example"

    def ff(self):
        return "ff"

# extending a class by putting parent in the parenthesis.
class X2(X1):
    "X2 extends/inherits X1"

    def gg(self, x):
        return x + 2

# create a object of X2
x2 = X2()

# ff is from X1. a inherited method
print (x2.ff()) # ff

For detail, see Python: Class and Object

Writing a Module

Here's a basic example. Save the following line in a file and name it mymodule.py.

# -*- coding: utf-8 -*-
# python 3

def f1(n):
    return n+1

To load the file, use import import module_name, then to call the function, use module_name.function_name. Example:

# -*- coding: utf-8 -*-
# python 3

import mymodule # import the module

print(mymodule.f1(5)) # calling its function. prints 6
print(mymodule.__name__)   # list its functions and variables

If you have a question, put $5 at patreon and message me.

Python 3

Lang Detail

  1. Print Version String
  2. Quoting String
  3. String Operations
  4. Format String
  5. Operators
  6. Object, ID, Type

Misc

  1. Traverse Directory
  2. Sort List, Matrix, Object
  3. Python 3: Map with Side Effect Doesn't Work If Result is Not Used
  4. Python 3 Closure
  5. Python 2 and 3 Difference