Title: Guide to Programming with Python
1Guide to Programming with Python
- Chapter One
- Getting Started The Game Over Program
2Objectives
- Introduce Python
- Demonstrate how to install Python
- Explain how to print text to the screen
- Describe comments and how to use them
- Demonstrate Pythons development environment,
IDLE, using it to write, edit, run, and save
programs - Course mechanics
3Examining the Game Over Program
- Figure 1.1 Game Over Program Output
- The all-too familiar words from a computer game
4Examining the Game Over Program (continued)
- Hello World program By tradition, prints
"Hello, world! - Often used as first program
- Console window Provides a text-based interface
to Windows operating system - Terminal application Provides a text-based
interface to Mac OS X and Linux operating systems
5Where well get to by the end
- From Game Over to real games.
- Demos from previous semester(s)
- Every program you write in this class will be
related to gaming! - But how do you make these games?
6Programming!
- Getting your computer to do stuff.
- By being very specificlike writing recipes for a
very dumb robot - Why learn programming?
- Computers are an empowering universal tool
- Lots of jobs in programming
- All fields of science rely on computers now
- Even if you dont ever program again, youll
learn valuable skills for tackling problems by
breaking them down into smaller problems and
thinking logically
7Introducing Python
- Powerful yet easy to use programming language
- Developed by Guido van Rossum
- First released in 1991
- Named after comedy troupe Monty Python
- An alarming number of references to spam, eggs,
and the number 42 in documentation
8Monty Python DemonstratesWhy Programming
Computers is Hard
9Why Python? Its Easy to Use
- High-level language Distinct from the low-level
processor operations closer to human language
than machine language - "Programming at the speed of thought"
- Increases productivity
- Python programs three to five times shorter than
Java - Python programs five to ten times shorter than
C - Normally, Programming is like making fine
furniture with an axe and a nail file. - Python makes it more like working with a table
saw a lathe - You still have to learn how to use them, but
theyre the right tools for the job
10Python Is Easy to Use (continued)
- Python Program
- print "Game Over!"
- C Program
- include ltiostreamgt
- int main()
-
- stdcout ltlt "Game Over!" ltlt stdendl
- return 0
-
11Python Is Powerful
- Used by large organizations
- NASA
- Google
- Microsoft
- Used in published games
- Battlefield 2
- Civilization IV
- Disneys Toontown Online
- Used throughout academia and the scientific
community
12Python Is Object-Oriented
- Object-oriented programming (OOP) Methodology
that defines problems in terms of objects that
send messages to each other - In a game, a Missile object could send a Ship
object a message to Explode - OOP not required, unlike Java and C
13Python Is a Glue Language
- Can be integrated with other languages
- C/C
- Java
- Use existing code
- Leverage strengths of other languages
- Extra speed that C or C offers
14Python Runs Everywhere
- Platform independent Independent of the specific
computer operating system - Python runs on
- Windows
- DOS
- Mac OS X
- Linux
- Many more
15Python Has a Strong Community
- As an approachable language, has approachable
community - Python Tutor mailing list
- http//mail.python.org/mailman/listinfo/tutor
- Perfect for beginners
- No actual "tutors" or "students"
16Python Is Free and Open Source
- Open source Publicly available open source
software typically programmed by volunteers
anyone can use source code without fee - Can modify or even resell Python
- Embracing open-source ideals is part of what
makes Python successful
17Python is Popular
- All those advantages make Python a commonly used
(and liked) language (http//www.langpop.com/)
Java C C Javascript PHP Python SQL Perl C
18Installing Python
- Do NOT install anything from the textbooks
CD-ROM - Instead, follow the instructions on the class web
page - Dont have to worry about PyGame LiveWires yet
- Windows
- Go to http//www.python.org/download/
- Download the latest standard (aka production)
release installer (.msi file) --e.g. Python 2.6.4 - Double-click the installer program and follow its
instructions to install Python on your boot (C)
drive
19Installing Python (continued)
- Linux
- Python probably already installed
- Test try running python at command prompt
- If not installed, go to http//www.python.org/down
load/ (you will probably need to build from
source) - Mac OS X
- For 10.5.x or 10.6.x follow the instructions on
the class web site (install Enthought Python
Distribution and replace IDLE) - For earlier versions download appropriate version
from Python web site at http//www.python.org/down
load/
20Introducing IDLE
- Integrated Development Environment (IDE)
Application that helps software developers write
programs - Like a word processor for your code
- IDLE is the IDE that ships with Python
- Has two modes Interactive and Script
21Programming in Interactive Mode
Figure 1.4 Python in interactive mode Python
awaits your command.
22Programming in Interactive Mode (continued)
- Great for immediate feedback
- Test a simple idea
- Remember how something works
- Open Python in interactive mode
- Windows From the Start menu, choose Programs,
Python ltversiongt, IDLE (Python GUI) - Mac Launch /Applications/Enthought/IDLE.app
- On STC Lab machines
- Windows Will be in Start menu gt All Programs gt
Departmentally Sponsored gt Informatics gt IDLE (or
python26) - Mac Click IDLE 2.6 in the Departmentally
Sponsored folder in the Dock, or type
/usr/local/bin/python2.6 from the command line in
/Applications/Utilities/Terminal.app
23Programming in Interactive Mode (continued)
- At command prompt (gtgtgt), type print "Game Over"
- Python responds with Game Over
24Programming in Interactive Mode (continued)
- print Statement can display a string (actually,
any expression) - String Sequence of characters
- Statement Single unit in programming language
that performs some action - print "Game Over"
- Expression Something which has a value or that
can be evaluated to a single value - "Game Over"
- 7 2
- Code Sequence of programming statements
25Programming in Interactive Mode (continued)
- Syntax highlighting Displaying programming code
in different colors or fonts, according to the
category of each item (e.g. in IDLE) - Errors
- Computers take everything literally
- primt "Game Over" produces an Error Message
SyntaxError invalid syntax - Syntax error Error in the rules of usage often
a typo - Bug Error in programming code usually a logic
error a mistake that produces unintended results
26(No Transcript)
27Programming in Script Mode
Figure 1.5 Python in script mode Your blank
canvas awaits.
28Programming in Script Mode (continued)
- Great for programs you want to run later
- Write, edit, save, and load programs
- Like word processor for your programs
- Find and replace
- Cut and paste
- Open a script window
- In interactive window, select File menu, New
Window
29Programming in Script Mode (continued)
- Write program
- In script window, type print "Game Over"
- Save program
- Select File, Save As, name game_over.py
- Always save before running
- Run Program
- Select Run, Run Module
- Results displayed in interactive window
30Programming in Script Mode (continued)
- Figure 1.6 Python after a script has been run
- The results of running the Game Over program
31The Game Over Program
- Game Over
- Demonstrates the print command
- print "Game Over"
- raw_input("\n\nPress the enter key to exit.")
32The Game Over Program (continued)
- Comment A note in source code meant only for
programmers ignored by computer - Start comment with
- Use opening block of comments to say what program
does, who wrote it and when - Blank Lines
- Also (generally) ignored by computer
- Use for readability keep related code together
- Console Window
- Final line keeps console window open until youre
ready to end it
33Summary
- Python is a high-level, object-oriented
programming language thats powerful yet easy to
use - Python can interface with other programming
languages - IDLE is Pythons standard IDE
- IDLE has an interactive mode that offers
immediate response to Python code - IDLE has a script mode that allows programmers to
write, edit, load, save, and run their programs
34Summary (continued)
- A string is a sequence of characters
- A statement is a single unit of programming that
performs some action - The print statement displays strings on the
screen - An expression is something which has a value or
that can be evaluated to a single value - Syntax highlighting is displaying programming
code in different colors or fonts, according to
the category of each item
35Summary (continued)
- A syntax error is a violation of the grammar of a
programming language often caused by a typo - A logical error is a mistake made at run time
that produces incorrect results - A bug is an error in programming code
- A comment is a note in source code meant only for
programmers ignored by computer - Comments start with
- You should use an opening block of comments in
your programs to identify the programmer, the
creation date, and the programs purpose
36Summary (continued)
- For all class info see the class web page
- http//informatics.indiana.edu/larryy/I210
- All quizzes, assignments, and grades administered
through Oncourse in the combined lecture section - Class structure 2 lectures, 1 lab
- lab attendance is mandatory
- lab quiz administered at random times
37Summary (continued)
- Weekly assignments (and quizzes) are from the
book - Read it!
- Assignments are administered via the Assignments
page on Oncourse in the combined lecture section - Upload files with names specified in the
assignment - Due before Tuesday class!
- Midterm exam will be given during lab of week 7
- Final game project (instead of final exam)
38Summary (continued)
- No cellphones in lectures
- No computers in lectures unless prompted
- Bring laptops to labs and to office-hour visits
(if possible) - No late submission of assignments
- Help each other, but no copying of codewell
find it! - This class is hard, and you learn programming by
doing it. So put in the time, come prepared to
labs and office hours, and keep up! And have fun!
39Guide to Programming with Python
- Chapter Two
- Types, Variables, and Simple I/O The Useless
Trivia Program
40Objectives
- Use triple-quoted strings and escape sequences
- Make programs do math
- Store data in the computers memory
- Use variables to access and manipulate that data
- Get input from users to create interactive
programs
41The Useless Trivia Program
- Figure 2.1 Sample run of the Useless Trivia
program - Whoa! Steve might think about a diet before he
visits the sun.
42Using Quotes with Strings
- Can create a single string that's paragraphs long
- Can format text of string in a specific manner
- Can use quotes to create long string or to format
43The Game Over 2.0 Program
- Figure 2.2 Sample run of the Game Over 2.0
program - Ah, the game is really over.
44Using Quotes
- Using quotes inside strings
- Define with either single (') or double quotes
(") - 'Game Over' or "Game Over"
- Define with one type, use other type in string
- "Program 'Game Over' 2.0"
- Triple-quoted strings can span multiple lines
- """
- I am a
- triple-quoted string
- """
- Line-continuation character \
45Using Escape Sequences with Strings
- Escape sequence Set of characters that allow you
to insert special characters into a string - Backslash followed by another character
- e.g. \n
- Simple to use
46The Fancy Credits Program
- Figure 2.3 Sample run of the Fancy Credits
program - So many people to thank, so many escape sequences
47Escape Sequences
- System bell
- print "\a"
- Tab
- print "\t\t\tFancy Credits"
- Backslash
- print "\t\t\t \\ \\ \\ \\ \\ \\ \\"
- Newline
- print "\nSpecial thanks goes out to"
- Quote
- print "My hair stylist, Henry \'The Great\', who
never says \"can\'t\"."
48Escape Sequences (continued)
- Table 2.1 Selected escape sequences
49Concatenating and Repeating Strings
- Can combine two separate strings into larger one
- Can repeat a single string multiple times
50The Silly Strings Program
- Figure 2.4 Sample run of the Silly Strings
program - Strings appear differently than in the program
code.
51Concatenating Strings
- String concatenation Joining together of two
strings to form a new string - When used with string operands, is the string
concatenation operator - "concat" "enate"
- Suppressing a Newline
- When used at the end of print statement, comma
suppresses newline - print "No newline after this string",
52Repeating String
- Multiple concatenations
- When used with strings, creates a new string by
concatenating a string a specified number of
times - Like multiplying a string
- "Pie" 10 creates new string "PiePiePiePiePiePieP
iePiePiePie"
53Working with Numbers
- Can work with numbers as easily as with strings
- Need to represent numbers in programs
- Score in space shooter game
- Account balance in personal finance program
- Python can represent different types of numbers
54The Word Problems Program
- Figure 2.5 Sample run of the Word Problems
program - With Python, you can keep track of a pregnant
hippos weight.
55Numeric Types
- Type Represents the kind of value determines
how the value can be used - Two common numeric types
- Integers Numbers without a fractional part
- 1, 0, 27, -100
- Floating-Point Numbers (or Floats) Numbers with
a fractional part - 2.376, -99.1, 1.0
56Mathematical Operators
- Addition and Subtraction
- print 2000 - 100 50 displays 1950
- Integer Division
- print 24 / 6 displays 4
- But print 19 / 4 displays 4 as well
- Result of integer division always integer
- Floating-Point Division
- print 19.0 / 4 displays 4.75
- When at least one number is a float, result is a
float - Modulus (remainder of integer division)
- print 107 4 displays 3
57Mathematical Operators (continued)
- Table 2.2 Mathematical operators with integers
58Mathematical Operators (continued)
- Table 2.3 Mathematical operators with floats
59Understanding Variables
- Variable Represents a value provides way to get
at information in computer memory - Variables allow you to store and manipulate
information - You can create variables to organize and access
this information
60The Greeter Program
- Figure 2.6 Sample run of the Greeter program
- Using a variable for the name
61Creating Variables
- Assignment statement Assigns a value to a
variable creates variable if necessary - name "Larry"
- Stores string "Larry" in computer memory
- Creates variable name
- Assigns value so that name refers to "Larry"
62Using Variables
- Use variable where you want value it represents
- print name or print "Larry"
- Both display Larry
- print "Hi, " name or print "Hi, Larry"
- Both display Hi, Larry
63Naming Variables
- Rules for legal variable names
- Can contain only numbers, letters, and
underscores - Cant start with a number
- Cant be a keyword
- Keyword Built-in word with special meaning
- Legal Names
- velocity, player2, max_health
- Illegal Names
- ?again, 2nd_player, print
64Naming Variables (continued)
- Guidelines for good variable names
- Choose descriptive names score instead of s
- Be consistent high_score or highScore
- Follow traditions Names that begin with
underscore have special meaning - Keep the length in check personal_checking_account
_balance - too long? - Self-documenting code Code written so that its
easy to understand, independent of any comments
65Getting User Input
- Variables important for
- Getting user input
- Storing user input
- Manipulating user input
66The Personal Greeter Program
- Figure 2.7 Sample run of the Personal Greeter
program - name is assigned a value based on what the user
enters.
67Getting User Input
- Function A named collection of programming code
that can receive values, do some work, and return
values - Argument Value passed to a function
- Return value Value returned from a function upon
completion - Function is like a pizzeria
- Make a call
- Provide information (like pepperoni)
- Get something back (like a hot pepperoni pizza)
68Getting User Input (continued)
- raw_input() function
- Prompts the user for text input
- Returns what the user entered as a string
- name raw_input("Hi. What's your name? ")
- Uses argument "Hi. What's your name? " to prompt
user - Returns what user entered as a string
- In assignment statement, name gets returned
string
69Using String Methods
- String methods allow you to do many things,
including - Create new strings from old ones
- Create string thats all-capital-letters version
of original - Create new string from original, based on letter
substitutions
70The Quotation Manipulation Program
- Figure 2.8 Sample run of the Quotation
Manipulation program - The slightly low guess is printed several times
with string methods.
71String Methods
- Method A function that an object has
- Use dot notation to call (or invoke) a method
- Use variable name for object, followed by dot,
followed by method name and parentheses - an_object.a_method()
- Strings have methods that can return new strings
72String Methods (continued)
- quote "I think there is a world market for
maybe five computers." - print quote.upper()
- I THINK THERE IS A WORLD MARKET FOR MAYBE FIVE
COMPUTERS. - print quote.lower()
- i think there is a world market for maybe five
computers. - print quote.title()
- I Think There Is A World Market For Maybe Five
Computers. - print quote.replace("five", "millions of")
- I think there is a world market for millions of
computers. - Original string unchanged
- print quote
- I think there is a world market for maybe five
computers.
73String Methods (continued)
- Table 2.4 Useful string methods
74Using the Right Types
- Important to know which data types are available
- Equally important to know how to work with them
- If not, might end up with program that produces
unintended results
75The Trust Fund BuddyBad Program
- Figure 2.9 Sample run of the Trust Fund
Buddy-Bad program - The monthly total should be high, but not that
high.
76Logical Errors
- Logical Error An error that doesnt cause a
program to crash, but instead produces unintended
results - Program output that looks like very large number
200001000017000500075001200068001000 - Remember, raw_input() returns a string, so
program is not adding numbers, but concatenating
strings
77Logical Errors (continued)
- car raw_input("Lamborghini Tune-Ups ")
- rent raw_input("Manhattan Apartment ")
- jet raw_input("Private Jet Rental ")
- gifts raw_input("Gifts ")
- food raw_input("Dining Out ")
- staff raw_input("Staff (butlers, chef, driver,
assistant) ") - guru raw_input("Personal Guru and Coach ")
- games raw_input("Computer Games ")
- total car rent jet gifts food staff
guru games - car, rent, jet, gifts, food, staff, guru, games
are strings - total is concatenation of all strings
78Converting Values
- Can convert one type of value to another
- Use built-in functions
- Solution to Trust Fund BuddyBad program
79The Trust Fund BuddyGood Program
- Figure 2.10 Sample run of the Trust Fund
Buddy-Good program - Now the total is right.
80Converting Types
- int() function converts a value to an integer
- car raw_input("Lamborghini Tune-Ups ")
- car int(car)
- Can nest multiple function calls
- rent int(raw_input("Manhattan Apartment "))
81Converting Types (continued)
- Table 2.5 Selected type conversion functions
82Augmented Assignment Operators
- Common to assign a value to a variable based on
its original value - For example, increment value of variable
- Augmented assignment operators provide condensed
syntax - Original score score 1
- Augmented score 1
83Augmented Assignment Operators (continued)
- Table 2.6 Useful augmented assignment operators
84Printing Multiple Values
- To print multiple values in single print
statement, separate values by commas - print "\nGrand Total ", total
85Summary
- String can be defined with either single or
double quotes - Tripled-quoted strings, defined by three opening
and closing quotes, can span multiple lines - An escape sequence is a set of characters that
allow you to insert special characters into a
string - String concatenation is the joining together of
two strings to form a new string - Integers, whole numbers with no decimal part, and
floats, numbers with a decimal part, are two
numeric types
86Summary (continued)
- Result of integer division is always an integer
while result of floating-point division is always
a float - A variable represents a value and provides way to
get at information in computer memory - An assignment statement assigns a value to a
variable and creates variable if necessary - A function is a named collection of programming
code that can receive values, do some work, and
return values - The raw_input() function prompts the user for
input and returns what the user entered as a
string
87Summary (continued)
- A method is a function that an object has
- Strings have methods that can return new strings
- A logical error produces unintended results
- Python has functions for converting values to an
integer, a float, or a string - Augmented assignment operators provide condensed
syntax for changing the value of a variable based
on its original value