Python Tips

You may find these tips helpful if you have programmed in another language such as C++ or Java. When in doubt, read the docs.

If you have never programmed before, skip this and begin the course.

Whitespace Syntax

Python formally uses whitespace as part of its syntax. Examples:

You may be used to languages ending logical lines with a semicolon: ;. Python ends logical lines with a carriage return (a new line).

Compare Java:

System.out.println("Hello");
System.out.println("World");

with Python:

print("Hello")
print("World")

You can extend a logical line of code over multiple lines using backslash characters:

print("Hello \
")
print("World")

Logical lines can be extended inside of groupings such as arrays:

x = [1, 2, 3,
     4, 5, 6]

Where languages like Java use curly braces { and } to group statements, Python typically uses indentation.

Compare Java:

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

with Python:

for i in range(5):
    print(i) # note that the print statement is indented 

The above also demonstrates:

  • Comments are indicated with #
    • More on comments in the course
  • for loop syntax is concise
    • Declaration of i and i += 1 are implied
    • Python does not have ++, use +=1
    • More on loops in the course
  • Things that are associated with groups of statements end in a colon :

Nesting loops and/or conditions uses multiple levels of indentation:

for i in range(3):
    for j in range(4):
        print(i+j)
        print(i*j)

The Interpreter

You can run the Python interpreter from the command line and experiment with code. Open a terminal and simply run python.

Operators

Basic math operators work similarly in Python and Java:

print(1 + 2)
3
print(1 * 2)
2
print(1 / 2)
0.5

Dividing two integers (or any two numbers) with / automatically yields a float. Quotient/remainder is available with the quotient // and remainder % operators:

print(7 // 2)
3
print(7 % 2)
1

These are not constrained to integers:

print(6 // 2.5)
2.0
print(6 % 2.5)
1.0

Operators like + and * work like math operators when the things on both sides of them are numbers. They do other things when they’re around strings.

+ concatenates:

print("Fizz" + "Buzz")
FizzBuzz

* extends the string, when used with an integer:

print("Fizz" * 5)
FizzFizzFizzFizzFizz

The above ‘multiplication’ operation would be nonsensical with a float instead of an int, or with two strings, and trying it will give you an error.

Powers can be raised with **:

print(2**3)
8

There is also a well-documented math library for things like square roots.

import math

print(math.sqrt(2))
1.4142135623730951

Note: There is nothing wrong with the math library, but most people use numpy for math these days.

import numpy as np

print(np.sqrt(2))
1.4142135623730951

Conditionals

Conditionals are expressed with if, elif, and else:

  • The if is required.
  • Any whole number of elifs are allowed.
  • Zero or one elses are allowed, and the else always comes last.

Syntax uses colons and indentation, just like loops.

x = 5

if x > 10:
    print("x is huge")
elif x < 0:
    print("x is negative")
elif x > 0:
    print("x can be counted on fingers")
else:
    print("x is zero")
x can be counted on fingers

(This is a very silly example.)

Types and Variables

Python has types, but variables do not have types at compile time. Compared to Java, this might seem confusing. You can think of variables as pointing to objects that have types (Python also does not, explicitly, have pointers):

x = 126
y = "sunset"
z = 12.6

Variables can be reassigned without regard to the type the variable is pointing at:

x = 126
x = "sunrise"

Assigning a variable to another variable assigns it to wherever the other variable is pointing:

x = 126
y = "sunset"
x = y
print(x)
sunset

Reassigning the other variable doesn’t change the first variable:

x = 126
y = "sunset"
x = y
y = "sunrise"
print(x)
sunset

Lists

Lists are delimited with square brackets [ and ].

x = [5, 6, 7]
print(x)
[5, 6, 7]

They are not typed and can contain whatever you want. Or, for the imaginative, they can contain any type of object.

x = [126, "sunset", 12.6]
print(x)
[126, 'sunset', 12.6]

Individual list elements can be accessed via “slicing.” Note that lists are 0-indexed.

x = [126, "sunset", 12.6]
print(x[1])
sunset

Individual elements of a list can be modified:

x = [126, "sunset", 12.6]
x[1] = "sunrise"
print(x)
[126, 'sunrise', 12.6]

Lists are collections of references to variables and behave differently with respect to assignment. Specifically, assigning a variable to another variable that references a list will cause both variables to reference the same list object:

x = [126, "sunset", 12.6]
y = x
print(y)
[126, 'sunset', 12.6]

Changing x also changes y, since they reference the same thing:

x = [126, "sunset", 12.6]
y = x
x[1] = "sunrise"
print(y)
[126, 'sunrise', 12.6]

Slicing can access more than one element:

x = [126, "sunset", 12.6]
print(x[1:3])
['sunset', 12.6]

Strings can also be sliced:

x = "sunrise"
print(x[0:3])
sun

More details about slicing in the course and the docs.

Lists can be concatenated:

x = [1, 2, 3] + [4, 5, 6]
print(x)
[1, 2, 3, 4, 5, 6]

Lists can be extended with append()

x = ["sunrise"]
x.append("sunset")
print(x)
['sunrise', 'sunset']

Tuples

Tuples are similar to lists, but they are immutable. They are optionally delimited with parentheses ( and )

x = ("sunrise", "sunset")
print(x[1])
y = "duck", "teal"
print(y[0])
sunset
duck

While the parentheses are optional, they are typically used.

Dicts

Hash tables in Python are called dictionaries, or “dicts.” They consist of key-value pairs. They are delimited with curly braces { and }.

This dict has one pair: the key is 'sunrise' (a string) and the value is 126 (an int).

x = {'sunrise': 126}
print(x)
{'sunrise': 126}
  • Keys and values can be any variable type. Values can be lists or dicts, but keys cannot (since these cannot be hashed.)

Dict values can be accessed via their keys:

x = {'sunrise': 126}
print(x['sunrise'])
126

Dict values can also be or added via their keys:

x = {'sunrise': 126}
x['sunrise'] = 127
x['sunset'] = 12.6
print(x)
{'sunrise': 127, 'sunset': 12.6}

Functions

Functions are defined with def and a colon. Indentation to group statements follows the same conventions you have already seen.

def doubling(x):
    return x*2

y = doubling(2)
print(y)
4

Functions do not have to return anything.

def good_morning():
    print("sunrise")

good_morning()
sunrise

Variables passed to a function are copied into the function and not modified outside of the scope of the function.

def add_one(x):
    x += 1
    return x

y = 2
z = add_one(y)
print(y)
2

Lists passed to a function are passed as references, and are modified outside of the scope of the function.

def append_sunrise(x):
    x.append("sunrise")
    return x

y = ['sunset']
z = append_sunrise(y)
print(y)
['sunset', 'sunrise']

This is a decent time to note that you can get into some trouble with functions because nothing in Python is explicitly typed:

def append_sunrise(x):
    x.append("sunrise")
    return x

y = 'sunset'
z = append_sunrise(y)
print(y)

Should I Use Python 2

No, use Python 3.

Is This Everything I Need To Know About Python

Almost certainly not. The docs are comprehensive and searchable.