I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.

Slides:



Advertisements
Similar presentations
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Advertisements

Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
Guide to Programming with Python
Jay Summet CS 1 with Robots IPRE Python Review 1.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Chapter 2 Writing Simple Programs
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Guide to Programming with Python
Python Control of Flow.
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
The University of Texas – Pan American
4. Python - Basic Operators
Fundamentals of Python: First Programs
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Guide to Programming with Python Chapter Three Branching, while Loops, and Program Planning: The Guess My Number Game.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Mastery Objective: Students will understand how to use while loops in computer programming.
If statements while loop for loop
Flow of Control Part 1: Selection
Built-in Data Structures in Python An Introduction.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
COMP 171: Data Types John Barr. Review - What is Computer Science? Problem Solving  Recognizing Patterns  If you can find a pattern in the way you solve.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Chapter 2 Writing Simple Programs
String and Lists Dr. José M. Reyes Álamo.
Python Review 1.
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Tuples and Lists.
Guide to Programming with Python
Python: Control Structures
Programming Mehdi Bukhari.
If, else, elif.
Exceptions and files Taken from notes by Dr. Neil Moore
Arrays, For loop While loop Do while loop
Arithmetic operations, decisions and looping
Topics Introduction to File Input and Output
Guide to Programming with Python
Exceptions and files Taken from notes by Dr. Neil Moore
CS190/295 Programming in Python for Life Sciences: Lecture 6
T. Jumana Abu Shmais – AOU - Riyadh
I210 review.
3 Control Statements:.
ERRORS AND EXCEPTIONS Errors:
String and Lists Dr. José M. Reyes Álamo.
Programming Errors Key Revision Points.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
For loops Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Presentation transcript:

I210 review Fall 2011, IUB

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

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) 3

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) 4

Mathematical Operators

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

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 ()

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 8

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!!

Using Dictionaries Dictionary: A mutable collection of key- value pairs 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"] 10

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 11

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

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" 13

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 14

The while Loop while condition: 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 15

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 16

Using for Loops for loop –Like while 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 17

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, 18

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 def my_func(): print " this function does nothing " my_func() 19

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

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

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 22

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 23