Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
-The Zen of Python, Tim Peters
Side note: Python is a dynamically-typed interpreted language. Open up the Start Menu and the Anaconda3 folder. Click on 'IPython'. This is an interpreter. It interprets your commands through what is called a a Read-Eval-Print loop. It reads your commands after you press enter, it evaluates them, it prints the results, and then waits for your next input to read. Type a = 1 and then press enter. Then type a + 10 and press enter. It allows you to enter your instructions one-by-one in a convenient, interactive manner.
In [ ]:
# Remember, lines starting with # comments and are not run.
a = 5
'''Multiline
comments
done
like
this.'''
if a > 1:
print('Greater than 1.')
else:
print('Not greater than 1.')
In Python, we have syntatically important whitespace. In other words, you have to indent certain things. This is different than most other languages where curly braces {} are used to set code blocks apart. This, for example, would not work:
a = 5
if a > 1:
print('Greater than 1.')
else:
print('Not greater than 1.)
This takes some getting used to, but is a blessing in disguise because it forces you to write cleaner and more understandable code.
If you come from another programming language, you'll also notice that we don't have to specify the types of our variables. The 'a' in the example above is automatically presumed to be a number because we put a number in it. It will happily treat it as a number until we do something un-number-like with it, at which point Python will complain.
To compare with a similar Java program (notice type designations and curly braces):
public class ProgramInJava {
public static void main(String[] args) {
int a = 5;
if (a > 1) {
System.out.println("Greater than 1.");
} else {
System.out.println("Not greater than 1.");
}
}
}
Normally, this would have indentation to make it clearer, but it has been removed for the purposes of demonstration.
In [ ]:
# You assign variables with the equals sign
a = 5
# Not to be confused with equality
5 == 5
In [ ]:
# Functions
def functiony(my_input):
s = 'Functions process input and give outputs like ' + my_input
return s
# We invoke functions with parenthesis
functiony('rutabega')
In [ ]:
# Loops
for item in [1, 2, 3, 4, 5]:
print(item * 5)
In [ ]:
# Indexing is 0-based like other C languages
my_list = [0, 1, 2, 3]
print('First item of list is ' + str(my_list[0]))
print('Last item of list is ' + str(my_list[-1]))
# WE can also slice ranges like this
print(my_list[0:2])
# Or this
print(my_list[1:])
# Or this
print(my_list[:2])
In [ ]:
# Exceptions are straightforward.
try:
print(x)
except NameError as e:
print('Name not found!')
In [ ]:
# We can also create objects for object-oriented programming
class Classy(object):
def __init__(self):
self.attribute = 'Attribute!'
def method(self):
return 'Method invoked!'
c = Classy()
# When you see a period, you're accessing a part of it
c.attribute
If you ever see a % (percent) sign in IPython code where you wouldn't expect it otherwise, it's pretty safe to assume that you're triggering some of IPython's "magic" commands. These commands will let you do everything from running external commands to timing how quickly certain calculations run. Some of the more common ones you will see are:
%time
Which times how long it takes for your cell to run, and:
%matplotlib inline
Which makes plotting functions draw in your browser instead of in a separate window.
In [ ]:
# Here is an example of %timeit. Use magic.
%timeit import time; time.sleep(.1);
In [ ]:
# Run this cell to enter the variable
text = 'I am a text string'
In [ ]:
# After that, we can autocomplete by pressing TAB
# Add a period to the end of the text variable.
# This will allow you to access attributes.
# Move until after the period, and press TAB.
# A window should come up giving you your options.
# Choose the "split" function with your arrow keys.
# Add parenthesis to invoke the function.
text
In [ ]:
# Putting a question mark will bring up a help window.
text?
# Don't forget the built in dir() method either, which allows inspection.
dir(text)[-5:]