SlideShare a Scribd company logo
1 of 48
Download to read offline
2. Modules, Scripts, and I/O
Topics:
Script Mode
Modules
The print andinput statements
Formatting
First look at importing stuff from
other modules
The Windchill Calculation
Let’s compute the windchill temperature given
that the air temperature is T = 32F and the wind
is W = 20mph.
Here is the formula courtesy of the National
Weather Service:
The formula only applies if T <= 50F and W>=3mph.
16.
)4275.075.35()6215.074.35( WTTWchill 
Use Python in Interactive Mode
>>> Temp = 32
>>> Wind = 20
>>> A = 35.74
>>> B = .6215
>>> C = -35.75
>>> D = .4275
>>> e = .16
>>> WC = (A+B*Temp)+(C+D*Temp)*Wind**e
>>> print WC
19.9855841878
The print statement is used for displaying values in variables.
Quick Note on print
The line
>>> print WC
results in the display of the value currently
housed in the variableWC
More on theprint statement later.
Motivating “Script Mode”
What is the new windchill if the wind is
increased from 20mph to 30mph?
Looks like we have to type in the same
sequence of statements. Tedious.
Wouldn’t it be nice if we could store the
sequence of statements in a file and then have
Python “run the file” after we changed
Wind = 20 to Wind = 30 ?
Script Mode
Instead of running Python in interactive mode,
we run Python in script mode.
The code to be run (called a script) is entered
into a file (called a module).
We then ask Python to “run the script”.
What is a Module?
A module is a .py file that contains Python code.
In CS 1110, these are created using Komodo Edit.
The ModuleWindChill.py
Temp = 32
Wind = 20
A = 35.74
B = .6215
C = -35.74
D = .4275
e = .16
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
Produced using Komodo Edit. This is our first draft.
WindChill.py
Running the Module
Here are the steps to follow in the
command shell:
1. Navigate the file system so that you are
“in” the same diretory that houses
WindChill.py
2. Type: python WindChill.py
Details
Suppose I have a directory on my desktop
calledTODAY where I keep all my python files
for today’s lecture.
I navigate the file system until I get this
prompt:
C:UserscvDesktopTODAY>
Asking Python to Run
the Code in WindChill.py
C:UserscvDesktopTODAY> Python WindChill.py
19.6975841877955
To save space in subsequent slides, we will refer to
C:UserscvDesktopTODAY> as BlahBlah>
Multiple Statements on a Line
Temp = 32
Wind = 20
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
Can put multiple statements on a line. Separate
the statements with semicolons.
WindChill.py
For lecture slides we will sometimes do this to save space.
But in general, it makes for ``dense reading’’ and should be avoided.
Module Readability: Comments
Comments begin with a “#”
Temp = 32
Wind = 20
# Model Parameters
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
# Compute and display the windchill
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
WindChill.py
Comments: Guidelines
Wind = 20 # wind speed in miles-per-hour
Comments can also appear on the same line
as a statement:
Everything to the right of the “#” is
part of the comment and not part of the
program.
Comments and Readability
Start each program (script) with a concise
description of what it does.
Define each important variable/constant.
A chunk of code with a specific taskshould
be generally be prefaced with a concise
comment.
Module Readability: docstrings
A special comment at the top of the module.
“““Computes windchill as a function of
wind(mph)and temp (Fahrenheit).”””
Temp = 32
Wind = 20
# Model Parameters
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
# Compute and display the windchill
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
WindChill.py
Docstrings: Guidelines
Docstrings are multiline comments that are
delimited by triple quotes: “““
They are strategically located at the beginning
of “important” code sections.
Their goal is to succinctly describe what the
code section is about.
One example of an “important” code section is a module.
Trying Different Inputs
“““Computes windchill as a function of
wind(mph)and temp (Fahrenheit).”””
Temp = 32
Wind = 20
# Model Parameters
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
# Compute and display the windchill
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
Can we be more
flexible here?
WindChill.py
Handy Input
If we want to explore windchill as a
function of windspeed and temperature,
then it is awkward to proceed by editing
the moduleWindChill.py every time
we want to check out a new wind/temp
combination.
The input statement addresses this issue.
The input Statement
The input statement is used to solicit
values via the keyboard:
input( < string that serves as a prompt > )
Later we will learn how to input data from a file.
Temp andWind via input
“““Computes windchill as a function of
wind(mph)and temp (Fahrenheit).”””
Temp = input(‘Enter temp (Fahrenheit):’)
Wind = input(‘Enter wind speed (mph):’)
# Model Parameters
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
# Compute and display the windchill
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print WC
WindChill.py
A Sample Run
> Enter temp (Fahrenheit) :
The prompt is displayed…
And you respond…
> Enter temp (Fahrenheit) : 15
A Sample Run
> Enter wind speed (mph) :
The next prompt is displayed…
And you respond again…
> Enter wind speed (mph) : 50
A Sample Overall “Dialog”
BlahBlah> python WindChill.py
Enter temp (Fahrenheit) : 15
Enter wind speed (mph) : 50
-9.79781580448
For more on Keyboard Input
Practice with the demo file
ShowInput.py
There is an alternative to input called
raw_input
It is handier in certain situations. Practice with
ShowRawInput.py
More Readable Output
The print statement can be used to format
output in a way that facilitates the
communication of results.
We don’t need to show wind chill to the
12th decimal!
More Readable Output
“““Computes windchill as a function of
wind(mph)and temp (Fahrenheit).”””
Temp = input(‘Enter temp (Fahrenheit):’)
Wind = input(‘Enter wind speed (mph):’)
# Model Parameters
A=35.74;B=.6215;C=-35.74;D=.4275;e=.16
# Compute and display the windchill
WC = (A+B*Temp)+(C+D*Temp)*Wind**e
print ' Windchill :%4.0f' % WC
WindChill.py
The “Dialog” With Formatting
BlahBlah> WindChill
Enter temp (Fahrenheit) : 15
Enter wind speed (mph) : 50
-9.79781580448
BlahBlah> WindChill
Enter temp (Fahrenheit) : 15
Enter wind speed (mph) : 50
Windchill : -10
print
without
formatting
print
with
formatting
The print Statement
The print statement tries to intelligently
format the results that it is asked to
display.
print with formatting puts you in control.
Later we will learn how to direct output to a file
print w/o Formatting
0.4
0.333333333333
1234.56789012
For float values, print (by itself) displays up to 12 significant digits
x = 2./5.
print x
x = 1./3.
print x
x = 1234.5678901234
print x
Script:
Output:
print w/o Formatting
1234 12345678
x = 1234
y = 12345678
print x,y
Script:
Output:
To display more then one value on a line, separate the references with com
A single blank is placed in between the displayed values.
print with the%f Format
x = 1234.123456789
print ‘x = %16.3f’ %x
print ‘x = %16.6f’ %x
print ‘x = %16.9f’ %x
x = 1234.123
x = 1234.123457
x = 1234.123456789
Formatted print statements are developed by “trial and error.”
It not a topic for memorization and it does not show up on exams.
print with the%e Format
x = 1234.123456789
print ‘x = %16.3e’ %x
print ‘x = %16.6e’ %x
print ‘x = %16.9e’ %x
x = 1.234e+03
x = 1.234123e+03
x = 1.234123456e+03
Formatted print statements are developed by “trial and error.”
It not a topic for memorization and it does not show up on exams.
print with the%d Format
x = 1234
print ‘x = %4d’ %x
print ‘x = %7d’ %x
print ‘x = %10d’ %x
x = 1234
x = 1234
x = 1234
Formatted print statements are developed by “trial and error.”
It not a topic for memorization and it does not show up on exams.
print with the %s Format
The Beatles in 1964
Band = ‘The Beatles’
print ‘%s in 1964’ % Band
Script:
Output:
Strings can be printed too
Formatted Print With More than
1 Source Value
The Beatles in 1964 and 1971
y1 = 1964
y2 = 1971
Band = ‘The Beatles’
print ‘%s in %4d and %4d’ % (Band,y1,y2)
Script:
Output:
Need parentheses
here.
print with Formatting
print <string with formats >%( <list-of-variables >)
A string that
includes
things like
%10.3f. %3d,
%8.2e, etc
Comma-separated,
e.g., x,y,z. One
variable for each
format marker
in the string. The
Parentheses are
Required if more
than one variable.
Practice with the demo fileShowFormat.py
Why Program Readability and
Style is Important
How we “do business” in commerical, scientific,
and engineering settings increasingly relies on
software.
Lack of attention to style and substandard
documentation promotes error and makes it
hard to build on one another’s software.
Another Detail
All modules that are submitted for grading
should begin with three comments.
# WindChill.py
# Xavier Zanzibar (xz3)
# January 1, 1903
etc
Name of module
Your name and netid
Date
WindChill.py
A Final Example
Write a script that solicits the area of
a circle and prints out the radius.
Preliminary Solution
A = input(‘Enter the circle area: ‘)
r = sqrt(A/3.14)
print r
The Math: solve A = pi*r*r for r.
Radius.py
We Get an Error
A = input(‘Enter the circle area: ‘)
r = sqrt(A/3.14)
print ‘The radius is %6.3f’ % r
sqrt is NOT a built-in function
r = sqrt(A/3.14)
NameError: name 'sqrt' is not defined
Final Solution
from math import sqrt
A = input(‘Enter the circle area: ‘)
r = sqrt(A/3.14)
print ‘The radius is %6.3f’ % r
The Math: solve A = pi*r*r for r.
We are importing the functionsqrt
from the math module.
Radius.py
The Idea Behindimport
People write useful code and place it in
modules that can be accessed by others.
The import statement makes this possible.
One thing in the math module is the square
root functionsqrt.
If you want to use it in your module just say
from math import sqrt
Better Final Solution
from math import sqrt,pi
A = input(‘Enter the circle area: ‘)
r = sqrt(A/pi)
print ‘The radius is %6.3f’ % r
Can import more than one thing from a module. Much more on import la
We are importing the functionsqrt and
the constantpi from the math module.
Radius.py
Sample Run
C:UserscvDesktopTODAY> Python Radius.py
Enter the circle area: 10
The radius is 1.785
For more insights, check out the lecture scriptSurfaceArea.py.
Modules and Scripts- Python Assignment Help

More Related Content

What's hot

Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFTvikram mahendra
 
PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONPART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONAndrea Antonello
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexityparamita30
 
PART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGPART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGAndrea Antonello
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...hwbloom38
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegressionDaniel K
 
Amortized Analysis of Algorithms
Amortized Analysis of Algorithms Amortized Analysis of Algorithms
Amortized Analysis of Algorithms sathish sak
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Philip Schwarz
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexityparamita30
 
logistic regression with python and R
logistic regression with python and Rlogistic regression with python and R
logistic regression with python and RAkhilesh Joshi
 
Assignment on Numerical Method C Code
Assignment on Numerical Method C CodeAssignment on Numerical Method C Code
Assignment on Numerical Method C CodeSyed Ahmed Zaki
 
support vector regression
support vector regressionsupport vector regression
support vector regressionAkhilesh Joshi
 
Chapter13 two-dimensional-array
Chapter13 two-dimensional-arrayChapter13 two-dimensional-array
Chapter13 two-dimensional-arrayDeepak Singh
 

What's hot (20)

130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
 
Vector3
Vector3Vector3
Vector3
 
PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHONPART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHON
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexity
 
PART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTINGPART 4: GEOGRAPHIC SCRIPTING
PART 4: GEOGRAPHIC SCRIPTING
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
Part II: 2-Dimensional Array file name: lab1part2.cpp (10 points) Write a C++...
 
knn classification
knn classificationknn classification
knn classification
 
C- Programming Assignment 3
C- Programming Assignment 3C- Programming Assignment 3
C- Programming Assignment 3
 
Programacion
ProgramacionProgramacion
Programacion
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
 
Amortized Analysis of Algorithms
Amortized Analysis of Algorithms Amortized Analysis of Algorithms
Amortized Analysis of Algorithms
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexity
 
logistic regression with python and R
logistic regression with python and Rlogistic regression with python and R
logistic regression with python and R
 
Assignment on Numerical Method C Code
Assignment on Numerical Method C CodeAssignment on Numerical Method C Code
Assignment on Numerical Method C Code
 
support vector regression
support vector regressionsupport vector regression
support vector regression
 
Chapter13 two-dimensional-array
Chapter13 two-dimensional-arrayChapter13 two-dimensional-array
Chapter13 two-dimensional-array
 
13 Amortized Analysis
13 Amortized Analysis13 Amortized Analysis
13 Amortized Analysis
 

Viewers also liked

Post wealth transfer- managing business stock in trusts and partnerships
Post wealth transfer- managing business stock in trusts and partnershipsPost wealth transfer- managing business stock in trusts and partnerships
Post wealth transfer- managing business stock in trusts and partnershipsPrivatus CI3O Services, LLC
 
SunSight - Field Management App for Solar Providers
SunSight - Field Management App for Solar ProvidersSunSight - Field Management App for Solar Providers
SunSight - Field Management App for Solar ProvidersrapidBizApps
 
Analisis cientifico del movimiento2
Analisis cientifico del movimiento2Analisis cientifico del movimiento2
Analisis cientifico del movimiento2Alejandra Salazar
 
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoft
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoftBusiness Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoft
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoftEric Schames
 
Postgresql + Python = Power!
Postgresql + Python = Power!Postgresql + Python = Power!
Postgresql + Python = Power!Juliano Atanazio
 
Container Testing: A Contract Laboratory's Perspective on Industry Confusion
Container Testing: A Contract Laboratory's Perspective on Industry ConfusionContainer Testing: A Contract Laboratory's Perspective on Industry Confusion
Container Testing: A Contract Laboratory's Perspective on Industry ConfusionBrandon Zurawlow
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
OSINT tools for security auditing [FOSDEM edition]
OSINT tools for security auditing [FOSDEM edition] OSINT tools for security auditing [FOSDEM edition]
OSINT tools for security auditing [FOSDEM edition] Jose Manuel Ortega Candel
 
Programando em python modulos
Programando em python   modulosProgramando em python   modulos
Programando em python modulossamuelthiago
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonCP-Union
 
Recruitment training.nl Opleidingsprogramma Startende Recruiter
Recruitment training.nl Opleidingsprogramma Startende RecruiterRecruitment training.nl Opleidingsprogramma Startende Recruiter
Recruitment training.nl Opleidingsprogramma Startende RecruiterAlexander Crépin
 
Métodos de búsqueda avanzada
Métodos de búsqueda avanzadaMétodos de búsqueda avanzada
Métodos de búsqueda avanzadaSusana García
 
Demystifying how imports work in Python
Demystifying how imports work in PythonDemystifying how imports work in Python
Demystifying how imports work in Pythonprodicus
 

Viewers also liked (20)

Designing Modules in Python
Designing Modules in PythonDesigning Modules in Python
Designing Modules in Python
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Post wealth transfer- managing business stock in trusts and partnerships
Post wealth transfer- managing business stock in trusts and partnershipsPost wealth transfer- managing business stock in trusts and partnerships
Post wealth transfer- managing business stock in trusts and partnerships
 
SunSight - Field Management App for Solar Providers
SunSight - Field Management App for Solar ProvidersSunSight - Field Management App for Solar Providers
SunSight - Field Management App for Solar Providers
 
Analisis cientifico del movimiento2
Analisis cientifico del movimiento2Analisis cientifico del movimiento2
Analisis cientifico del movimiento2
 
Búsqueda de empleo, Linkedin y redes sociales
Búsqueda de empleo, Linkedin  y redes socialesBúsqueda de empleo, Linkedin  y redes sociales
Búsqueda de empleo, Linkedin y redes sociales
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 
Genetica y cruzamiento2
Genetica y cruzamiento2Genetica y cruzamiento2
Genetica y cruzamiento2
 
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoft
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoftBusiness Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoft
Business Etiquette for Entrepreneurs 2016 - Eric Schames @ StartupLoft
 
Postgresql + Python = Power!
Postgresql + Python = Power!Postgresql + Python = Power!
Postgresql + Python = Power!
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Container Testing: A Contract Laboratory's Perspective on Industry Confusion
Container Testing: A Contract Laboratory's Perspective on Industry ConfusionContainer Testing: A Contract Laboratory's Perspective on Industry Confusion
Container Testing: A Contract Laboratory's Perspective on Industry Confusion
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
OSINT tools for security auditing [FOSDEM edition]
OSINT tools for security auditing [FOSDEM edition] OSINT tools for security auditing [FOSDEM edition]
OSINT tools for security auditing [FOSDEM edition]
 
Programando em python modulos
Programando em python   modulosProgramando em python   modulos
Programando em python modulos
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
Tema1 CONCEPTO DE VENTA
Tema1 CONCEPTO DE VENTATema1 CONCEPTO DE VENTA
Tema1 CONCEPTO DE VENTA
 
Recruitment training.nl Opleidingsprogramma Startende Recruiter
Recruitment training.nl Opleidingsprogramma Startende RecruiterRecruitment training.nl Opleidingsprogramma Startende Recruiter
Recruitment training.nl Opleidingsprogramma Startende Recruiter
 
Métodos de búsqueda avanzada
Métodos de búsqueda avanzadaMétodos de búsqueda avanzada
Métodos de búsqueda avanzada
 
Demystifying how imports work in Python
Demystifying how imports work in PythonDemystifying how imports work in Python
Demystifying how imports work in Python
 

Similar to Modules and Scripts- Python Assignment Help

Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answersdebarghyamukherjee60
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docxrosemarybdodson23141
 
Programming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESProgramming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESNaveed Rehman
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docx
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docxProblem 7PurposeBreak apart a complicated system.ConstantsC7C13.docx
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docxLacieKlineeb
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdfVcTrn1
 
ENG3104 Engineering Simulations and Computations Semester 2, 2.docx
ENG3104 Engineering Simulations and Computations Semester 2, 2.docxENG3104 Engineering Simulations and Computations Semester 2, 2.docx
ENG3104 Engineering Simulations and Computations Semester 2, 2.docxYASHU40
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabMohan Raj
 

Similar to Modules and Scripts- Python Assignment Help (20)

ICP - Lecture 6
ICP - Lecture 6ICP - Lecture 6
ICP - Lecture 6
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Python Manuel-R2021.pdf
Python Manuel-R2021.pdfPython Manuel-R2021.pdf
Python Manuel-R2021.pdf
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
Programming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESProgramming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EES
 
Es272 ch1
Es272 ch1Es272 ch1
Es272 ch1
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
C++
C++C++
C++
 
2621008 - C++ 1
2621008 -  C++ 12621008 -  C++ 1
2621008 - C++ 1
 
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docx
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docxProblem 7PurposeBreak apart a complicated system.ConstantsC7C13.docx
Problem 7PurposeBreak apart a complicated system.ConstantsC7C13.docx
 
Apclass (2)
Apclass (2)Apclass (2)
Apclass (2)
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdf
 
ENG3104 Engineering Simulations and Computations Semester 2, 2.docx
ENG3104 Engineering Simulations and Computations Semester 2, 2.docxENG3104 Engineering Simulations and Computations Semester 2, 2.docx
ENG3104 Engineering Simulations and Computations Semester 2, 2.docx
 
Linux_C_LabBasics.ppt
Linux_C_LabBasics.pptLinux_C_LabBasics.ppt
Linux_C_LabBasics.ppt
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Apclass
ApclassApclass
Apclass
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Modules and Scripts- Python Assignment Help

  • 1.
  • 2. 2. Modules, Scripts, and I/O Topics: Script Mode Modules The print andinput statements Formatting First look at importing stuff from other modules
  • 3. The Windchill Calculation Let’s compute the windchill temperature given that the air temperature is T = 32F and the wind is W = 20mph. Here is the formula courtesy of the National Weather Service: The formula only applies if T <= 50F and W>=3mph. 16. )4275.075.35()6215.074.35( WTTWchill 
  • 4. Use Python in Interactive Mode >>> Temp = 32 >>> Wind = 20 >>> A = 35.74 >>> B = .6215 >>> C = -35.75 >>> D = .4275 >>> e = .16 >>> WC = (A+B*Temp)+(C+D*Temp)*Wind**e >>> print WC 19.9855841878 The print statement is used for displaying values in variables.
  • 5. Quick Note on print The line >>> print WC results in the display of the value currently housed in the variableWC More on theprint statement later.
  • 6. Motivating “Script Mode” What is the new windchill if the wind is increased from 20mph to 30mph? Looks like we have to type in the same sequence of statements. Tedious. Wouldn’t it be nice if we could store the sequence of statements in a file and then have Python “run the file” after we changed Wind = 20 to Wind = 30 ?
  • 7. Script Mode Instead of running Python in interactive mode, we run Python in script mode. The code to be run (called a script) is entered into a file (called a module). We then ask Python to “run the script”.
  • 8. What is a Module? A module is a .py file that contains Python code. In CS 1110, these are created using Komodo Edit.
  • 9. The ModuleWindChill.py Temp = 32 Wind = 20 A = 35.74 B = .6215 C = -35.74 D = .4275 e = .16 WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC Produced using Komodo Edit. This is our first draft. WindChill.py
  • 10. Running the Module Here are the steps to follow in the command shell: 1. Navigate the file system so that you are “in” the same diretory that houses WindChill.py 2. Type: python WindChill.py
  • 11. Details Suppose I have a directory on my desktop calledTODAY where I keep all my python files for today’s lecture. I navigate the file system until I get this prompt: C:UserscvDesktopTODAY>
  • 12. Asking Python to Run the Code in WindChill.py C:UserscvDesktopTODAY> Python WindChill.py 19.6975841877955 To save space in subsequent slides, we will refer to C:UserscvDesktopTODAY> as BlahBlah>
  • 13. Multiple Statements on a Line Temp = 32 Wind = 20 A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC Can put multiple statements on a line. Separate the statements with semicolons. WindChill.py For lecture slides we will sometimes do this to save space. But in general, it makes for ``dense reading’’ and should be avoided.
  • 14. Module Readability: Comments Comments begin with a “#” Temp = 32 Wind = 20 # Model Parameters A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 # Compute and display the windchill WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC WindChill.py
  • 15. Comments: Guidelines Wind = 20 # wind speed in miles-per-hour Comments can also appear on the same line as a statement: Everything to the right of the “#” is part of the comment and not part of the program.
  • 16. Comments and Readability Start each program (script) with a concise description of what it does. Define each important variable/constant. A chunk of code with a specific taskshould be generally be prefaced with a concise comment.
  • 17. Module Readability: docstrings A special comment at the top of the module. “““Computes windchill as a function of wind(mph)and temp (Fahrenheit).””” Temp = 32 Wind = 20 # Model Parameters A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 # Compute and display the windchill WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC WindChill.py
  • 18. Docstrings: Guidelines Docstrings are multiline comments that are delimited by triple quotes: “““ They are strategically located at the beginning of “important” code sections. Their goal is to succinctly describe what the code section is about. One example of an “important” code section is a module.
  • 19. Trying Different Inputs “““Computes windchill as a function of wind(mph)and temp (Fahrenheit).””” Temp = 32 Wind = 20 # Model Parameters A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 # Compute and display the windchill WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC Can we be more flexible here? WindChill.py
  • 20. Handy Input If we want to explore windchill as a function of windspeed and temperature, then it is awkward to proceed by editing the moduleWindChill.py every time we want to check out a new wind/temp combination. The input statement addresses this issue.
  • 21. The input Statement The input statement is used to solicit values via the keyboard: input( < string that serves as a prompt > ) Later we will learn how to input data from a file.
  • 22. Temp andWind via input “““Computes windchill as a function of wind(mph)and temp (Fahrenheit).””” Temp = input(‘Enter temp (Fahrenheit):’) Wind = input(‘Enter wind speed (mph):’) # Model Parameters A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 # Compute and display the windchill WC = (A+B*Temp)+(C+D*Temp)*Wind**e print WC WindChill.py
  • 23. A Sample Run > Enter temp (Fahrenheit) : The prompt is displayed… And you respond… > Enter temp (Fahrenheit) : 15
  • 24. A Sample Run > Enter wind speed (mph) : The next prompt is displayed… And you respond again… > Enter wind speed (mph) : 50
  • 25. A Sample Overall “Dialog” BlahBlah> python WindChill.py Enter temp (Fahrenheit) : 15 Enter wind speed (mph) : 50 -9.79781580448
  • 26. For more on Keyboard Input Practice with the demo file ShowInput.py There is an alternative to input called raw_input It is handier in certain situations. Practice with ShowRawInput.py
  • 27. More Readable Output The print statement can be used to format output in a way that facilitates the communication of results. We don’t need to show wind chill to the 12th decimal!
  • 28. More Readable Output “““Computes windchill as a function of wind(mph)and temp (Fahrenheit).””” Temp = input(‘Enter temp (Fahrenheit):’) Wind = input(‘Enter wind speed (mph):’) # Model Parameters A=35.74;B=.6215;C=-35.74;D=.4275;e=.16 # Compute and display the windchill WC = (A+B*Temp)+(C+D*Temp)*Wind**e print ' Windchill :%4.0f' % WC WindChill.py
  • 29. The “Dialog” With Formatting BlahBlah> WindChill Enter temp (Fahrenheit) : 15 Enter wind speed (mph) : 50 -9.79781580448 BlahBlah> WindChill Enter temp (Fahrenheit) : 15 Enter wind speed (mph) : 50 Windchill : -10 print without formatting print with formatting
  • 30. The print Statement The print statement tries to intelligently format the results that it is asked to display. print with formatting puts you in control. Later we will learn how to direct output to a file
  • 31. print w/o Formatting 0.4 0.333333333333 1234.56789012 For float values, print (by itself) displays up to 12 significant digits x = 2./5. print x x = 1./3. print x x = 1234.5678901234 print x Script: Output:
  • 32. print w/o Formatting 1234 12345678 x = 1234 y = 12345678 print x,y Script: Output: To display more then one value on a line, separate the references with com A single blank is placed in between the displayed values.
  • 33. print with the%f Format x = 1234.123456789 print ‘x = %16.3f’ %x print ‘x = %16.6f’ %x print ‘x = %16.9f’ %x x = 1234.123 x = 1234.123457 x = 1234.123456789 Formatted print statements are developed by “trial and error.” It not a topic for memorization and it does not show up on exams.
  • 34. print with the%e Format x = 1234.123456789 print ‘x = %16.3e’ %x print ‘x = %16.6e’ %x print ‘x = %16.9e’ %x x = 1.234e+03 x = 1.234123e+03 x = 1.234123456e+03 Formatted print statements are developed by “trial and error.” It not a topic for memorization and it does not show up on exams.
  • 35. print with the%d Format x = 1234 print ‘x = %4d’ %x print ‘x = %7d’ %x print ‘x = %10d’ %x x = 1234 x = 1234 x = 1234 Formatted print statements are developed by “trial and error.” It not a topic for memorization and it does not show up on exams.
  • 36. print with the %s Format The Beatles in 1964 Band = ‘The Beatles’ print ‘%s in 1964’ % Band Script: Output: Strings can be printed too
  • 37. Formatted Print With More than 1 Source Value The Beatles in 1964 and 1971 y1 = 1964 y2 = 1971 Band = ‘The Beatles’ print ‘%s in %4d and %4d’ % (Band,y1,y2) Script: Output: Need parentheses here.
  • 38. print with Formatting print <string with formats >%( <list-of-variables >) A string that includes things like %10.3f. %3d, %8.2e, etc Comma-separated, e.g., x,y,z. One variable for each format marker in the string. The Parentheses are Required if more than one variable. Practice with the demo fileShowFormat.py
  • 39. Why Program Readability and Style is Important How we “do business” in commerical, scientific, and engineering settings increasingly relies on software. Lack of attention to style and substandard documentation promotes error and makes it hard to build on one another’s software.
  • 40. Another Detail All modules that are submitted for grading should begin with three comments. # WindChill.py # Xavier Zanzibar (xz3) # January 1, 1903 etc Name of module Your name and netid Date WindChill.py
  • 41. A Final Example Write a script that solicits the area of a circle and prints out the radius.
  • 42. Preliminary Solution A = input(‘Enter the circle area: ‘) r = sqrt(A/3.14) print r The Math: solve A = pi*r*r for r. Radius.py
  • 43. We Get an Error A = input(‘Enter the circle area: ‘) r = sqrt(A/3.14) print ‘The radius is %6.3f’ % r sqrt is NOT a built-in function r = sqrt(A/3.14) NameError: name 'sqrt' is not defined
  • 44. Final Solution from math import sqrt A = input(‘Enter the circle area: ‘) r = sqrt(A/3.14) print ‘The radius is %6.3f’ % r The Math: solve A = pi*r*r for r. We are importing the functionsqrt from the math module. Radius.py
  • 45. The Idea Behindimport People write useful code and place it in modules that can be accessed by others. The import statement makes this possible. One thing in the math module is the square root functionsqrt. If you want to use it in your module just say from math import sqrt
  • 46. Better Final Solution from math import sqrt,pi A = input(‘Enter the circle area: ‘) r = sqrt(A/pi) print ‘The radius is %6.3f’ % r Can import more than one thing from a module. Much more on import la We are importing the functionsqrt and the constantpi from the math module. Radius.py
  • 47. Sample Run C:UserscvDesktopTODAY> Python Radius.py Enter the circle area: 10 The radius is 1.785 For more insights, check out the lecture scriptSurfaceArea.py.