Advertisement
Guest User

Untitled

a guest
Jan 29th, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.33 KB | None | 0 0
  1. Intro to Python
  2. ===============
  3.  
  4. What is python?
  5. ===============
  6. interpeted (programs are executed line by line instead of being compiled and then run)
  7. slower as a consequence : compiler can make passes over the code to optimize it
  8. dynamic typing (type-checking done at run-time rather than at compile time)
  9. type-checking : checking for expressions in which types are incorrectly used
  10. procedural + functional + object-oriented
  11. object-oriented : can define classes, instantiate objects
  12. procedural : do this, then this, then this
  13. functional : define functions, express the result of your program as an output of
  14. those functions
  15.  
  16. What's so great about python
  17. ============================
  18.  
  19. easy to use, learn
  20. good support network
  21. good documentation
  22. very readable
  23.  
  24. more technically:
  25. very powerful built-in functions and methods
  26. very powerful built-in data structures
  27. support for lambda functions
  28. type coercion
  29.  
  30. e.g. quicksort in python
  31.  
  32. Python vs C++
  33. =============
  34. not compiled
  35. dynamic typing (with type coercion)
  36. typically slower
  37. very few lines of code required
  38. 'batteries loaded' - most important functions/libraries preinstalled
  39. centralized package system (PyPy)
  40. REPL (read-eval-print loop) provided by IDLE
  41. use of whitespace to denote block structure rather than braces
  42.  
  43. def qs(ls):
  44. if ls == '[]': return []
  45. pivot = ls[0]
  46. less = [x for x in ls if x < pivot]
  47. more = [x for x in ls if x > pivot]
  48. equal = [x for x in ls if x == pivot]
  49. return qs(less) + qs(equal) + qs(more)
  50.  
  51. installing python
  52. python.org/download
  53. linux : pre-installed
  54.  
  55. simplest possible program
  56. print "Hello world!"
  57.  
  58. no need to load any libraries or define any 'main' function!
  59.  
  60. what a python program looks like
  61.  
  62. -stored in a .py file
  63. -one statement on one line
  64. -indentation is used to express block structure
  65.  
  66. how to use IDLE
  67. type in a statement or two, hit Enter
  68. quick and easy way to test out small pieces of code
  69. very useful when you're learning python to begin with!
  70.  
  71. comments
  72. --------
  73. single-line comments : #
  74. Multi-line comments : '''<comment (which may include newlines)>'''
  75.  
  76. variables
  77. ---------
  78. a = 1
  79. asdf = True
  80. b, c = 'abcdefghijklmnopqrstuvwxyz', -4.5
  81.  
  82. every variable has its own type
  83. types in Python: bool, int, str, float
  84.  
  85. when in doubt, use the type() function
  86. >>> type('i am a string!')
  87. <type 'str'>
  88. >>> type(-345)
  89. <type 'int'>
  90. >>> type(5.6)
  91. <type 'float'>
  92. and so on
  93.  
  94. can convert between types in certain cases!
  95. >>> int('678')
  96. 678
  97. >>> float(633)
  98. 633.0
  99.  
  100. representing numbers in python
  101. negative numbers: -2, -3
  102. floating point numbers: 5.7 -44.2
  103. large numbers: python adds an 'L'
  104.  
  105. >>> 42365376484
  106. 42365376484L
  107.  
  108. can convert between bin, hex, oct, dec
  109. to use a binary number as part of an expression: 0b01101 (precede it with a 0b)
  110. for hex: 0x, for oct: 0o
  111. >>> 0010
  112. 8 (python returns the value in dec)
  113.  
  114. basic operations with numbers
  115. -----------------------------
  116. x, y = 5, 6 #multiple assignment
  117. x + y
  118. x - y
  119. x * y
  120. x / y # in Python 2, truncates the answer
  121. x ** y # x raised to the power of y
  122.  
  123. conditionals
  124. ------------
  125. if 3 > 5:
  126. print "hello"
  127. else:
  128. print "world"
  129.  
  130. x = ['some_string']
  131. if len(x) == 0:
  132. print "x is empty"
  133. else:
  134. print "x has %d %s" %(len(x), 'elements' if len(x) > 1 else 'element')
  135.  
  136. else statement not compulsory
  137.  
  138. if not []: # the empty list evaluates to false
  139. print 3
  140.  
  141. functions
  142. ---------
  143. def function_name(function_arguments):
  144. <some code>
  145. return <some expression>
  146.  
  147. no need to mention the 'types' of formal arguments or return type of the function
  148.  
  149. returning a value is optional e.g.
  150.  
  151. def say_hello(name):
  152. print "hello %s" %(name)
  153.  
  154. we can also add a conditional to the return statement
  155. makes our code looks neater
  156.  
  157. def even_or_odd(number):
  158. return "even" if number%2 == 0 else "odd"
  159.  
  160. lists
  161. -----
  162. a = []
  163. a.append(3)
  164. a.append(True)
  165. a += ['hello', -4, 1.66, [3,44]]
  166. len(my_list)
  167. a[0]
  168. a[3]
  169. a[-1]
  170. a[-2]
  171. a[-1][1]
  172.  
  173. slicing
  174. a[:2]
  175. a[2:]
  176. a[:-1]
  177. a[:-3]
  178. a[2:5]
  179. a[2:-2]
  180. a[:40]
  181. a[:]
  182. a.insert(0, 'good')
  183. a.insert(-1, 'bye')
  184.  
  185. list comprehensions
  186. a = range(7)
  187. b = [x**2 for x in a]
  188. b = [x-3 for x in a[:-3]]
  189. b = [a[i] for i in range(len(a))]
  190.  
  191. reversing a list
  192. list(reversed(a)) # does not modify a
  193. a.reverse() # modifies a
  194.  
  195. sorting a list
  196. from random import shuffle
  197. a = range(10)
  198. shuffle(a)
  199. sorted(a) # returns a new list, does not modify a
  200. a.sort() # changes a
  201.  
  202. we can multiply lists by ints
  203. a = [0]*7
  204. but they are all references to the same object
  205. a = [[1,0]]*3
  206. a[0][1] = 2 # see what happens!
  207.  
  208. Q. Write a function that takes a list as input and returns the minimum element
  209. of the list. Try to do it in different ways
  210. A.
  211. def find_min(ls):
  212. return min(ls)
  213.  
  214. def find_min(ls):
  215. return sorted(ls)[0]
  216.  
  217. min = ls[0]
  218. for i in range(len(a)):
  219. if a[i] < min:
  220. min = a[i]
  221.  
  222. min = ls[0]
  223. for i in ls:
  224. min = i if i < min else min
  225.  
  226. tuples
  227. ======
  228. same as lists
  229. one exception: single element typles
  230. a = (1) # assigns 1 to a
  231. a = (1,) # assigns a one-element typle
  232. a = (1,2,3,4,5)
  233. a[2] = -1 # gives an error
  234. a.append(True) # gives an error
  235. a.sort() # no attribute
  236. a.reversed() # no attribute
  237. so, tuples are immutable! useful when building dicts
  238.  
  239. tuple(reversed(a))
  240. tuple(sorted(a))
  241. sorted(a)
  242.  
  243. can convert lists to tuples and vice versa
  244. tuple([3,4,5])
  245.  
  246. strings
  247. =======
  248. a = 'this is a string'
  249. a = "this is also a string"
  250. a = "now we're using a single quotation mark inside a string, so we're using
  251. double quotes"
  252. a = 'we can use "double quotation marks" inside single quotation marks'
  253. a = 'or we can use escape characters like this: he\'s'
  254. a = "this string has a newline character\n"
  255. a = 'to use a backlash in a string we have to escape it twice: \\'
  256. a = r'or we can use raw strings by putti\ng an r before the quotatio\n mark'
  257.  
  258. a = ' bcd '
  259. a.strip() # does not change a
  260. a = 'this is a sentence that i want to break into words'
  261. a.split() # does not change a
  262.  
  263. we can access strings and slice them like lists
  264. a = "hello world"
  265. a[3:8]
  266. a[-7]
  267.  
  268. strings are immutable
  269.  
  270. the join function:
  271. string.join(<iterable>)
  272. concatenates the elements of the iterable with the separator as 'string'
  273.  
  274. Q. Given a sentence, write a function to find the number of words it has
  275. A.
  276. def num_words(sentence):
  277. return len(sentence.split())
  278.  
  279. we can split according to different characters
  280. a = 'this,is,a,comma,separated,sentence"
  281. a.split(',')
  282.  
  283. a = '''this is a multi-line
  284. string. it can span as many lines as
  285. i want it to. it also includes newline
  286. characters'''
  287.  
  288. loops
  289. =====
  290. for i in range(0,4):
  291. print i
  292.  
  293. for i in range(0,4):
  294. print i,
  295.  
  296. i = 0
  297. while i < 10:
  298. print i
  299. i += 1
  300.  
  301. for i in range(5,19,4):
  302. print i
  303.  
  304. for x in [3,4,5]:
  305. pass
  306.  
  307. b = [x==2 for x in [3,4,5]]
  308.  
  309. Q. Write a function to zip two lists together
  310. A.
  311. def zip1(ls1, ls2):
  312. i, result = 0, []
  313. x = min([len(ls1), len(ls2)])
  314. while i < x:
  315. result.append((ls1[i], ls2[i]))
  316. i += 1
  317. return result
  318.  
  319. dictionaries
  320. ============
  321.  
  322. lists are useful for storing ordered data
  323. but what if we want to store a list of mappings?
  324.  
  325. say we want to store a list of courses for each student in IIT
  326. we don't care about the ordering of the students
  327. we can use a dict
  328.  
  329. a = {}
  330. a['freshie'] = ['ma105', 'ph105', 'cs101', 'hs101', 'me119']
  331. a['rohan'] = ['cs208', 'cs210', 'cs218', 'cs420', 'ma214', 'sc202']
  332.  
  333. and so on
  334.  
  335. >>> a
  336. {'rohan': ['cs208', 'cs210', 'cs218', 'cs420', 'ma214', 'sc202'],
  337. 'freshie': ['ma105', 'ph105', 'cs101', 'hs101', 'me119']}
  338.  
  339. >>> a.keys()
  340. ['rohan', 'freshie']
  341.  
  342. The mapping can be from any type to any other type
  343. However there are restrictions
  344. We cannot map lists to other items using a dict
  345. Since lists are mutable (type error: unhashable type: list)
  346. But tuples aren't, so we can use tuples in dicts
  347.  
  348. dict comprehensions
  349. a = {x:10-x for x in range(10)}
  350.  
  351. classes
  352. =======
  353.  
  354. class Student:
  355. def __init__(self, year, cpi, dept):
  356. self.year = year
  357. self.cpi = cpi
  358. self.dept
  359.  
  360. input
  361. =====
  362.  
  363. a = raw_input()
  364. print "Hello", a
  365.  
  366. files
  367. =====
  368. with open('path/to/file') as f:
  369. file_contents = f.readlines()
  370.  
  371. more functions: f.readline(), f.read(), f.write()
  372. <code dealing with file_contents)
  373.  
  374. a simple example of file handling: time_scraper.py
  375.  
  376. older method (no need to use in python 2.7):
  377. f = open('path/to/file')
  378. try:
  379. for line in f:
  380. <some code>
  381. finally:
  382. f.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement