We’ll cover basic Python syntax by example.
Many of these topics will be covered in more depth in other sections. The purpose here is to have a quick reference for jumping into writing Python code.
Hello World¶
print("Hello World")Variable Assignment¶
Variables do not need to be declared, and are not typed
x = 1
print(x)
x = 'a'
print(x)Comments¶
Comments begin with the pound (#) symbol
print(x)
x = 1 # assign the variable x
print(x) # print the variable xLists¶
A Python list is specified using square brackets []
x = [1, 2, 3]
print(x)You can access elements using square brackets [] as well. Python is 0-indexed, so the first index is x[0]
print(x[0])the length of the list can be obtained using len()
print(len(x))Functions¶
Functions are defined using the def keyword, followed by the function name, arguments, and then a colon :. You can return values from a function using return.
Scope is determined by indentation (4 spaces).
def square(x):
# returns the square of x
return x * x
square(2)Functions can take multiple arguments, and keyword arguments. They can return mutiple values.
def f(x,y, a=2):
# a is a keyword argument
return x + y, a * x
w, z = f(1,3, a=1)
print(w)
print(z)Strings¶
Strings in Python can be specified with either single quotes ', or double quotes ". You shouldn’t mix which one you are using
a = 'hello'
b = "hello"
a == bMulti-line strings are specified with triple quotes - either ''' or """
a = """A mulit-
line string"""
print(a)printf-style formating¶
Strings can be formatted using a syntax similar to C’s printf.
s = "value = %d" % 1
ss = "name: %s, age: %d, weight: %.1f" % ("Bob", 20, 160.0)
sThe format method¶
strings can be formatted using the format method, which will fill-in curly braces {}:
x = 1
print("x = {}".format(x))You can use the format arguments in multiple positions or in different orders by specifying the index in the braces:
x = 2
print("{0} * {0} = {1}".format(x, square(x)))You can also use keyword arguments in format, which can be very helpful in complicated situations
print("{name1} said \"hello {name2}!\", and {name2} said \"hello {name1}!\"".format(name1="Alice", name2="Bob"))f-strings¶
In Python 3.6 format strings, or f-strings were introduced. These give another option for formating strings, which is easy to read - similar to using keyword arguments with format, but names are pulled from the environment. F-strings are denoted with an f before the first quote, as in f'...'
name = "Alice"
s = f"Hello, {name}!"
print(s)A good reference for format string syntax is the documentation.
Documentation¶
You can read documentation for functions and classes using help():
help(print)If you’re running ipython (either the REPL, or in a Jupyter notebook), you can use ?
print?Documentation is written in docstrings. Right now, you see that the square function above does not have documentation aside from the call signature.
help(square)Docstrings are written in a string at the beginning of a function
def square(x):
"""
returns the square of the input x
"""
return x * xhelp(square)Logic and Control Flow¶
For control flow, Python uses if, elif and else.
The True and False keywords are used logically.
In Python, you should use and, or, and not for logical epressions.
def sign(x):
"""
returns the sign of a number.
"""
if x < 0:
return -1
elif x > 0:
return 1
else:
return 0
print(sign(2), sign(-3), sign(0))if True:
print(True)
if False:
print(False)if True or False:
print(True or False)if not False:
print("hello")Iteration¶
Iteration can be done in for-loops or while loops. These use the keywords for and while.
Again, indentation determines scope.
break will break out of the loop.
continue will jump directly to the next iteration of the loop
for i in range(5):
print(i)n = 0
while True:
if n == 5:
break
print(n)
n = n + 1You can also iterate over a variety of objects such as lists using in
x = [1,2,'a']
for i in x:
print(i)Classes and Objects¶
You can define custom classes using the class keyword. To obtain an instance of the class, you need to define the __init__ method.
class MyComplex():
def __init__(self, re, im):
self.re = re
self.im = im
z = MyComplex(1, 2)
print(f"{z.re} + {z.im}i")A class is a recipe for creating objects. Everything in Python is an object, whose type is a class. You can find about an object’s type using type()
print(type(z))
print(type(square))
print(type(1))Packages¶
Packages provide functionality not available in standard Python. One such example is numpy, which provides a standard numerical array faster than Python lists.
First, you should make sure a package is installed. From a terminal:
$ conda install numpyNow, from Python, you can import the package
import numpyFunctions and classes in a package are imported into a namespace, which by default has the same name as the package. For example, numpy has an array class, which you can access using numpy.array
a = numpy.array([1,2,3])
print(a)
type(a)You can change the namespace during import using the as keyword. For example, numpy is often imported as np
import numpy as np
a = np.array([1,2,3]) # now we use the np namespace
a# Your code here
Notebook Cell
def add_cubes(x, y):
total = x**3 + y**3
return totalExercise 2¶
Use Python to compute the sum .
# Your code here
Notebook Cell
def add():
total = 0
for num in range(1, 101):
total += num
return totalExercise 3¶
Write a function that will take an integer n as input, and return the sum .
# Your code here
Notebook Cell
def add_until_n(n):
total = 0
for num in range(1, n+1):
total += num
return totalExercise 4¶
Write a function that will take an integer n as input and print “even” if n is even, and “odd” if n is odd.
Hint: Look up the modulo operator.
# Your code here
Notebook Cell
def is_even(n):
if n%2 == 0:
print("even")
else:
print("odd")