Sie sind auf Seite 1von 45

Input/Output

CS 111: Computer Science for Scientists


Console
So far the only way weve gotten data from the user and
presented data to the user is through the console

In the real world, how many times have you used something
like a console to enter data?
Probably zero.
Pros and Cons
Consoles have a few problems
1. You cannot enter lots of data easily.
2. They are ugly.
3. You can only do string input.
4. You can only do one thing at a time.
5. If you make a mistake entering data you are screwed.
On the other hand,
1. Consoles are easy to program
2. If you are the only user of the program, theyre fine
3. If a program is very small, theyre fine.
Other types of input/output
There are four different types of Input/Output that well talk
about this semester.
Files
Internet
Drawing (Output only)
Graphical User Interface (GUI)
Files
There are many many different types of files for storing data.
In this class, we focus on comma separated values (CSV) files
CSV files are great for holding data associated with a 2-
dimensional array.
Each line of the file corresponds to row of the array.
In each line, each value is separated by a comma
hence the name
If you store strings, then each string is put in quotes
row/col 0 1 2
0 20 200 70

CSV Example 1
2
30
40
300
400
80
90
3 50 500 100
4 60 600 110

20,200,70
30,300,80
40,400,90
50,500,100
60,600,110
data.csv
row/col 0 1
0 hello C Patterson

CSV Example 1
2
guy, gal
fruit
tree
a b c d

"hello", "C Patterson"


"guy, gal","tree"
"fruit","a b c d"
data.csv
Internet
Well mostly read data from the internet in this class
Writing data is possible, but harder
The data well read will be in CSV format.
So, its similar to a normal file, but how we access it will be
different.
Drawing
Well cover a few different approaches to drawing this
semester.
The simplest one that well cover in this lecture is called turtle
Its really slow but it lets you easily plot points in an (x,y)-
coordinate space
GUI
Graphical User Interfaces
(GUIs) are the main way you
are use to interacting with
programs.
GUIs use buttons, windows,
textboxes, etc.
Well cover GUIs later in the
semester.
Input/Output and Programming
Languages
Programming languages are made for different purposes
As a result, different languages have different strengths
Python is great at files
However, Java and Swift are much better at GUI
Files
Open a file (for reading)
Before reading a file, we have to open it
variable = open("filename", "r")

The variable is file handle that will let us get a the contents
of the file
The "r" means open for reading
The filename needs to be the exact file name we are using
Close a file
Once you are done with a file, you should close it.
This is true if you read or write a file
This is done via the close command.

variable = open("filename", "r")


variable.close()
Read from a file (for loop)
There are a few different approaches for reading data from a
file.
The easiest is the for loop.
We can use this approach to get one line at a time
file = open("data.csv", "r")
for line in file:
print(line)
file.close()
readline()
We can use the readline() command to read just one line of a
file at a time.
Useful if you have a header line your file
You can read the header and then get to your data!
file = open("data.csv", "r")
firstLine = file.readline()
print("First line")
print(firstLine)
print("Rest")
for line in file:
print(line)
file.close()
Getting data from a line
Lines under both approaches are strings.
We need to get the data. How do we do that?
Easiest way is to use method split(chString).
This will split a string on the substring chString and
return a list of all the terms
Example Split

aLine = "20,30,40,50"
aList = aLine.split(",")
sum = 0
for element in aList:
intValue = int(element)
sum+=intValue
print(sum)

Note: aList is a list of strings which is why each


element has to be converted to integers.
Example Split

file = open("data.csv", "r")


total = 0
for line in file:
aLineAsList = line.split(",")
rowSum = 0
for element in aLineAsList:
rowSum+=int(element)
total+=int(element)
print("The row total is "+str(rowSum))
print("total is "+str(total))
file.close()
Writing to a file
To write to a file you first need to open it.
Same approach as before except use the w command

variable = open("filename", "w")


variable.close()
Writing
To write to a file we us the command creatively called write

fileGuy = open("store.csv", "w")


fileGuy.write("store this string")
fileGuy.write("Write only writes string")
fileGuy.write("Use \n to make a new line")
x = 33
fileGuy.write("If you want a number "+str(x))
fileGuy.write("Don't forget to close")
fileGuy.close()
Example 1
Make a program that reads data from one file, multiplies each
value by two and stores it back in the same file.
Example 2
Lets make a program that lets the user enter a bunch of
grades for students.
Each col is a new HW grade
Each row is a new student
We wont use names
Example 3
Lets now make a program that reads the data produced by
the last program and calculates the average grade for each
student
Example 4
Lets now add student names into the two previous programs
When reading the file, for each student print out the students
name and average.
Turtle
Turtles
The Turtle package in Python
allows us access to some simple
drawing.
Turtle has two ways to draw
You can direct the turtle forward,
backward, left, right and it will leave a
trail.
You can move it to a point and draw a
dot
https://goo.gl/b5Pk6c
Setup and Teardown
To use turtle you have to do a few #Import package
things before and after you draw. import turtle

Before #create turtle object


Import the turtle package myTurtle = turtle.Turtle()

Create the turtle object #keep window open


After turtle.exitonclick()

Make sure the window doesnt close right


away
Object
Well talk a lot about objects later
For right now, its important to know that a programming
object is similar to a real life objects
Real world objects have properties and can perform actions
Similarly computing objects have properties (internal variables) and
can perform actions (methods)
Objects must be created before they can be used.
Turtle Objects
Turtle objects can the following properties
(x,y) position
Direction (up, down, left, right)
Color
Pen up/Pen down
A few more that we dont really care about
Calling a method
To call a method on an object we use the dot (.) operator
So, if we made a turtle called steven and wanted to call the
setpos() method to set the position to be (40,50), then we
would call:
steven.setpos(40,50)
Turtle Methods (primary)
forward(x) or fd(x), move forward x units
backward(x) or bk(x), move back x units
right(x) or rt(x), turn x degrees right
left(x) or lt(x), turn x degrees left
setposition(x,y) or setpos(x,y), move to point (x,y)
penup() or pu(), move without drawing
pendown() or pd(), draw while moving
color("color name"), change color to color name
pensize(x), change the size of the pen to x.
dot(x), draw a dot of size x at the current spot
Brief Example
#Import package
import turtle

#create turtle object


myTurtle = turtle.Turtle()

myTurtle.penup()
myTurtle.setpos(20,30)
myTurtle.dot(10)
myTurtle.setpos(0,0)
myTurtle.pendown()
myTurtle.color("red")
myTurtle.right(90)
myTurtle.fd(50)
myTurtle.right(90)
myTurtle.fd(50)
myTurtle.right(90)
myTurtle.fd(50)
myTurtle.right(90)
myTurtle.fd(50)

#keep window open


turtle.exitonclick()
Now you try
Use a loop in the previous example so you dont have to write
the same lines of code over and over.
For no reason: a pretty flower
import turtle
myTurtle = turtle.Turtle()
#Sets line and fill color
myTurtle.color('red', 'yellow')
#all connected spaces created between
#the begin and end fill will
#be filled in yellow
myTurtle.begin_fill()
myTurtle.forward(200)
myTurtle.left(170)
while abs(myTurtle.pos())>=1:
myTurtle.forward(200)
myTurtle.left(170)
myTurtle.end_fill()

turtle.exitonclick()
speed
Turtle is very slow
import turtle
We can make it faster using the myTurtle = turtle.Turtle()
method speed() myTurtle.color('red', 'yellow')
myTurtle.speed(0)
Speed takes a number between myTurtle.begin_fill()
0-9 myTurtle.forward(200)
1 is the slowest 9 is very fast. 0 is myTurtle.left(170)
while abs(myTurtle.pos())>=1:
the fastest myTurtle.forward(200)
There is no good reason for this. myTurtle.left(170)
Someone just felt they were clever myTurtle.end_fill()
when they created turtle
turtle.exitonclick()
Just use 0.
World Coordinates
We can also change the world coordinates

myTurtle = turtle.Turtle()
minX = -50
minY = -50
maxX = 100
maxY = 100
screen = myTurtle.getscreen()
screen.reset()
screen.setworldcoordinates(minX, minY, maxX, maxY)
Examples
Write a method with one parameter: sideLength. The
function should draw a square with side length sideLength.
Modify your function so that it has two parameters:
sideLength and numSides. The function should draw a
regular polygon with numSides sides and side length
sideLength. Hint: The sum of the angles in a regular
polygon is 360 degrees.
Internet
Setup
The internet is just a big file system
The Uniform Resource Locator (URL) tells us which computer
contains the file we want, the directory of the file, and specific
file in that directory.
http://daringfireball.net/linked/2016/06/20/leventhal-apfs/index.html

Computer Directory File

There is a bit more to it than this, but thats fine for now
Opening URL
How we interpret a file depends on its type.
For example .jpg is an image .txt is a text file
For right now we are only going to work text files, which are
called ascii files.
After we decode it, then it becomes similar to a file.
Simple Request

import urllib.request

page = urllib.request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL")
pageBytes = page.read()
pageText = pageBytes.decode("ascii")
pageList = pageText.splitlines()
data = []
for line in pageList[1:]:
data += [line.split(",")]
print(data)
page.close()
import urllib.request
import turtle

page = urllib.request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=FB")
pageBytes = page.read()
pageText = pageBytes.decode("ascii")
pageList = pageText.splitlines()
data = []
for line in pageList[1:]:
data += [line.split(",")]

maxX = len(data)
maxY = 0
for line in data:
if maxY < int(float(line[4])):
maxY = int(float(line[4]))

myTurtle = turtle.Turtle()
myTurtle.speed(0)
screen = myTurtle.getscreen()
screen.reset()
screen.setworldcoordinates(0, 0, maxX, maxY)
myTurtle.pu()

x = maxX
for line in data:
myTurtle.setpos(x, int(float(line[4])))
print(line[0])
myTurtle.dot(3, "red")
x -= 1
page.close()
turtle.exitonclick()
Examples
Write a function called stockPlot2 with two parameters:
stock1 and stock2. These two parameters should be the
stock symbols for two companies. This function should plot
the closing stock prices for these two companies in different
colors.
Write a function called stockPlot3 with two parameters:
stock and dataType. The first parameter is the stock
symbol, and the second parameter indicated what kind of
data we want to plot (opening price, high, low, or closing
price). This function should plot the indicated data for the
company.
Examples
Write a function called stockPlotDate with three
parameters: symbol, startDate, and endDate. It should
plot the closing stock prices for the indicated company from
the startDate to the endDate. Hint: See if you can figure
out what this website displays:
http://ichart.finance.yahoo.com/table.csv?s=AAPL&a=9&b=2
3&c=2007&d=0&e=5&f=2015
Write a function called stockPlotAll with one parameter:
symbol. This function should plot the high, low, open, and
close data for the indicated company.

Das könnte Ihnen auch gefallen