SlideShare uma empresa Scribd logo
1 de 39
Learn Python the Hard Way
Exercises 13 – 19

http://learnpythonthehardway.org/
from sys import argv
• You’ll see this kind of thing a lot in Python
scripts:
from ----- import ----• The first thing (sys) is a module that already
exists in Python. It contains many things.
• The second thing (argv) is a variable that is
defined in sys. By importing it, you can do
stuff that would not work otherwise.
Python is flexible …
• Once you have argv in your program (because
you started with from sys import argv), you
can use it like this:

script, x, y, z = argv
• It’s entirely up to you how many things you
put in that line before = argv
… but Python is fussy too
• If your program has four things in the line
before = argv
script, x, y, z = argv
• … then you absolutely must invoke your
program with three arguments, like this:
~$ python ex13.py Tom Dick Harry
from sys import argv
• Zed’s “Study Drills” are really key for learning
how this works
• Think of why a program might need this
instead of raw_input()
• Note: The “arguments” for argv are loaded
into your program before the program is
running
“Adventure”: An early computer game
> type something here
With Zed’s Exercise 14, again, his “Study Drills”
are really important.
If you’re skipping them, you’re probably not
getting it.
You’re going to start feeling very lost …
Exercise 15

Opening files
f = open("myfileonmycomputer.txt")
f is a variable name (it could be x, or file, or txt)
myfileonmycomputer.txt
is the name of a normal file on your computer

open() is a built-in function in Python.
Note: This only stores the file as a value (it does NOT
show you the contents of the file).
Exercise 15

Opening files (2)
f = open(filename)
In Ex. 15, Zed has that (above).
Where does filename come from?
Go back to the second line of his code:
script, filename = argv
filename came from the argument you typed
when you invoked your program:
~$ python ex15.py ex15_sample.txt
Exercise 15

Reading files
print f.read()
What does this do?
Make sure you understand this.
read() is a method in Python. It reads what
you tell it to read, and then returns a string that
contains what it read.
You can play with this stuff
on the command line
Why this is cool
You can send Python out to the Web and ask it
to read files out there.
Then you can search the contents of those files
and do stuff with the contents.
Python is powerful.
Code is powerful!
Exercise 16

Messing with the contents of files
f = open(filename, 'w')
What does the ‘w’ do? Did you look it up?
f.truncate()
What does this do? (Make sure you know!)

f.write(something)
What does this do?
Truncate a file
Play on the command line!
Write to a file
Play on the command line!
Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
What will Python allow?
What happens if you enter:
f.write(a, b, c)
Note: You should try this kind of thing.
Write a comment in your code about what you
find out after you try it.
Modes for open()
f = open(filename, 'w')
Modes 'r+', 'w+' and 'a+' open the file for
updating (note that 'w+' truncates the file).
'r+' read
'w+' write and erase all contents
'a+' append

If the mode is omitted, it defaults to 'r'.
http://docs.python.org/2/library/functions.html#open
Exercise 17

Checking if a file exists
from sys import argv
from os.path import exists
Review Exercise 13
• The first thing (os.path) is a module that is part of
Python. It contains many things.
• The second thing (exists) is a function that is
defined in os.path. You must import it if you
intend to use it.
Exercise 17

Using exists
print "Does the output file exist?
%r" % exists(to_file)
If that confuses you, try just this:
print exists(to_file)
Then run the program again, and give it a
filename that does not exist on your computer.
You can even play with this
on the command line
Exercise 17

Copying file contents
• I think Zed’s filenames are confusing in Ex. 17.
• If you change the variable names for the two
files to: oldfile and newfile, or to original and
destination, maybe it will help you.
script, oldfile, newfile = argv
Exercise 17

Copying, Step 1
f = open(oldfile)
indata = f.read()
is the same as
indata = open(oldfile).read()
(Python allows us to chain instructions together
in one line)
Exercise 17

Copying, Step 2
t = open(newfile, 'w')
t.write(indata)
Confusing, yes?
The real file represented by newfile will now be
represented by the variable name t.
The value of indata is put into t.
Whatever was in oldfile is now in newfile.
This code accomplishes the same thing as Zed’s Ex. 17.
Exercise 17

len()

This is a good one to play with
on the command line
Compare the real file size
with the result from len()
Yes, Exercise 17 is hard.
Even Zed says so! *

* In his “Common Student Questions” section
Exercise 18

Functions!
• Functions are as essential to programming as
variables
• Most programming languages use functions
• Basically, a function has a name and a list of
instructions
• When you call the function, those instructions
will run (they will be executed)
Exercise 18

More about functions!
• Important: A function does not do anything,
ever, until it is called
• If you define a function, but you never call it,
it will never run
• Most programs contain several (or many)
different functions
Exercise 18

Accurate typing
• Here’s where your journalism editing skill
gives you an edge!
• Follow the style carefully …
def functionname(argument,
argument):
(don’t forget the colon!)

• Indents: In Python, the indents are superimportant! The convention is to use 4 spaces
—and NOT a tab.
Exercise 19

Variables inside and outside
• Python doesn’t throw an error if you use the
exact same variable name inside a function
AND outside a function
• This can be misleading
• Those would actually be two different
variables
• If you change the value of a variable inside a
function, the value of the other variable
(outside) will not change!
Exercise 19

Variables inside and outside
Therefore, it is very smart to be careful about
the names you give to your variables.
Don’t mix and match.
Use different variable names inside the
functions.
Start with the code you see below.
Then, below it, write a function that takes mpg,
price_of_gas, and distance as arguments.
The function will calculate the cost of gas for the trip.
You’ll learn much more
about functions
in the upcoming exercises!
Learn Python the Hard Way
Exercises 13 – 19
(now we know something)

Mais conteúdo relacionado

Mais procurados (20)

Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python basics
Python basicsPython basics
Python basics
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Python ppt
Python pptPython ppt
Python ppt
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python Session - 5
Python Session - 5Python Session - 5
Python Session - 5
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
The Benefits of Type Hints
The Benefits of Type HintsThe Benefits of Type Hints
The Benefits of Type Hints
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python basics
Python basicsPython basics
Python basics
 

Semelhante a Learn Python Functions and File Handling with Exercises 13-19

First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security ProfessionalsAditya Shankar
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - englishJen Yee Hong
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfExaminationSectionMR
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IDUSPviz
 

Semelhante a Learn Python Functions and File Handling with Exercises 13-19 (20)

First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Python training
Python trainingPython training
Python training
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part I
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 

Mais de Mindy McAdams

Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMindy McAdams
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopMindy McAdams
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills Mindy McAdams
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalismMindy McAdams
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction Mindy McAdams
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Mindy McAdams
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersMindy McAdams
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 CanvasMindy McAdams
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design Mindy McAdams
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web DesignMindy McAdams
 
Learning Python - Week 4
Learning Python - Week 4 Learning Python - Week 4
Learning Python - Week 4 Mindy McAdams
 
Learning Python - Week 1
Learning Python - Week 1Learning Python - Week 1
Learning Python - Week 1Mindy McAdams
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisMindy McAdams
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / BenklerMindy McAdams
 

Mais de Mindy McAdams (20)

Just Enough Code
Just Enough CodeJust Enough Code
Just Enough Code
 
Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the Classroom
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshop
 
Crowdsourcing
CrowdsourcingCrowdsourcing
Crowdsourcing
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalism
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not Newspapers
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
Beginning jQuery
Beginning jQueryBeginning jQuery
Beginning jQuery
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web Design
 
Learning Python - Week 4
Learning Python - Week 4 Learning Python - Week 4
Learning Python - Week 4
 
Learning Python - Week 1
Learning Python - Week 1Learning Python - Week 1
Learning Python - Week 1
 
Learning Python
Learning PythonLearning Python
Learning Python
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis Brandeis
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / Benkler
 

Último

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Último (20)

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 

Learn Python Functions and File Handling with Exercises 13-19

  • 1. Learn Python the Hard Way Exercises 13 – 19 http://learnpythonthehardway.org/
  • 2. from sys import argv • You’ll see this kind of thing a lot in Python scripts: from ----- import ----• The first thing (sys) is a module that already exists in Python. It contains many things. • The second thing (argv) is a variable that is defined in sys. By importing it, you can do stuff that would not work otherwise.
  • 3. Python is flexible … • Once you have argv in your program (because you started with from sys import argv), you can use it like this: script, x, y, z = argv • It’s entirely up to you how many things you put in that line before = argv
  • 4. … but Python is fussy too • If your program has four things in the line before = argv script, x, y, z = argv • … then you absolutely must invoke your program with three arguments, like this: ~$ python ex13.py Tom Dick Harry
  • 5.
  • 6. from sys import argv • Zed’s “Study Drills” are really key for learning how this works • Think of why a program might need this instead of raw_input() • Note: The “arguments” for argv are loaded into your program before the program is running
  • 8. > type something here With Zed’s Exercise 14, again, his “Study Drills” are really important. If you’re skipping them, you’re probably not getting it. You’re going to start feeling very lost …
  • 9. Exercise 15 Opening files f = open("myfileonmycomputer.txt") f is a variable name (it could be x, or file, or txt) myfileonmycomputer.txt is the name of a normal file on your computer open() is a built-in function in Python. Note: This only stores the file as a value (it does NOT show you the contents of the file).
  • 10. Exercise 15 Opening files (2) f = open(filename) In Ex. 15, Zed has that (above). Where does filename come from? Go back to the second line of his code: script, filename = argv filename came from the argument you typed when you invoked your program: ~$ python ex15.py ex15_sample.txt
  • 11. Exercise 15 Reading files print f.read() What does this do? Make sure you understand this. read() is a method in Python. It reads what you tell it to read, and then returns a string that contains what it read.
  • 12. You can play with this stuff on the command line
  • 13. Why this is cool You can send Python out to the Web and ask it to read files out there. Then you can search the contents of those files and do stuff with the contents. Python is powerful. Code is powerful!
  • 14. Exercise 16 Messing with the contents of files f = open(filename, 'w') What does the ‘w’ do? Did you look it up? f.truncate() What does this do? (Make sure you know!) f.write(something) What does this do?
  • 15. Truncate a file Play on the command line!
  • 16. Write to a file Play on the command line!
  • 17. Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
  • 18. What will Python allow? What happens if you enter: f.write(a, b, c) Note: You should try this kind of thing. Write a comment in your code about what you find out after you try it.
  • 19. Modes for open() f = open(filename, 'w') Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). 'r+' read 'w+' write and erase all contents 'a+' append If the mode is omitted, it defaults to 'r'. http://docs.python.org/2/library/functions.html#open
  • 20. Exercise 17 Checking if a file exists from sys import argv from os.path import exists Review Exercise 13 • The first thing (os.path) is a module that is part of Python. It contains many things. • The second thing (exists) is a function that is defined in os.path. You must import it if you intend to use it.
  • 21. Exercise 17 Using exists print "Does the output file exist? %r" % exists(to_file) If that confuses you, try just this: print exists(to_file) Then run the program again, and give it a filename that does not exist on your computer.
  • 22. You can even play with this on the command line
  • 23. Exercise 17 Copying file contents • I think Zed’s filenames are confusing in Ex. 17. • If you change the variable names for the two files to: oldfile and newfile, or to original and destination, maybe it will help you. script, oldfile, newfile = argv
  • 24. Exercise 17 Copying, Step 1 f = open(oldfile) indata = f.read() is the same as indata = open(oldfile).read() (Python allows us to chain instructions together in one line)
  • 25. Exercise 17 Copying, Step 2 t = open(newfile, 'w') t.write(indata) Confusing, yes? The real file represented by newfile will now be represented by the variable name t. The value of indata is put into t. Whatever was in oldfile is now in newfile.
  • 26. This code accomplishes the same thing as Zed’s Ex. 17.
  • 27. Exercise 17 len() This is a good one to play with on the command line
  • 28. Compare the real file size with the result from len()
  • 29. Yes, Exercise 17 is hard. Even Zed says so! * * In his “Common Student Questions” section
  • 30. Exercise 18 Functions! • Functions are as essential to programming as variables • Most programming languages use functions • Basically, a function has a name and a list of instructions • When you call the function, those instructions will run (they will be executed)
  • 31.
  • 32. Exercise 18 More about functions! • Important: A function does not do anything, ever, until it is called • If you define a function, but you never call it, it will never run • Most programs contain several (or many) different functions
  • 33. Exercise 18 Accurate typing • Here’s where your journalism editing skill gives you an edge! • Follow the style carefully … def functionname(argument, argument): (don’t forget the colon!) • Indents: In Python, the indents are superimportant! The convention is to use 4 spaces —and NOT a tab.
  • 34. Exercise 19 Variables inside and outside • Python doesn’t throw an error if you use the exact same variable name inside a function AND outside a function • This can be misleading • Those would actually be two different variables • If you change the value of a variable inside a function, the value of the other variable (outside) will not change!
  • 35.
  • 36. Exercise 19 Variables inside and outside Therefore, it is very smart to be careful about the names you give to your variables. Don’t mix and match. Use different variable names inside the functions.
  • 37. Start with the code you see below. Then, below it, write a function that takes mpg, price_of_gas, and distance as arguments. The function will calculate the cost of gas for the trip.
  • 38. You’ll learn much more about functions in the upcoming exercises!
  • 39. Learn Python the Hard Way Exercises 13 – 19 (now we know something)

Notas do Editor

  1. SOURCE http://learnpythonthehardway.org/book/
  2. All of this is just part of Python. Go with it. Relax.
  3. You can pass in any number of arguments. For example: script, a, b, c, d, e, f, g = argv
  4. BUT the number of arguments indicated in the program MUST BE matched by what you type when you invoke (run) the program.
  5. CODE EXAMPLE. LPTHW Exercise 13 – this is a variation on Zed’s exercise.
  6. Play with this code until you really understand it.
  7. See http://en.wikipedia.org/wiki/Adventure_game | Download Mac OS version (seen here) - http://lobotomo.com/products/Adventure/index.html
  8. LPTHW Exercise 15 – the first time we work with external files.
  9. LPTHW Exercise 15 requires you to understand Exercises 13 and 14. If you’re still unclear about argv – you’ll have to go back. SLIDE 2 in this PPT explains.
  10. f = open(something) does ONE thing. print f.read() does something else. For a list of all built-in functions, see http://docs.python.org/2/library/functions.html
  11. CODE EXAMPLE. Exercise 15.
  12. LPTHW Exercise 16 – open, truncate, write.
  13. CODE EXAMPLE. Exercise 16. Truncate.
  14. CODE EXAMPLE. Exercise 16. Write.
  15. Top: The original file, test.txt. Bottom: The same file, after truncating and writing.
  16. You’ll get an error … Figure out why!
  17. SOURCE http://docs.python.org/2/library/functions.html#open
  18. LPTHW Exercise 17 – first, the import statements …
  19. LPTHW Exercise 17 – how “exists” works
  20. CODE EXAMPLE - LPTHW Exercise 17
  21. LPTHW Exercise 17 – second, understanding the variable names …
  22. LPTHW Exercise 17 – third, copy the contents of oldfile into a new variable named indata …
  23. LPTHW Exercise 17 – fourth, copy the value of the variable named indata … into newfile.
  24. LPTHW Exercise 17 – a variation with the same result: contents of one file are totally copied into a different file.
  25. CODE EXAMPLE - LPTHW Exercise 17 – len() – How big is it? (or, how long? Measured in characters, or bytes)
  26. CODE EXAMPLE - LPTHW Exercise 17 – len() // Open the little Info window in Mac OS with Command-I (I for Info).
  27. LPTHW Exercise 17
  28. CODE EXAMPLE. LPTHW Exercise 18 – try to figure this out.
  29. CODE EXAMPLE. LPTHW Exercise 19 – try to figure this out.
  30. LPTHW Exercise 19 – a problem for you to solve
  31. Mindy McAdams - CONTACT – http://mindymcadams.com/