Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017
|
|
- Marsha Hill
- 6 years ago
- Views:
Transcription
1 Chapter 6: Files and Exceptions COSC 1436, Spring 2017 Hong Sun 3/6/2017
2 Function Review: A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you would have to copy and paste this code each time def hello(): print('howdy!') def hello(name): ## def statement with parameter print('howdy!, name) def get_name(): name=input( Enter your name: ) return name
3 Function Review: Position argument and keyword argument def remainder(number, divisor): return number % divisor remainder(20, 7) # position argument remainder(number=20, divisor=7) #keyword argument remainder(divisor=7, number=20) #keyword argument
4 Function Review: LOCAL AND GLOBAL SCOPE Scopes matter for several reasons: o Code in the global scope cannot use any local variables. o However, a local scope can access global variables. o Code in a function s local scope cannot use variables in any other local scope. o You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.
5 Function Review: LOCAL AND GLOBAL SCOPE globvar = 0 def set_globvar_to_one(): # Needed to modify global copy of globvar global globvar globvar = 1 def print_globvar(): # No need for global declaration to read value of globvar print(globvar) set_globvar_to_one() print_globvar() # Prints 1
6 Function Review RANDOM random.randint(1,10) #generate random interger random.randrange(0,101,10) random.random() ##gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0). random.uniform(a, b) ##gives you a random floating point number in the range [a, b], (where rounding may end up giving you b). random.seed(a) ##This is the seed for the next random number random.seed( 10 ) print ("Random number with seed 10 : ", random.random()) # It will generate same random number random.seed( 10 ) print( "Random number with seed 10 : ", random.random())
7 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a file. The data can be read from the file a later time. The process of retrieving data from a file is known as reading data from the file. The term input file is used to describe a file that data is read from. Three steps that must be taken when a file is used by a program. Open the file : Opening a file create a connection between the file and the program. Opening an input file allows the program to read data from the file. Opening an output file usually creates the file on the disk and allows the program to write data to it. Process the file: In this step data is either written to the file ( if it is an output file) or read from the file (if it is an input file). Close the file : When the program is finished using the file, the file must be closed. Closing a file disconnects the file from the program.
8 Two Types of Files 1. Text file: A text file contains data that has been encoded as a text, using a scheme such as ASCII or Unicode. Even if the file contains numbers, those numbers are stored in the file as a series of characters. The file may be opened and viewed in a text editor. 2. Binary file: A binary file contains data that has not been converted to text. The data that is stored in a binary file is intended onl for a program to read. As a consequence, you cannot view the contents of a binary file with a text editor.
9 File Access Methods, Filenames and File Objects Two ways to access data stored in a file: Sequential access: access the data from the beginning of the file to the end of the file. Direct access file (also known as a random access file): you can jump directly to any piece of daa in the file without reading the data that comes from it. Filenames: Each of operating system has its own rules for naming files. Many system support the use of filename extensions, which are short sequences of characters that appear at the end of a filename preceded by a period (which is known as a dot ) File Object: is an object that is associated with a specific file and provides a way for the program to work with that file. In the program, a variable references the file object.
10 Opening a File Open function The open function creates a file object and associates it with a file on the disk. file_variable = open(filename, mode) file_variable is the name of the variable that will reference the file object. Filename is a string specifying the name of the file. Mode is a string specifying the mode (reading, writing ) in which the file will be opened (see table below) Mode r w a Description Open a file for reading only. The file cannot be changed or written to Open a file for writing. If the file already exists, erase its contents. If it does not exist, create it. Open a file to be written to. All data written to the file will be appended to the end. If the file does not exist, create it.
11 Specifying the Location of a File The same location as that of the program Pass a file name that does not contain a path as an argument to the open function, the Python interpreter assumes that the file s location is the same as that of the program. test_file = open( test.txt, w ) Specify a path as well as a filename and prefix the string with letter r. test_file = open( r C:\users\blake\temp\test.txt, w )
12 Writing Data to a file and Close a file file_variable.write(string) file_variable is a variable that references a file object, string is a string that will be written to the file. The file must be opened for writing(using the w or a mode) file_variable.close() Once a program is finished working with a file, it should close the file.
13 Code Example # This program writes three lines of data # to a file. def main(): # Open a file named philosophers.txt. outfile = open('philosophers.txt', 'w') # Write the names of three philosphers # to the file. outfile.write('john Locke\n') outfile.write('david Hume\n') outfile.write('edmund Burke\n') # Close the file. outfile.close() # Call the main function. main()
14 Appending Data to an Existing File a mode when open an output file in append mode. If the file already exists, it will not be erased. If the file does not exist, it will be created. When data is written to the file, it will be written at the end of the file s current contents
15 Reading Data From a File read() The read() method reads the file s contents. readline() readline() method reads a line form the file readlines() returns a list containing all the lines in the file
16 Reading Data From a File Use the file object s read method to read its entire contents into memory. Code example: # This program reads and displays the contents # of the philosophers.txt file. def main(): # Open a file named philosophers.txt. infile = open('philosophers.txt', 'r') # Read the file's contents. file_contents = infile.read() # Close the file. infile.close() # Print the data that was read into # memory. print(file_contents) # Call the main function. main()
17 readline method Initial read position John Locke\nDavid Hume\nEdmund Brurke\n Read Position Read position advanced to the next line John Locke\nDavid Hume\nEdmund Brurke\n Read Position Read position advanced to the end of the file John Locke\nDavid Hume\nEdmund Brurke\n Read Position
18 Concatenating a Newline to a String # This program gets three names from the user # and writes them to a file. def main(): # Get three names. print('enter the names of three friends.') name1 = input('friend #1: ') name2 = input('friend #2: ') name3 = input('friend #3: ') # Open a file named friends.txt. myfile = open('friends.txt', 'w') # Write the names to the file. myfile.write(name1 + '\n') myfile.write(name2 + '\n') myfile.write(name3 + '\n') # Close the file. myfile.close() print('the names were written to friends.txt.') # Call the main function. main()
19 Strip Characters in Python Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both ends of a string. If the characters to be removed are not specified then white-space will be removed strip() #removes from both ends lstrip() #removes leading characters (Left-strip) rstrip() #removes trailing characters (Right-strip)
20 Strip Characters in Python strip() #removes from both ends spacious = " xyz " print spacious.strip() lstrip() #removes leading characters (Left-strip) spacious = " xyz " print spacious.lstrip() rstrip() #removes trailing characters (Right-strip) spacious = "xyz " print spacious.rstrip()
21 Reading a String and Stripping the rstrip method Name = Joanne Manchester\n Name = Name.rstrip( \n ) Code example # This program reads the contents of the # philosophers.txt file one line at a time. def main(): # Open a file named philosophers.txt. infile = open('philosophers.txt', 'r') # Read three lines from the file line1 = infile.readline() line2 = infile.readline() line3 = infile.readline() # Strip the \n from each string. line1 = line1.rstrip('\n') line2 = line2.rstrip('\n') line3 = line3.rstrip('\n') # Close the file. infile.close() # Print the data that was read into # memory. print(line1) print(line2) print(line3) # Call the main function. main() Newline from it
22 Writing and Reading Numeric Data str method to convert numeric data to string str(number) # This program demonstrates how numbers # must be converted to strings before they # are written to a text file. def main(): # Open a file for writing. outfile = open('numbers.txt', 'w') # Get three numbers from the user. num1 = int(input('enter a number: ')) num2 = int(input('enter another number: ')) num3 = int(input('enter another number: ')) # Write the numbers to the file. outfile.write(str(num1) + '\n') outfile.write(str(num2) + '\n') outfile.write(str(num3) + '\n') # Close the file. outfile.close() print('data written to numbers.txt') # Call the main function. main()
23 Using Loops to Process Files Use a loop to process the data in file. Open the file Use readline to read the first line from the file Did readline return an empty string? No (false) Process the item that was just read from the file Use readline to read the next line from the file Yes (true) Close the file
24 While Loop and For Loop while line!= for line in file Code example read_sales.py (p255) Read_sales2.py (p266)
25 Exceptions An exception is an error that occurs while a program is running, causing the program to abruptly halt. Use the try/except statement to gracefully handle exceptions. Try: statement statement etc Except ExceptionName: statement statement etc Code example : gross_pay2.py p275 Multiple Exception handling Try: except ExceptionName: except ExceptionName: except ExceptionName: Code example: sales_report1.py p279
26 Exceptions
27 Exceptions
28 Exceptions
29 Exceptions
30 Exceptions
31 Exception - continue One except clause to catch all Exceptions try: statement statement except: statement Exception s Default error Message try: statement except Exception as err: statement else clause try: statement except Exception as err: statement else: statement finally clause try: statement except Exception as err: statement Finally: statement etc
32 Exception - continue try: x = float(raw_input("your number: ")) inverse = 1.0 / x except ValueError: print ("You should have given either an int or a float" ) except ZeroDivisionError: print "Infinity" finally: print("there may or may not have been an exception.")
33 Exception - continue try: x = float(raw_input("your number: ")) inverse = 1.0 / x except ValueError: print ("You should have given either an int or a float" ) except ZeroDivisionError: print "Infinity" finally: print("there may or may not have been an exception.")
34 Lab and assignment Lab: programming Exercises #1,#2,#3,#5 Assignment: Programming Exercises #8, #9,#10 Due After midterm test.
Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016
Chapter 6: Files and Exceptions COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a
More informationAnnouncements COMP 141. Writing to a File. Reading From a File 10/18/2017. Reading/Writing from/to Files
Announcements COMP 141 Reading/Writing from/to Files Reminders Program 5 due Thurs., October 19 th by 11:55pm Solutions to selected problems from Friday s lab are in my Box.com directory (LoopLab.py) Programming
More informationChapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017
Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017 Defining and Calling a Void Function Function Name Roles: python requires that you follow the same rules that you follow when naming
More informationPROGRAMMING, DATA STRUCTURES AND ALGORITHMS IN PYTHON
NPTEL MOOC PROGRAMMING, DATA STRUCTURES AND ALGORITHMS IN PYTHON Week 5, Lecture 3 Madhavan Mukund, Chennai Mathematical Institute http://www.cmi.ac.in/~madhavan Dealing with files Standard input and output
More informationFile I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12
File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #7 is DUE on MONDAY (3/12) Lab
More informationMULTIPLE CHOICE. Chapter Seven
Chapter Seven MULTIPLE CHOICE 1. Which of these is associated with a specific file and provides a way for the program to work with that file? a. Filename b. Extension c. File object d. File variable 2.
More informationIntroduction to programming using Python
Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 6-2 1 Objectives To open a file, read/write data from/to a file To use file dialogs
More informationChapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018
Chapter 5 Functions Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018 while Loop Repetition Review A Condition-Controlled Loop Causes a statement or set of statements to repeat as long as a condition is true.
More informationPreviously. Iteration. Date and time structures. Modularisation.
2017 2018 Previously Iteration. Date and time structures. Modularisation. Today File handling. Reading and writing files. In order for a program to work with a file, the program must create a file object
More informationPreviously. Iteration. Date and time structures. Modularisation.
Lecture 7 Previously Iteration. Date and time structures. Modularisation. Today Pseudo code. File handling. Pseudo code Pseudocode is an informal high-level description of the operating principle of a
More informationSpring 2011 PROGRAMMING ASSIGNMENT Encrypted Message Program Due Tuesday, May 17th
COSC 175 Spring 2011 PROGRAMMING ASSIGNMENT Encrypted Message Program Due Tuesday, May 17th Dierbach For this programming assignment, you are to develop a Python program that can both encrypt a message
More informationFile Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO
File Processing CS 112: Introduction to Programming: File IO Coming up: File Processing 1 File Processing Sequence 1. Open the file 2. Read from the file 3. Close the file In some cases, not properly closing
More informationIntroduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017
Introduction Programming Using Python Lecture 8 Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017 Chapter 12 Inheritance and Class Design Review Suppose you will define classes to model circles, rectangles, and
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 5 Part 3 & Review The Department of Computer Science Multi-Line Strings Files: Multi-line Strings A file is a sequence of
More informationFiles. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington
Files CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 The Need for Files Suppose that we have to write a program that: takes a book (or a set of
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 4 (End of Chapter) File IO Coming up: File Processing 1 File Processing! The process of opening a file involves associating a file on disk
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 5 Part 3 & Review The Department of Computer Science Multi-Line Strings -2-1 Files: Multi-line Strings A file is a sequence
More informationFILE HANDLING AND EXCEPTIONS
FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob
More informationFile processing and decision structures
File processing and decision structures Michael Mandel Lecture 4 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture04final.ipynb
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationFile Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming
File Operations Files are persistent data storage titanicdata.txt in PS07 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a running program
More informationLECTURE 4 Python Basics Part 3
LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,
More informationFile Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming
File Operations Files are persistent data storage titanicdata.txt in PS06 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a program (exists
More informationFiles. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function
Files Files File I/O Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function open(file, mode='r', buffering=-1, encoding=none,...
More informationSequences: Strings, Lists, and Files
Sequences: Strings, Lists, and Files Read: Chapter 5, Sections 11.1-11.3 from Chapter 11 in the textbook Strings: So far we have examined in depth two numerical types of data: integers (int) and floating
More informationCPTS 111, Fall 2011, Sections 6&7 Exam 3 Review
CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review File processing Files are opened with the open() command. We can open files for reading or writing. The open() command takes two arguments, the file name
More informationCSCA20 Worksheet Working with Files
CSCA20 Worksheet Working with Files 1 Philosophical question: what s a file? Q. A general answer? Q. A programmer s answer? 2 Opening and closing a file To start using a file, given its filename, you have
More informationCSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray
CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray 01-c: Python review 2 python review: lists strings 3 Strings lists names = "John, Paul, Megan, Bill, Mary" names
More informationFile Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17
CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 1 Discussion Sections 02-08, 16, 17 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Become familiar with input and output (I/O) from
More informationISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings
ISE 101 Introduction to Information Systems Lecture 3 Objectives: While loops Strings While Loops Write a Python script that computes the sum of squares from 1 to 5. sum = 0; sum = sum + 1**2; sum = sum
More informationFiles on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.
1 z 9 Files Petr Pošík Department of Cybernetics, FEE CTU in Prague EECS, BE5B33PRG: Programming Essentials, 2015 Requirements: Loops Intro Information on a computer is stored in named chunks of data called
More informationExceptions and File I/O
Lab 6 Exceptions and File I/O Lab Objective: In Python, an exception is an error detected during execution. Exceptions are important for regulating program usage and for correctly reporting problems to
More informationData Structures (list, dictionary, tuples, sets, strings)
Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;
More informationFiles. Reading from a file
Files We often need to read data from files and write data to files within a Python program. The most common type of files you'll encounter in computational biology, are text files. Text files contain
More informationConverting File Input
Converting File Input As with the input func.on, the readline() method can only return strings If the file contains numerical data, the strings must be converted to the numerical value using the int()
More informationStrings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break
Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation
More information2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.
CMSC 0 Fall 0 Name Final Review Worksheet This worksheet is NOT guaranteed to cover every topic you might see on the exam. It is provided to you as a courtesy, as additional practice problems to help you
More informationPart III Appendices 165
Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.
More informationCS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016
CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016 In this course you will start by building a compiler for a language called Xi. This is an imperative,
More informationLecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming
Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationCS1114 Spring 2015 Test ONE ANSWER KEY. page 1 of 8 pages (counting the cover sheet)
CS1114 Spring 2015 Test ONE ANSWER KEY page 1 of 8 pages (counting the cover sheet) For the following questions, use these variable definitions a = 36 b = 3 c = 12 d = '3' What is the type and value of
More informationInput and Output File (Files and Stream )
Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14 Scope Describe the fundamentals of input & output files. Use data files for input & output purposes. Files Normally,
More information1 Strings (Review) CS151: Problem Solving and Programming
1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote
More informationText File I/O. #include <iostream> #include <fstream> using namespace std; int main() {
Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead,
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationOverview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017
Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More informationIntroduction to: Computers & Programming: Review prior to 1 st Midterm
Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in
More informationIntroduction to Python (All the Basic Stuff)
Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions
More informationPython in 10 (50) minutes
Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are
More informationTextbook. Topic 8: Files and Exceptions. Files. Types of Files
Textbook Topic 8: Files and A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools. -Douglas Adams 1 Strongly Recommended
More informationLevel 3 Computing Year 2 Lecturer: Phil Smith
Level 3 Computing Year 2 Lecturer: Phil Smith We looked at: Previously Reading and writing files. BTEC Level 3 Year 2 Unit 16 Procedural programming Now Now we will look at: Appending data to existing
More informationScientific Computing: Lecture 3
Scientific Computing: Lecture 3 Functions Random Numbers More I/O Practice Exercises CLASS NOTES Ò You should be finishing Chap. 2 this week. Ò HW00 due by midnight Friday into the Box folder Ò You should
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationText Data, File I/O, and Exceptions
Text Data, File I/O, and Exceptions Strings, revisited Formatted output File Input/Output Errors and Exceptions String representations Introduction to Computing Using Python A string value is represented
More informationOCR Pseudocode to Python
OCR Pseudocode to Python Syntax Topic OCR Pseudocode Result Python Local variables x = 10 x = 10 playername = "Sam" playername = "Sam" Global variables global currentuserid = 223 In Python, variables are
More informationChapter 10: Creating and Modifying Text Lists Modules
Chapter 10: Creating and Modifying Text Lists Modules Text Text is manipulated as strings A string is a sequence of characters, stored in memory as an array H e l l o 0 1 2 3 4 Strings Strings are defined
More informationDownloaded from Chapter 2. Functions
Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create
More information2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1
2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference
More informationPrinciples of Computer Science I
Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested
More informationCS 115 Lecture 4. More Python; testing software. Neil Moore
CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement
More informationTopic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved
Topic 2 1. Reading and writing text files 2. Reading text input 3. Writing text output 4. Parsing and formatting strings 5. Command line arguments 6. Random access and binary files Reading Words and Characters
More informationAlgorithms and Programming
Algorithms and Programming Lecture 4 Software design principles Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types
More information#11: File manipulation Reading: Chapter 7
CS 130R: Programming in Python #11: File manipulation Reading: Chapter 7 Contents File manipulation Text ASCII files Binary files - pickle Exceptions File manipulation Electronic files Files store useful
More informationPYTHON- AN INNOVATION
PYTHON- AN INNOVATION As per CBSE curriculum Class 11 Chapter- 2 By- Neha Tyagi PGT (CS) KV 5 Jaipur(II Shift) Jaipur Region Python Introduction In order to provide an input, process it and to receive
More informationGuide to Programming with Python. Algorithms & Computer programs. Hello World
Guide to Programming with Python Yuzhen Ye (yye@indiana.edu) School of Informatics and Computing, IUB Objectives Python basics How to run a python program How to write a python program Variables Basic
More informationChapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017
Chapter 2 Input, Processing and Output Hong Sun COSC 1436 Spring 2017 Jan 30, 2017 Designing a Program Designing a Program o Programs must be carefully designed before they are written. Before beginning
More informationMidterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals
Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List
More informationProgramming in Python 3
Programming in Python 3 Programming transforms your computer from a home appliance to a power tool Al Sweigart, The invent with Python Blog Programming Introduction Write programs that solve a problem
More informationConvenient way to deal large quantities of data. Store data permanently (until file is deleted).
FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.
More informationPython Tutorial. Day 1
Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env
More informationChapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018
Chapter 8: More About Strings COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Creating Strings The str Class s1 = str() # Create an empty string s2 = str("welcome") # Create a string Welcome Python provides
More informationUNIT II DATA, EXPRESSIONS, STATEMENTS. Python being a interpreter language has two modes namely: Interactive mode, Script Mode or Normal mode
UNIT II DATA, EXPRESSIONS, STATEMENTS PYTHON INTERPRETER AND INTERACTIVE MODE: Python being a interpreter language has two modes namely: Interactive mode, Script Mode or Normal mode INTERACTIVE MODE: -
More informationChapter 12: Advanced File Operations
Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:
More informationLoop structures and booleans
Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb
More informationPython File Modes. Mode Description. Open a file for reading. (default)
UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
More informationCOP4020 Programming Assignment 1 - Spring 2011
COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to
More informationPython: common syntax
Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable
More informationIntroduction to python
Introduction to python 13 Files Rossano Venturini rossano.venturini@unipi.it File System A computer s file system consists of a tree-like structured organization of directories and files directory file
More informationTopic: List processing (with application to files)
ICS 31 UC IRVINE FALL 2017 DAVID G. KAY Quiz 7 To get credit for this quiz, use the Quiz tool at eee.uci.edu to enter your answers, within the Sunday-to- Tuesday quiz period. Problem 1 (10 points) Topic:
More informationPython review. 1 Python basics. References. CS 234 Naomi Nishimura
Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not
More informationCIS192 Python Programming
CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline
More informationENGG1811 Computing for Engineers Week 9A: File handling
ENGG1811 Computing for Engineers Week 9A: File handling ENGG1811 UNSW, CRICOS Provider No: 00098G1 W9 slide 1 Motivations As an engineer, you may work with data Sometimes these data come in data files
More informationRandom Walks and Defining Functions FEB 9 AND 11, 2015
Random Walks and Defining Functions FEB 9 AND 11, 2015 If we take a random walk, will we go places? Problem: Simulate a random walk in which a person starts of at point 0 and at each step randomly picks
More informationCIS192 Python Programming
CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline
More informationLecture 3 The character, string data Types Files
Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',
More informationGetting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013
CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?
More informationCSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray
CSc 120 Introduction to Computer Programming II Adapted from slides by Dr. Saumya Debray 07: Excep*ons EXERCISE Type in the following code: def foo(): n = int(input("enter a number:")) print("n = ", n)
More informationThe Big Python Guide
The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String
More informationcs1114 REVIEW of details test closed laptop period
python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any
More informationOutline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.
OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce
More informationFinal exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)
Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had
More informationWhat is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]
What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)
More informationModularization. Functions and Modules. Functions. Functions how to define
Modularization Functions and Modules MBV-INFx410 Fall 2015 Programs can get big Risk of doing the same thing many times Functions and modules encourage - re-usability - readability - helps with maintenance
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationPart IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,
Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("
More information