Guide to Programming with Python - PowerPoint PPT Presentation

About This Presentation
Title:

Guide to Programming with Python

Description:

Guide to Programming with Python Chapter One Getting Started: The Game Over Program – PowerPoint PPT presentation

Number of Views:949
Avg rating:3.0/5.0
Slides: 82
Provided by: indi63
Category:

less

Transcript and Presenter's Notes

Title: Guide to Programming with Python


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

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 Pythons development environment,
    IDLE, using it to write, edit, run, and save
    programs

3
Examining the Game Over Program
  • Figure 1.1 Game Over Program Output
  • The all-too familiar words from a computer game

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

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

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

7
Python Is Easy to Use (continued)
  • Python Program
  • print "Game Over!"
  • C Program
  • include ltiostreamgt
  • int main()
  • stdcout ltlt "Game Over!" ltlt stdendl
  • return 0

8
Python Is Powerful
  • Used by large organizations
  • NASA
  • Google
  • Microsoft
  • Used in published games
  • Battlefield 2
  • Civilization IV
  • Disneys Toontown Online

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

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

11
Python Runs Everywhere
  • Platform independent Independent of the specific
    computer operating system
  • Python runs on
  • Windows
  • DOS
  • Mac OS
  • Linux
  • Many more

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"

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

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
  • Go to http//www.python.org/download/
  • Download the latest standard (aka production)
    release installer (.msi file)
  • Double-click the installer program and follow its
    instructions to install Python on your boot (C)
    drive

15
Setting up Python on Windows

Figure 1.2 Python 2.3.5 Installation Dialogue
under Windows Your computer is soon to be home to
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/down
    load/ (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/m
    oin/MacPython/Leopard
  • Earlier Mac OS X and other systems
  • If necessary, download appropriate version from
    Python web site at http//www.python.org/download/

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

18
Programming in Interactive Mode
Figure 1.4 Python in interactive mode Python
awaits your command.
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 ltversiongt, IDLE (Python GUI)
  • On STC Lab machines
  • Windows Will be in Start menu gt All Programs gt
    Departmentally Sponsored gt Informatics
  • Mac Type python in /Applications/Utilities/Termin
    al.app or run IDLE.app from the Developer Tools
    folder in the Dock

20
Programming in Interactive Mode (continued)
  • At command prompt (gtgtgt), type print "Game Over"
  • Python responds with Game Over

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

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

23
(No Transcript)
24
Programming in Script Mode

Figure 1.5 Python in script mode Your blank
canvas awaits.
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

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

27
Programming in Script Mode (continued)
  • Figure 1.6 Python after a script has been run
  • The results of running the Game Over program

28
The Game Over Program
  • Game Over
  • Demonstrates the print command
  • print "Game Over"
  • raw_input("\n\nPress the enter key to exit.")

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

30
Summary
  • 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

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

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 programs purpose 

33
Guide to Programming with Python
  • Chapter Two
  • Types, Variables, and Simple I/O The Useless
    Trivia Program

34
Objectives
  • 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

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.

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

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.

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 a
  • triple-quoted string
  • """
  • Line-continuation character \

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

40
The Fancy Credits Program
  • Figure 2.3 Sample run of the Fancy Credits
    program
  • So many people to thank, so many escape sequences

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

42
Escape Sequences (continued)
  • Table 2.1 Selected escape sequences

43
Concatenating and Repeating Strings
  • Can combine two separate strings into larger one
  • Can repeat a single string multiple times

44
The Silly Strings Program
  • Figure 2.4 Sample run of the Silly Strings
    program
  • Strings appear differently than in the program
    code.

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

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 "PiePiePiePiePiePieP
    iePiePiePie"

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

48
The Word Problems Program
  • Figure 2.5 Sample run of the Word Problems
    program
  • With Python, you can keep track of a pregnant
    hippos weight.

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

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

51
Mathematical Operators (continued)
  • Table 2.2 Mathematical operators with integers

52
Mathematical Operators (continued)
  • Table 2.3 Mathematical operators with floats

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

54
The Greeter Program
  • Figure 2.6 Sample run of the Greeter program
  • Using a variable for the name

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"

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

57
Naming 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

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 its
    easy to understand, independent of any comments

59
Getting User Input
  • Variables important for
  • Getting user input
  • Storing user input
  • Manipulating user input

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.

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)

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

63
Using 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

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.

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

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 quote
  • I think there is a world market for maybe five
    computers.

67
String Methods (continued)
  • Table 2.4 Useful string methods

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

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

70
Logical 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

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

72
Converting Values
  • Can convert one type of value to another
  • Use built-in functions
  • Solution to Trust Fund BuddyBad program

73
The Trust Fund BuddyGood Program
  • Figure 2.10 Sample run of the Trust Fund
    Buddy-Good program
  • Now the total is right.

74
Converting 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 "))

75
Converting Types (continued)
  • Table 2.5 Selected type conversion functions

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

77
Augmented Assignment Operators (continued)
  • Table 2.6 Useful augmented assignment operators

78
Printing Multiple Values
  • To print multiple values in single print
    statement, separate values by commas
  • print "\nGrand Total ", total

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

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

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
Write a Comment
User Comments (0)
About PowerShow.com