1 / 23

I210 review Fall 2011, IUB

I210 review Fall 2011, IUB. Python is. High -level programming High-level versus machine language Interpreted Language Interpreted versus compiled. Variables. Variable : Represents a value; provides way to get at information in computer memory

sanam
Download Presentation

I210 review Fall 2011, IUB

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. I210 reviewFall 2011, IUB

  2. Python is • High-level programming • High-level versus machine language • Interpreted Language • Interpreted versus compiled

  3. Variables • Variable: Represents a value; provides way to get at information in computer memory • Assignment statement: Assigns a value to a variable; creates variable if necessary • Rules for legal variable names • Can contain only numbers, letters, and underscores • Can’t start with a number • Can’t be a keyword (del, elif, else, except, for , from, global, if, import, in, is, not, or, print, return, try, while, with)

  4. Data Types • Data type: sequences (containers) • Strings (a sequence of letters) • Tuples (a sequence of elements of any type; immutable) • Lists (a sequence of elements of any type; mutable) • Dictionary is NOT a sequence • How to access the elements in a sequence • Sequential access (using for and while loops) • Indexing & Slicing • Removing and adding elements • Important sequence operators and functions, len([1, 2, 3]), ”a" in "abc", [1, 2, 3].index(1)

  5. Mathematical Operators

  6. Indexing & Slicing Sequences inventory = ["sword", "armor", "shield", "healing potion"] inventory[0] ? inventory[0][1]? inventory[0:2]?

  7. List Methods languages = ["Python", "C++", "Java", "HTML"] • languages.append("FORTRAN") • languages.remove("C++") • languages.sort() • languages.count"C++") • languages.index("Python") • languages.insert(0, "PHP") • languages.pop()

  8. Using the Right Types • Python does not need to specify the type of a variable in advance (by contrast, C does) Python: cost = 10 C: int cost = 10; • Important to know which data types are available • Equally important to know how to work with them • If not, might end up with program that produces unintended results • Converting values: e.g., int(“3”) = 3

  9. Lists versus Tuples invent_list = ["sword", "armor", "shield", "healing potion"] invent_tuple = ("sword", "armor", "shield", "healing potion") invent_list[0] = "money" is OK!! invent_tuple[0] = "money" ERROR • Lists are mutable(we can dynamically change the individual elements!); but tuples are immutable • Strings are immutable word = "sword” word[0] = "S" ERROR word = "Sword" is OK!!

  10. Using Dictionaries • Dictionary: A mutable collection of key-valuepairs geek = {"404" : "clueless.", "Uninstalled" : "being fired."} • Unlike tuples and lists, dictionaries don’t organize data into sequences, but pairs • Look up a key to get a value geek["404"]

  11. Branching Structures • Branches based on a condition/conditions • if • if-else • if-elif-else • Condition: Expression that is True or False • Often create conditions by comparing values • Treating values as conditions: Any empty (None) or zero value is False • Compound conditions (logical operators) • and, or, not

  12. Branching Structures Branches based on a condition/conditions A block of code

  13. Using Indentation to Create Blocks Correct: if password == "secret": print "Access Granted" else: print "Access Denied” Incorrect: if password == "secret": print "Access Granted” else: print "Access Denied"

  14. Loop Structure • Need to know when and how to use for and while loops correctly • for loops: iterate over the elements in a sequence • while loops: repeat a block of code as long as a condition is • insertion_sort.py

  15. The while Loop while condition: <block> while response != "Because.": response = raw_input("Why? ”) • Repetition based on a condition • Allows you to repeat section of code as long as some condition is True • Like if statement, in that it tests a condition and executes associated block if condition True • But, after block, repeats condition test; if condition still True, repeats block • Continues process until condition tests False

  16. The continue & break Statements while True: count += 1 # end loop if count is greater than 10 if count > 10: break # skip 5 if count == 5: continue print count • continue jumps to top of loop to check condition • break causes a loop to end immediately

  17. Using for Loops • for loop • Likewhile loop, repeats a loop body • Unlike while loop, doesn’t repeat based on condition • Repeats loop body for each element in a sequence • Ends when it reaches end of the sequence • e.g., go through sequence of game titles and print each

  18. Counting Forward, By Fives, and Backwards # counting forward for i in range(10): print i, # counting by fives for i in range(0, 50, 5): print i, # counting backwards for i in range(10, 0, -1): print i,

  19. Functions • How to write functions • How to receive and return values • Not all functions take arguments, and not all functions return values!! • Understand local and global variables • And don’t forget to call functions defmy_func(): print "this function does nothing" my_func()

  20. Working with Files • Open a file ("r", "w") • Read/write • Read from text files; readline(), readlines() • Write to text files (permanent storage); write(), writelines() • Close the file text_file = open("read_it.txt", "r”) line1 = text_file.readline() text_file.close() • Loop through a file text_file = open("read_it.txt", "r") for line in text_file: print line

  21. Types of Errors • Syntax errors • “Computer doesn’t understand what I wrote, because I made a typo” • Logical Errors • Program does not perform correctly • Debugging • Runtime Error • The program saves and begins to execute, then crashes, usually after receiving input • try-except statements

  22. Handling Exceptions try: num = float(raw_input("\nEnter a number: ")) except(ValueError): print "That was not a number!" else: print "You entered the number", num • Can add single else clause after all except clauses • else block executes only if no exception is raised • num printed only if assignment statement in the try block raises no exception

  23. A Sample Question • Write a function that accepts a filename and reads in the comma-separated numbers from the text file. The function saves the numbers in a list, calculates and displays the average of the numbers, and return the list of numbers. • Please work out the practice midterm

More Related