-
Notifications
You must be signed in to change notification settings - Fork 25
Basic Python
To run a python program, execute python program-name.py. Many programs will take arguments, which are given after the program name python program-name.py arg1 arg2 arg3. In this class, you will never have to write programs from scratch.
Python programs can import code from external packages with import packageName, you will often see lines like this at the top of our programs. All of the functions from that package will then be available as packageName.functionName(). Sometimes we will give the package a shorter name with import packageName as p so we can call p.functionName(). Again, in this class this will all be managed for you.
Comments in python are given by the # character. Don't forget that whitespace is significant.
The simplest way to see what your program is doing is to print information to the terminal/command prompt. Python has several options for printing formatted information (see the docs), but the simplest method is to just concatenate string with +. Surrounding any non-string data (numbers, lists, objects) with str() will yield a string representation of that data.
print("Hello world")
print(str(7))
print("This is the number pi: " + str(3.14) + ". Isn't it great?")
l = [1, 1, 2, 3, 5, 8, 13] # create a list
print("For my next trick, I'll print a list: " + str(l))This prints:
Hello world
7
This is the number pi: 3.14. Isn't it great?
For my next trick, I'll print a list: [1, 1, 2, 3, 5, 8, 13]
Here's a simple example of if statements.
x = 5.0
# Basic if-statement
if x > 3.0:
print("x is bigger than 3!")
# Use 'and' and 'or' to create complex conditions
y = 10.0
if y > 5.0 or y < 20.0:
print("y is medium sized")
# Use if-elif-else to create multi-stage conditions
z = 35
if (z % 3 == 0) and (z % 5 == 0):
print("z is divisible by 3 and 5!")
elif (z % 3 == 0):
print("z is only divisible by 3")
elif (z % 5 == 0):
print("z is only divisible by 5")
else:
print("z isn't very divisible...")This prints:
x is bigger than 3!
y is medium sized
z is only divisible by 5
For-loops in Python use a simpler syntax than many other languages. In our code we will often use iterators, rather than indexed loops (as explained in the section below). While-loops work like they do in most languages.
# A simple for-loop over i=0,1,2
for i in range(3):
print("Iteration i = " + str(i))
# A while-loop
x = 3
while x >= 0:
print("x is now: " + str(x))
x = x - 1prints
Iteration i = 0
Iteration i = 1
Iteration i = 2
x is now: 3
x is now: 2
x is now: 1
x is now: 0
Lists are defined using brackets, and indexed with 0-indexing. We will often operate on the elements of a list (or some other datastructure) using an iterator, which is like a function that returns the elements one at a time when called. Iterators can also be defined to return other things one at a time (like the faces which touch a vertex in a mesh).
# Define a list
animals = ["cat","dog","duck"]
# Basic list operations
print("The first element is " + str(animals[0]))
print("The last element is " + str(animals[-1]))
animals.append("bunny") # add a new element to the end
print("The new last element is " + str(animals[-1]))
# Iterate over the elements in the list
for critter in animals:
print("Processing critter: " + str(critter))prints
The first element is cat
The last element is duck
The new last element is bunny
Processing critter: cat
Processing critter: dog
Processing critter: duck
Processing critter: bunny
Python code encourages the frequent use of sets and dictionaries, which we like due to their correspondence with mathematical ideas. A set is a collection of unique elements.
A = set([2,7,5]) # Create a set
for x in A: # Iterate through the set
print("x = " + str(x))
print("6 in A = " + str((6 in A))) # test if the set contains a value
print("7 in A = " + str((7 in A)))
B = set([2,4])
print("A union B is " + str(A.union(B))) # we can even use set arithmeticprints
x = 2
x = 5
x = 7
6 in A = False
7 in A = True
A union B is set([2, 4, 5, 7])
A dictionary is a mapping from keys to values. Both the keys and values can be anything you want!
d = dict() # create a new, empty dictionary
# add some mappings from string --> float
d["cat"] = 3.0
d["duck"] = -4.5
d["bunny"] = 1.61
print(str(d)) # print the entire dictionary
print("Cat has value " + str(d["cat"])) # look up a valueprints
{'duck': -4.5, 'bunny': 1.61, 'cat': 3.0}
Cat has value 3.0
Functions in Python work pretty much like you would expect. Optional arguments include an equals sign in their definition. These arguments do not have to be given when the function is called, and if omitted they take the value on the righthand side of the equals sign.
#Define a simple function
#n is an optional argument, it has a default value of 2
def power(x, n=2):
return x**n # this is the Python syntax for raising x to the n'th power
print("Power(5) = " + str(power(5)))
print("Power(5,n=4) = " + str(power(5,n=4)))prints
Power(5) = 25
Power(5,n=4) = 625
Here's a simple demonstration of a class in Python
# Define our class
class Person(object):
# Every class method or variable must be prefixed with self
# (this does NOT include temporary variables in functions, only variables
# that we want to keep around)
# This is a special constructor method, which executes when we create a new Person()
def __init__(self, newName):
self.myName = newName # store the name in the variable myName
# Define a simple method with no parameters which makes the person say its name
def greet(self):
print("Hello, my name is " + str(self.myName))
# Now, lets create 3 new person objects, put them in a set, and have each say its name
people = set()
person1 = Person("Larry")
people.add(person1)
person2 = Person("Curly")
people.add(person2)
person3 = Person("Moe")
people.add(person3)
for p in people:
p.greet()this prints
Hello, my name is Larry
Hello, my name is Curly
Hello, my name is Moe