CSC 1010 Programming for All Lecture 7 Input, Output & Graphics
Jan 17, 2016
CSC 1010Programming for All
Lecture 7Input, Output & Graphics
INPUT
2
Reading using input function• Prompt:
– Asks the user for input– Example: input(“Enter your first name”)– Need to store the string results
• Input• firstName = input(“Enter your first name”)
– Here – message is displayed– Computer waits until user types in and hits Enter– Characters are stored in variable to left of =– print(firstName) #prints what user entered – Input is always of type string
Number needed• Converting a string variable to a number can be
used if numeric (rather than string input) is needed
age = int(input("Please enter age: "))
• The above is equivalent to doing it two steps (getting the input and then converting it to a number):
aString = input("Please enter age: ") # String input age = int(aString) #age is now an integer
decimalAge = float(aString) # a float
Example: y = ax2 + bx + c • Try to use the coefficients of a quadratic equation
s = input(“enter single digit quadratic coefficients: “ +
“a b c with one space in betweensa = s[0] # string inputbs = s[2]cs = s[4]
a=int(as) # converts string to numberb=int(bs)c=int(cs)
ans=a+b+c # proves we converted from string to numbers
Quick check• Ask the user for his number of siblings and convert
the to an integer (paper answer)• Ask the user for price of soda and covert to decimal
number(paper answer)• NEXT: Go to IDLE
– New Window – Save as testInput.py#Testing input and conversionsage=input(“Enter your age”)ans=sage*2
– Did it work? Try converting sage to integer age and then multiplying age * 2
– Did this work?
FORMATTING OUTPUT
7
Formatting• Two separate parts:• The mask(s) to be used in formatting• The value(s) to be formatted• The mask(s)
– Surrounded by quote marks– Each mask is preceded by %– Each mask is followed by its type (s,f,d)– Each mask can have a width– All items are right justified unless specified differently
• The value(s)– Enclosed in parenthesis – Preceded by %– In same order as the mask(s)
Formatting Output• Outputting floating point values can look strange: price = 1.21997
• We want to format the output to look good – Want 1.22– print(“%.2f” % price)
• Suppose we want a field of width 10 characters– print("%10.2f" % price)
• The %10.2f is called a format specifier
10 spaces 9
Syntax: formatting strings
Copyright © 2011 by John Wiley & Sons. All rights reserved.
Page 10
Formatting Examples:
• Left Justify a String: print("%-10s" %("Total:"))
Right justify a number with two decimal places print("%10.2f" %(price))
And you can print multiple values: print("%-10s%10.2f" %("Total: ", price))
11
Format String
Sample output
Comments
“%d” 24 Use with integers
“%5d” 24 3 spaces to left of number
“%05d” 00024 3 zeroes to left of number
“HI:%5d”
HI: 24 Word HI followed by 3spaces&#
“%f” 1.21997 Use with Floating point number
“%2f” 1.22 2 places after decimal & rounds
“%5s” HI String right justified
“%-5s” HI String left justified
“%d%%” 24% Adds a % after number
Quick check with Partner• Open IDLE• Type the following and save as testFmt.py
# Testing Format# testFmt.pymyString=“HI”myInt=54myFloat=1.21997print(“Format Example = \n“ , -------)
• Change ---- to format mask in quotes and the %(number) you are formatting (no comma in between)
GRAPHICS
14
Download Graphics• For our class Schedule for today, download
Graphics.zip• Unzip it and...• Store it in on your computer or on VUAD (the
shared space on the university system)• Open the folder and look at the files
15
Creating Graphics Window• First: Import the Graphics Window:
from graphics import GraphicsWindow
• Second: Size the window to (640 x 480 pixels):
win = GraphicsWindow(640, 480)
• Third: Access the canvas contained in the graphics window:
canvas = win.canvas()
Drawing on a Canvas & Waiting• Once we have the canvas we can draw• Example
canvas.drawRect(15, 10, 20, 30)
•Must “wait” after drawing to allow window to stay opened until user clicks the X to close the window
win.wait()
A graphics window
Copyright © 2011 by John Wiley & Sons. All rights reserved.
Page 18
Quick Check• Download the graphics module• Create the following short program called testWin.py in IDLE and run it
#Test Graphics Windowfrom graphics import GraphicsWindowwin = GraphicsWindow()canvas=win.canvas()canvas.drawRect(5,10,20,30)win.wait()
Math Coordinate System
x- Axis
y- Axis
0,0
Python Coordinate System
0,0
21
y- Axis
x- Axis
Lines • Draw from one point to a second point• Each point is designated with an x,y coordinate• Example:
canvas.drawLine(x1,y1,x2,y2)
• Example:
canvas.drawLine(40,10, 100,65)
canvas.drawLine:
23
x1, y1
x2,y2
0, 0
drawLine(x1, y1, x2, y2)
Drawing a Line
Copyright © 2012 Pearson Education, Inc.
X
Y
10
20
150
45
canvas.drawLine (10, 20, 150, 45)
canvas.drawLine (150, 45, 10, 20)
or
Lets have some Fun• Basic shapes have 4 properties: x coordinate, y
coordinate, width and height.• Example:
canvas.drawRect(20, 15,120, 75)– This statement draws a rectangle with the upper top left
corner at point (20,15) in the window with a width of 120 and a width of 75.
• Common shapes that can be drawn include: rectangles, squares, circles and ovals.
• In a Square the width and height are equal
canvas.drawRect:
26
x, y width
height
0, 0
drawRect( x, y, width, height)
Drawing Ovals:• To draw an oval (or circle)• We specify the rectangle into which the oval is to be
inscribed• The rectangle is the bounding box that will contain
the oval
canvas.drawOval(x,y, width, height)
• Example:
canvas.drawOval(175, 20, 50, 80)
Drawing an Oval
Copyright © 2012 Pearson Education, Inc.
X
Y
canvas.drawOval (175, 20, 50, 80)
175
20
50
80
boundingrectangle
Quick Check• Take testWin.py: change the win instruction to be:
win = GraphicsWindow(680,400)• and do the following additional code just before the
instruction:
win.wait()
• Draw an oval• Draw a circle• Draw a line• Save and run the program
Making Text Part of Drawing• Used to label parts of a drawing• Specify x, y coordinates of where to start• Specify the message in Quotes• Example:
cavas.drawText(x,y, “Message”)
canvas.drawText(50,100, “Hi There”)-----------------------------------------------------------
Quick Check: Add to testWin.py before the wait, save and run program
Recap
Colors – codes and color names• Colors use the RGB code – 0 to 255• Example:
(255, 0, 0 ) Lots of Red, no green, no blue
(0, 255, 0) No red, lots of green, no blue
(255, 0, 255) Red, no green, Blue = purple
• Color names are easier
Color Names
Set Outline colors• Default outline is black• Change outline color as follows:
canvas.setOutline(255,0,0)
or
canvas.setOutline(“red”)
• Once the outline is set you can draw your shape
canvas.drawOval(175, 20, 50, 80)
Fill Shapes• Default is no Fill• To fill shapes
canvas.setFill(0,255,0) # fills green• or
canvas.setFill(“green”)• Then:
canvas.drawOval(175, 20, 50, 80)
• To Erase Fill:
canvas.setFill()
Sets Color for Both Fill and Outline• Uses RGB or Color Names:
canvas.setColor(red, green, blue values)
canvas.setColor(“name”)
Example:
canvas.setColor(0,0,255)canvas.setColor(“blue”)• Then
canvas.drawOval(175, 20, 50, 80)
Recap
Going Back to defaults
canvas.setFill("red")canvas.setOutline("black")canvas.setFill()canvas.drawOval(310,340,75, 85)
Remember: • To create any graphics program you need:
from graphics import GraphicsWindow
win = GraphicsWindow(680,400)
canvas=win.canvas()
# your code in here
win.wait()
Quick Check• Open IDLE and create a program: testColor.py
– Remember you will need the import, window, canvas and wait instructions. Move the shape each time, so all show
1. set the outline color to one of your choice
2. display any shape
3. set the fill color to another color using RGB
4. display a different shape
5. Set an outline of one color and a fill of a second color and display a third shape
6. Display a 4th shape using the settings from #5
7. Erase the outline from all shapes and display again the same shape used in #6
8. Show to instructor, TA or lab neighbor.
Summary• The Python library has mathematical
functions like sqrt() and abs()
• Convert between integers, floats and strings using the respective functions: int(), float(), str()
• Python libraries are grouped into modules. Use the import statement to use methods from a module.
41
String Summary• Strings are sequences of characters.
• len() function yields the number of characters in a String.
• Use the + operator to concatenate Strings; that is, to put them together to yield a longer String.
• To perform a concatenation, the + operator requires both arguments to be strings.
• Numbers must be converted to strings using the str() function.
42
String Summary, continued
• String index numbers are counted starting with 0.
• Use the [ ] operator to extract the elements of a String.
43
Summary, continued• Use the input() function to read keyboard input
in a console window.• Use the format specifiers to specify how values
should be formatted.
--------------------------------------------------• Graphical shapes (such as squares, rectangles,
circles, ovals), or lines and text can be drawn using the graphics module.
• The color of graphical objects can be set with the setOutline() and setFill() methods.
44