Python 101 1

662 views

Published on

Python 101 slides from Lets code group!
https://www.facebook.com/letscodeblacksburg

1 Comment
1 Like
Statistics
Notes
No Downloads
Views
Total views
662
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
33
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide

Python 101 1

  1. 1. Python 101McBryde 101Feb 22, 2013
  2. 2. Overview for Today1. Setting up Python2. Background on Python3. Basics of Python4. Data Structures in Python5. Control Structures in Python6. Functions in Python
  3. 3. Things you should doAsk questions! If you are confused, there is a 80% chance thatsomeone else is even more confused.Participate! Were all friends here. Tell us if were going too slowly.Tell us if were boring. Tell us if have an idea forsomething.Follow along! Open up Python and try stuff!
  4. 4. Setting up Python
  5. 5. Download & Install Pythonhttp://www.python.org/download/Run pythonWindows: python.exeMac/Linux: python
  6. 6. Background on Python
  7. 7. What is Python?● A language● An interpreter● A reference to a British sketch comedy: "Monty Pythons Flying Circus" (The documentation is full of jokes referencing theshow)
  8. 8. Why Python?● Traditional languages (C++, C, Java) evolved for large-scale programming● Scripting language (Perl, Python) evolved for simplicity and flexibility
  9. 9. The Python Language● Free!● Elegant and Powerful!● Cross-Platform!● Tons of useful modules!● Chock full of technical buzzwords! ○ Object-oriented, dynamic-typing
  10. 10. The "Zen" of PythonBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated....Readability Counts... (Its actually a lot longer)
  11. 11. The Basics
  12. 12. Printing in Python>>> print "Hello World."Hello World.Meanwhile, in Java land:public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello World"); }}
  13. 13. Input in Python>>> input("Tell me something: ")Tell me something:Type something in and press enter
  14. 14. Comments in Python>>> # This is a comment...The following will NOT work:/*Multiline comment in Java*/// Single line comment in Java
  15. 15. Scripts in Python1. In your IDE/Text Editor, write # My first program! print "Hello", "World"2. Save the file as helloworld.py3. From the terminal, > python helloworld.py Hello World.
  16. 16. Congratulations!You are now all Python programmers.
  17. 17. Basic Data
  18. 18. Values in Python-5 # Integer type23.1 # Float type"Some words" # String typeTrue # Boolean typeVariables in Pythonage = 23miles_from_home = 301.36name = "Cory Bart"has_dog = False
  19. 19. OperatorsNumerics Strings1 + 4 "Hello " + "World"2 - 3 "Repeat" * 54 * 110.0 / 2 Comparisons10.5 // 2 10 >= 52 ** 4 3 < 8022 % 12 5 == 10 3 != 3
  20. 20. Operators continued...Boolean logicTrue and FalseTrue or Truenot True
  21. 21. Exercisegiven a string myString and anumbernumRepetitions, return myStringmultiplied numRepetitions times.multiplyString(a, 4) → aaaamultiplyString(Hello, 2) → HelloHellomultiplyString(Python, 3) →PythonPythonPython
  22. 22. Control and Data Structures
  23. 23. If statementsif has_dogs: print "Has dogs"elif age >= 25: print "Can rent a car"elif name == "Ellie" or name == "Becky" print "Is awesome!"else: print "Not a great fellow"*Note the white-space!*
  24. 24. Defining functionsdef add(first, second): return first + secondvalue = add(10, 5)
  25. 25. ExerciseWrite a function that can compute tips for ameal, given the price and how generous theuser is.# price: float# generous: string, either "stingy"# or "generous"# returns a float indicating tipdef calculate_tip(price, generosity): ...
  26. 26. Multiple returns!def flip_coordinates(pos): x, y = pos return -x, -yx, y = flip_coordinates((5, -5))
  27. 27. SequencesLists are Mutable and Ordereda_list = [1, 3, 2]Tuples are Immutable and Ordereda_tuple = (1, 2, 3)Sets are Mutable, Unordered, and Uniquea_set = set([1, 2, 3])Dictionaries are Key-Value pairsa_dictionary = {A: 1, B: 2, C: 3}Strings are immutable sequences of one-character Strings!a_string = "Also a sequence!"
  28. 28. Working with a listcolors = [red, blue, yellow, purple]Add to a listcolors.append(green) or colors.insert(index)Remove from a listcolors.pop() or colors.remove(index)
  29. 29. Sets are a little different>>> set([1, 1, 2, -2, 3, 3, 4])set([1, 2, -2, 3, 4])>>> set([1, 2, -2, 3, 4]).add(4)set([1, 2, -2, 3, 4])>>> set([1, 2, -2, 3, 4]).add(5)set([1, 2, -2, 3, 4, 5])
  30. 30. Tuples are a little different>>> my_tuple = (1, 2, 3, 4)>>> my_tuple.add(5)NOPE!Tuples will be more awesome when we get tofunctions.
  31. 31. Dictionaries are wonderful>>> scores = {"Cory": 32, "Ellie": 100, "Becky": 78}>>> print scores["Cory"]32
  32. 32. Working with sequencesGet an element of a sequence:"Puzzle"[2]Get the length of a sequencelen(set([1, 2, 3, 4, 5, 6]))Is something in a sequence?5 in (1, 2, 3, 4, 5)Get a sublist from a list[red, blue, yellow, green][1:2]There are many built-in functions for sequencessum((1, 2, 3, 4))min((5, 10, 15))
  33. 33. Strings have a ton of methods!"1, 2, 3, 4".split(",")",".join([1,2,3,4])" whitespace ".strip()"I am 22".replace("am", "was")"HeLlO wOrLd".swapcase()
  34. 34. Converting between typesstr(5) -> "5"int("10") -> 10float("10.0") -> 10.0bool(None) -> Falselist((1, 2, 3, 4)) -> [1,2,3,4]tuple([1, 2, 4, 8]) -> (1,2,4,8)
  35. 35. Truthiness in Python True FalseTrue False5 0-5 [][1, 2, 3] """Hello world" None items_left = [1, 2, 3] while items_left: print items_left.pop()
  36. 36. LoopingThe for-each loop is best! Listfor item in [1, 2, 3]: Set print item Tuple String File handlerYou can also use a while loop.while True: # do something
  37. 37. xrangefor value in xrange(5): print value01234
  38. 38. Iterating with indicesfor index, item in enumerate("ABCDE"): print index, item0 A1 B2 C3 D4 E
  39. 39. Iterating over Dictionarya_dictionary = {a:1,b:2}for key, value in a_dictionary.items(): print key, value
  40. 40. ExerciseWrite a program that will "translate" a sentenceinto Pyglatin:"We only speak Pyglatin in Pyrome"->"Eway onlyay peaksay Yglatinpay inay yromeay"
  41. 41. List comprehensionsYou can make a list by sticking a for loop inside![value*2 for value in range(10)][int(number) for number in "123456789"]
  42. 42. File I/Ofile = open(word_lists.txt, r)for line in file: print linefile = open(numbers.txt, w)for number in range(100): file.write(number)
  43. 43. Importingimport randomrandom.choice(("Heads", "Tails"))import sysprint sys.argsimport mathprint math.sqrt(36)
  44. 44. Command line arguments>python file.py this is a testInside of file.pyimport sysprint sys.argsOutputs[this, is, a, test]
  45. 45. What should I do next?The Python Challenge http://www.pythonchallenge.com/Online Books: http://tinyurl.com/interactivepython
  46. 46. Feedback● Facebook - http://tinyurl.com/letscode● Would you be interested in this formulating into a meetup group?● How often?● What would you like to learn next?● Does the location matter?● Any other feedback?● How large/small class size would you prefer?

×