To Import a library
import math
import string
Comments
# whole line of comment
print stuff #remainder is comment
Loops
for char in str:
print char
while i <= max: print i
Conditionality
if input == type("a") and output == type('a'):
print "input is string, output is char"
elif input == type("a") and not output == type('a'):
print "input is string, output is NOT char"
else:
print "unknown..."Basic Maths
a*b # multiplication
a**b # a to the power b
a/b # division
a+b # addition
a-b # subtraction
# -------
float(a) # convert to float
int(a) # convert to int
# -------
math.pi # constant
math.sin(angle) # function
strings
a = "abcdefg"
b = "hijklmn"
a+b # abcdefghijklmn (concatination)
a**2 # abcdefgabcdefg (multiplicity)
a[1] # b
a[0:2] # ab
a[3:] # defg
a[:3] # abc
# ------
string.find(haystack, needle) # find needle in haystack
string.lowercase # abcdefghijklmnopqrstuvwxyz
string.uppercase # ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits # 0123456789
string.whitespace # contains all whitespace characters eg. \n \t %20 ...
Important:: like in C, strings cannot be altered once initialised.
Lists
myList = [10, 20, 30]
myList = ["string", 3, '4']
myList[-1] # 20 (counts backwards)
len(myList) # 3
del myList[1] # [10, 30] (deletion)
myPointer = myList # (Aliasing)
myCopy = myList[:] # (Independent Copy)
myList = string.split("a b c d e", 'c') # split around 'c's
# myList = ["ab", "de"]
myNewList = string.Join(myList, 'c') # joins with 'c'
# myNewList = myList = "abcde"
Functions
def myFunction(myArgument)
result = myArgument * 2
result = result / 2
return result
- Functions can return arrays, tuples
- ...
Keyboard IO
# Text Input
prompt = "Type Now!"
userInput = raw_input(prompt) # text or numerical
userInput = input(prompt) # numerical only (else error)
print "output text", outputVar # print to Terminal
0 comments:
Post a Comment