python

Slice

python

You can get a list from a list by slicing it. Like so: >>> spam ['cat', 'bat', 'rat', 'elephant'] >>> spam[1:4] ['bat', 'rat', 'elephant'] The first integer is the index where the slice starts. The slice is up to the second number but doesn’t include the value at the second integer. You can leave out the first index or second index and get a list starting from the beginning up until that point, or from the index to the end of the list. ...

sort()

python

Lists of number or string values can be sorted with the sort() method. >>> spam = [2, 5, 3.14, 1, -7] >>> spam.sort() >>> spam [-7, 1, 2, 3.14, 5] You can also sort in reverse. >>> spam.sort(reverse=True) >>> spam [5, 3.14, 2, 1, -7] Sorts the list in place Can’t sort mixed type lists. (i.e. numbers & strings) Uses ASCIIbetical order ASCIIbetical sorting. >>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats'] >>> spam. ...

split()

python

Allows splitting a string into multiple strings. By default splits at whitespace characters. >>> 'My name is Simon'.split() ['My', 'name', 'is', 'Simon'] You can pass a different delimiter if you want. >>> 'MyABCnameABCisABCSimon'.split('ABC') ['My', 'name', 'is', 'Simon']

String Interpolation

python

Instead of using string concatenation an often easier way is to use string interpolation. >>> name = 'Al' >>> age = 4000 >>> 'My name is %s. I am %syears old.' % (name, age) 'My name is Al. I am 4000 years old.'

String Literals

python

A string literal is a string surrounded by single or double quotes. 'This is a string literal' "This is also a string literal" If you need to have an apostrophe in a string use double-quotes. "That is Alice's cat." See also # Escape characters

Styling Classes

python

Class names should be written in CamelCase. Every class should have a docstring immediately following the class definition. Use blank lines between methods in a class Use 2 blank lines to separate classes If you need to import a module from the standard library and a module you wrote place the import statement for the standard library module first. Then add a blank line, and the import the module you wrote on the next line. ...

sys.exit()

python

Python programs always terminate if they reach the EOF. But, you can force a program to terminate or exit at any point by calling the sys.exit() function. import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed ' + response + '.')