Transcript Session 2
Computer Graphics and
Games
MONT 105S, Spring 2009
Lecture 2
Simple Python Programs
Working with numbers and strings
1
Review
Write a program that asks for a user's favorite food, and then
says that it likes that food too.
# Program: food.py
# Purpose: Asks user for their favorite food, and tells
# them it likes that food too.
faveFood = raw_input("What is your favorite food? ")
print "I love " + faveFood + " too!"
What does this print out if the user enters 'Chocolate' when
asked for their favorite food?
2
Classes and Objects
Python is an object oriented programming language.
All items of data are objects.
Objects have properties: Things that describe the objects
Objects have methods: Things an object can do.
A class describes a group of objects that have the same methods
and set of properties.
Example: A car class
Properties: color, number of doors, body type
Methods: accelerate, brake, steer
My car is an object that is a member of the car class.
3
Primitive Numeric Types
Type
integer
Kind of info
whole number
Uses
Arithmetic expressions
long integer
Large whole number
floating point decimal number
Examples:
integer: 12
-37
"
"
"
"
5672
long integer: 29387651298L
floating point: 12.6
0.2
-7.615
4
Arithmetic Expressions
with Floating Point Numbers
Arithmetic operators for real numbers:
+
*
/
**
These work the way you would expect:
4.0 + 3.3
7.3
5.0 * 7.0
35.0
3.6 / 3
1.2
2.0**3.0
8.0
5
Arithmetic Expressions
with Integers
Arithmetic operators for integers:
+
*
/
%
**
All work the way you would expect, except / and %
DIV: Integer division truncates the decimal portion.
12 / 3
4
8/3
2
1/2
0
MOD: Gives the remainder of division of two integers:
7%2
1
11 % 4
3
6
Example Using Numbers
# Program: dogYears.py
# Purpose: To calculate a dogs age in dogyears.
ageOfDog = input("How old is the dog? ")
dogYears = 7*ageOfDog
print "The dog is", dogYears, "years old in dogyears."
7
Using commas vs. + in a print
statement
•A + sign is used to concatenate (join) two strings.
•It can be used in a print statement to print two strings joined
together.
•It cannot be used to join a string with a number.
Example:
myCat = "Calico"
print "My cat is a " + myCat
•A comma is used to list items to print. It is used when we have
several items of different types (e.g. a string and an integer) that
we want to print.
Example:
myAge = 39
print "My age is", myAge
8
Strings
A line of text is called a string.
A string is indicated using quotes.
Example:
>>>"dog"
'dog'
Triple quotes allow newlines in the middle of a string.
Example:
>>> ' ' 'This string has a break
in the middle. ' ' '
'This string has a break\nin the middle.'
9
String Methods
Python provides a variety of operations with strings:
Concatenation: +
"dog" + "house" -> "doghouse"
Repetition: *
"cool"*3
-> "coolcoolcool"
Length: len(stringName)
len("cool")
-> 4
There are numerous other operations that can be applied to strings.
Some of these are described in your textbook.
10