Python CheatSheet
Python CheatSheet
Python CheatSheet
1
General Information Numbers
Whitespace matters! Indent where needed. total = 3 * 3 # 9
Import modules with "import modulename" total = 5 + 2 * 3 # 11
# This is a comment cost = 1.50 + 3.75 # 5.25
print("Hello, World!") # prints to screen total = int("9") + 1 # 10
Conditional Statements Strings
if isSunny: title = 'Us and them'
print('It's sunny!') # most list operations work on strings
elif 90 <= temp < 100 and bath > 80: title[0] # 'U'
print('Bath is hot and full!') len(title) # 11
elif not ((job == 'qa') or (usr == 'adm')): title.split(' ') # ['Us', 'and', 'them']
print('Match if not qa or adm') ':'.join(['A','B','C']) # 'A:B:C'
else: nine = str(9) # convert int to string
print('No match. Job is ' + job) title.replace('them', 'us') # Us and us
Lists Tuples
scores = ['A', 'C', 90, 75, 'C'] Like lists, except they cannot be changed
scores[0] # 'A' tuple1 = (1,2,3,"a","z") # Creates tuple
scores[1:3] # 'C', 90 tuple1[3] # 'a'
scores[2:] # 90, 75, 'C' Dictionaries
scores[:1] # 'A'
scores[:-1] # 'A', 'C', 90, 75 votes = {'red': 3, 'blue': 5}
len(scores) # 5 votes.keys() # ['blue', 'red']
scores.count('C') # 2 votes['gold'] = 4 # add a key/val
scores.sort() # 75, 90, 'A', 'C', 'C' del votes['gold'] # deletes key
scores.remove('A') # removes 'A' votes['blue'] = 6 # change value
scores.append(100) # Adds 100 to list len(votes) # 2
scores.pop() # removes the last item votes.values() # [6, 3]
scores.pop(2) # removes the third item 'green' in votes # False
75 in scores # True votes.has_key('red') # True