81
Guide to Programming with Python Chapter One Getting Started: The Game Over Program

Guide to Programming with Python Chapter One Getting Started: The Game Over Program

Embed Size (px)

Citation preview

Guide to Programming with Python

Chapter OneGetting Started: The Game Over Program

Guide to Programming with Python 2

Objectives

• Introduce Python

• Demonstrate how to install Python

• Explain how to print text to the screen

• Describe comments and how to use them

• Demonstrate Python’s development environment, IDLE, using it to write, edit, run, and save programs

Guide to Programming with Python 3

Examining the Game Over Program

Figure 1.1: Game Over Program OutputThe all-too familiar words from a computer game

Guide to Programming with Python 4

Examining 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

Guide to Programming with Python 5

Introducing 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

Guide to Programming with Python 6

Python Is Easy to Use

• High-level language: Separate 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++

Guide to Programming with Python 7

Python Is Easy to Use (continued)

• Python Programprint "Game Over!"

• C++ Program#include <iostream>

int main()

{

std::cout << "Game Over!" << std::endl;

return 0;

}

Guide to Programming with Python 8

Python Is Powerful

• Used by large organizations– NASA– Google– Microsoft

• Used in published games– Battlefield 2– Civilization IV– Disney’s Toontown Online

Guide to Programming with Python 9

Python 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#

Guide to Programming with Python 10

Python 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

Guide to Programming with Python 11

Python Runs Everywhere

• Platform independent: Independent of the specific computer operating system

• Python runs on – Windows– DOS– Mac OS– Linux– Many more

Guide to Programming with Python 12

Python 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"

Guide to Programming with Python 13

Python 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

Guide to Programming with Python 14

Setting up Python on Windows

• The book suggests using the CD-ROM it came with, but that version of Python (2.3.5) is old now

• Instead, follow the instructions on the class web page:1. Go to http://www.python.org/download/

2. Download the latest “standard” (aka “production”) release installer (.msi file)

3. Double-click the installer program and follow its instructions to install Python on your boot (C:) drive

Guide to Programming with Python 15

Setting up Python on Windows

Figure 1.2: Python 2.3.5 Installation Dialogue under WindowsYour computer is soon to be home to Python.

Guide to Programming with Python 16

Setting up Python on Other Operating Systems

• Linux– Python probably already installed– Test: try running python at command prompt– If not installed, go to http://www.python.org/download/ (you will

probably need to build from source)

• Mac OS 10.5.x– Leopard (10.5.x) already has Python 2.5.1 installed, but you need

to install IDLE.app following instructions at http://wiki.python.org/moin/MacPython/Leopard

• Earlier Mac OS X and other systems– If necessary, download appropriate version from Python web site

at http://www.python.org/download/

Guide to Programming with Python 17

Introducing IDLE

• Integrated Development Environment (IDE): Application that helps software developers write programs– Like a word processor for your code

• IDE that ships with Python

• Has two “modes”: Interactive and Script

Guide to Programming with Python 18

Programming in Interactive Mode

Figure 1.4: Python in interactive modePython awaits your command.

Guide to Programming with Python 19

Programming in Interactive Mode (continued)

• Great for immediate feedback– Test a simple idea– Remember how something works

• Open Python in interactive mode– In Windows, from the Start menu, choose Programs, Python

<version>, IDLE (Python GUI)

• On STC Lab machines– Windows: Will be in Start menu > All Programs >

Departmentally Sponsored > Informatics– Mac: Type python in /Applications/Utilities/Terminal.app or run

IDLE.app from the Developer Tools folder in the Dock

Guide to Programming with Python 20

Programming in Interactive Mode (continued)

• At command prompt (>>>), type: print "Game Over"• Python responds with: Game Over

Guide to Programming with Python 21

Programming 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

Guide to Programming with Python 22

Programming in Interactive Mode (continued)

• Syntax highlighting: Displaying programming code in different colors or fonts, according to the category of each item

• 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

Guide to Programming with Python 23

Guide to Programming with Python 24

Programming in Script Mode

Figure 1.5: Python in script modeYour blank canvas awaits.

Guide to Programming with Python 25

Programming 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

Guide to Programming with Python 26

Programming 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

Guide to Programming with Python 27

Programming in Script Mode (continued)

Figure 1.6: Python after a script has been runThe results of running the Game Over program

Guide to Programming with Python 28

The Game Over Program

# Game Over

# Demonstrates the print command

print "Game Over"

raw_input("\n\nPress the enter key to exit.")

Guide to Programming with Python 29

The Game Over Program (continued)

• Comment: Note in source code meant only for programmers; ignored by computer– Start comment with #– Use opening block of comments

• Blank Lines– Also (generally) ignored by computer– Use for readability; keep related code together

• Console Window– Final line keeps console window open

Guide to Programming with Python 30

Summary

• Python is a high-level, object-oriented programming language that’s powerful yet easy to use

• Python can interface with other programming languages

• IDLE is Python’s 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

Guide to Programming with Python 31

Summary (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

Guide to Programming with Python 32

Summary (continued)

• A syntax error is a violation of the grammar of a programming language; often caused by a typo 

• 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 program’s purpose 

Guide to Programming with Python

Chapter TwoTypes, Variables, and Simple I/O: The Useless

Trivia Program

Guide to Programming with Python 34

Objectives

• Use triple-quoted strings and escape sequences

• Make programs do math

• Store data in the computer’s memory

• Use variables to access and manipulate that data

• Get input from users to create interactive programs

Guide to Programming with Python 35

The 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.

Guide to Programming with Python 36

Using 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

Guide to Programming with Python 37

The Game Over 2.0 Program

Figure 2.2: Sample run of the Game Over 2.0 program

Ah, the game is really over.

Guide to Programming with Python 38

Using 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 atriple-quoted string """

• Line-continuation character \

Guide to Programming with Python 39

Using 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

Guide to Programming with Python 40

The Fancy Credits Program

Figure 2.3: Sample run of the Fancy Credits program

So many people to thank, so many escape sequences

Guide to Programming with Python 41

Escape 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\"."

Guide to Programming with Python 42

Escape Sequences (continued)

Table 2.1: Selected escape sequences

Guide to Programming with Python 43

Concatenating and Repeating Strings

• Can combine two separate strings into larger one

• Can repeat a single string multiple times

Guide to Programming with Python 44

The Silly Strings Program

Figure 2.4: Sample run of the Silly Strings program

Strings appear differently than in the program code.

Guide to Programming with Python 45

Concatenating 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",

Guide to Programming with Python 46

Repeating 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 "PiePiePiePiePiePiePiePiePiePie"

Guide to Programming with Python 47

Working 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

Guide to Programming with Python 48

The Word Problems Program

Figure 2.5: Sample run of the Word Problems program

With Python, you can keep track of a pregnant hippo’s weight.

Guide to Programming with Python 49

Numeric 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

Guide to Programming with Python 50

Mathematical 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

Guide to Programming with Python 51

Mathematical Operators (continued)

Table 2.2: Mathematical operators with integers

Guide to Programming with Python 52

Mathematical Operators (continued)

Table 2.3: Mathematical operators with floats

Guide to Programming with Python 53

Understanding 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

Guide to Programming with Python 54

The Greeter Program

Figure 2.6: Sample run of the Greeter program

Using a variable for the name

Guide to Programming with Python 55

Creating 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"

Guide to Programming with Python 56

Using 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

Guide to Programming with Python 57

Naming Variables

• Rules for legal variable names– Can contain only numbers, letters, and underscores– Can’t start with a number– Can’t be a keyword

• Keyword: Built-in word with special meaning

• Legal Names– velocity, player2, max_health

• Illegal Names– ?again, 2nd_player, print

Guide to Programming with Python 58

Naming 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 it’s easy to understand, independent of any comments

Guide to Programming with Python 59

Getting User Input

• Variables important for– Getting user input– Storing user input– Manipulating user input

Guide to Programming with Python 60

The Personal Greeter Program

Figure 2.7: Sample run of the Personal Greeter program

name is assigned a value based on what the user enters.

Guide to Programming with Python 61

Getting 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)

Guide to Programming with Python 62

Getting 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

Guide to Programming with Python 63

Using String Methods

• String methods allow you to do many things, including:– Create new strings from old ones – Create string that’s all-capital-letters version of

original– Create new string from original, based on letter

substitutions

Guide to Programming with Python 64

The Quotation Manipulation Program

Figure 2.8: Sample run of the Quotation Manipulation program

The slightly low guess is printed several times with string methods.

Guide to Programming with Python 65

String 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

Guide to Programming with Python 66

String 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 quoteI think there is a world market for maybe five computers.

Guide to Programming with Python 67

String Methods (continued)

Table 2.4: Useful string methods

Guide to Programming with Python 68

Using 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

Guide to Programming with Python 69

The Trust Fund Buddy–Bad Program

Figure 2.9: Sample run of the Trust Fund Buddy-Bad program

The monthly total should be high, but not that high.

Guide to Programming with Python 70

Logical Errors

• Logical Error: An error that doesn’t 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

Guide to Programming with Python 71

Logical 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

Guide to Programming with Python 72

Converting Values

• Can convert one type of value to another

• Use built-in functions

• Solution to Trust Fund Buddy–Bad program

Guide to Programming with Python 73

The Trust Fund Buddy–Good Program

Figure 2.10: Sample run of the Trust Fund Buddy-Good program

Now the total is right.

Guide to Programming with Python 74

Converting Types

• int() function converts a value to an integercar = raw_input("Lamborghini Tune-Ups: ")

car = int(car)

• Can nest multiple function callsrent = int(raw_input("Manhattan Apartment: "))

Guide to Programming with Python 75

Converting Types (continued)

Table 2.5: Selected type conversion functions

Guide to Programming with Python 76

Augmented 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

Guide to Programming with Python 77

Augmented Assignment Operators (continued)

Table 2.6: Useful augmented assignment operators

Guide to Programming with Python 78

Printing Multiple Values

• To print multiple values in single print statement, separate values by commas– print "\nGrand Total: ", total

Guide to Programming with Python 79

Summary

• 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

Guide to Programming with Python 80

Summary (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

Guide to Programming with Python 81

Summary (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