• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Chapter 1
 

Chapter 1

on

  • 1,714 views

 

Statistics

Views

Total Views
1,714
Views on SlideShare
1,714
Embed Views
0

Actions

Likes
0
Downloads
62
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Chapter 1 Chapter 1 Presentation Transcript

    • Guide to Programming with Python Chapter One Getting Started: The Game Over Program
    • 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
    • Examining the Game Over Program
      • Figure 1.1: Game Over Program Output
      • The all-too familiar words from a computer game
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • Python Is Easy to Use (continued)
      • Python Program
        • print "Game Over!"
      • C++ Program
        • #include <iostream>
        • int main()
        • {
        • std::cout << &quot;Game Over!&quot; << std::endl;
        • return 0;
        • }
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • 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
    • 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 &quot;tutors&quot; or &quot;students&quot;
      Guide to Programming with Python
    • 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
    • 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
      Guide to Programming with Python
    • Setting up Python on Windows Guide to Programming with Python Figure 1.2: Python 2.3.5 Installation Dialogue under Windows Your computer is soon to be home to Python.
    • 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
    • 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
    • Programming in Interactive Mode Guide to Programming with Python Figure 1.4: Python in interactive mode Python awaits your command.
    • 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
    • Programming in Interactive Mode (continued)
      • At command prompt ( >>> ), type: print &quot;Game Over&quot;
      • Python responds with: Game Over
      Guide to Programming with Python
    • 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 &quot;Game Over&quot;
      • Expression : Something which has a value or that can be evaluated to a single value
        • &quot;Game Over&quot;
        • 7 + 2
      • Code : Sequence of programming statements
      Guide to Programming with Python
    • 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
        • pri m t &quot;Game Over&quot; 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
    • Guide to Programming with Python
    • Programming in Script Mode Guide to Programming with Python Figure 1.5: Python in script mode Your blank canvas awaits.
    • 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
    • Programming in Script Mode (continued)
      • Write program
        • In script window, type print &quot;Game Over&quot;
      • 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
    • Programming in Script Mode (continued)
      • Figure 1.6: Python after a script has been run
      • The results of running the Game Over program
      Guide to Programming with Python
    • The Game Over Program
      • # Game Over
      • # Demonstrates the print command
      • print &quot;Game Over&quot;
      • raw_input(&quot; Press the enter key to exit.&quot;)
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • 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
    • Guide to Programming with Python Chapter Two Types, Variables, and Simple I/O: The Useless Trivia Program
    • 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
    • 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
    • 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
    • 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
    • Using Quotes
      • Using quotes inside strings
        • Define with either single ( ' ) or double quotes ( &quot; )
          • 'Game Over' or &quot;Game Over&quot;
        • Define with one type, use other type in string
          • &quot;Program 'Game Over' 2.0&quot;
      • Triple-quoted strings can span multiple lines
        • &quot;&quot;&quot;
        • I am a
        • triple-quoted string
        • &quot;&quot;&quot;
      • Line-continuation character
      Guide to Programming with Python
    • 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.
        • Simple to use
      Guide to Programming with Python
    • 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
    • Escape Sequences
      • System bell
        • print &quot;a&quot;
      • Tab
        • print &quot; Fancy Credits&quot;
      • Backslash
        • print &quot; amp;quot;
      • Newline
        • print &quot; Special thanks goes out to:&quot;
      • Quote
        • print &quot;My hair stylist, Henry 'The Great', who never says &quot;can't&quot;.&quot;
      Guide to Programming with Python
    • Escape Sequences (continued)
      • Table 2.1: Selected escape sequences
      Guide to Programming with Python
    • Concatenating and Repeating Strings
      • Can combine two separate strings into larger one
      • Can repeat a single string multiple times
      Guide to Programming with Python
    • 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
    • Concatenating Strings
      • String concatenation : Joining together of two strings to form a new string
      • When used with string operands , + is the string concatenation operator
        • &quot;concat&quot; + &quot;enate&quot;
      • Suppressing a Newline
        • When used at the end of print statement, comma suppresses newline
        • print &quot;No newline after this string&quot;,
      Guide to Programming with Python
    • 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
        • &quot;Pie&quot; * 10 creates new string &quot;PiePiePiePiePiePiePiePiePiePie&quot;
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • 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
    • Mathematical Operators (continued)
      • Table 2.2: Mathematical operators with integers
      Guide to Programming with Python
    • Mathematical Operators (continued)
      • Table 2.3: Mathematical operators with floats
      Guide to Programming with Python
    • 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
    • The Greeter Program
      • Figure 2.6: Sample run of the Greeter program
      • Using a variable for the name
      Guide to Programming with Python
    • Creating Variables
      • Assignment statement : Assigns a value to a variable; creates variable if necessary
      • name = &quot;Larry&quot;
        • Stores string &quot;Larry&quot; in computer memory
        • Creates variable name
        • Assigns value so that name refers to &quot;Larry&quot;
      Guide to Programming with Python
    • Using Variables
      • Use variable where you want value it represents
      • print name or print &quot;Larry&quot;
      • Both display Larry
      • print &quot;Hi, &quot; + name or print &quot;Hi, Larry&quot;
      • Both display Hi, Larry
      Guide to Programming with Python
    • 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
    • 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
    • Getting User Input
      • Variables important for
        • Getting user input
        • Storing user input
        • Manipulating user input
      Guide to Programming with Python
    • 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
    • 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
    • Getting User Input (continued)
      • raw_input() function
        • Prompts the user for text input
        • Returns what the user entered as a string
      • name = raw_input(&quot;Hi. What's your name? &quot;)
        • Uses argument &quot;Hi. What's your name? &quot; to prompt user
        • Returns what user entered as a string
        • In assignment statement, name gets returned string
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • String Methods (continued)
      • quote = &quot;I think there is a world market for maybe five computers.&quot;
        • 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(&quot;five&quot;, &quot;millions of&quot;)
        • 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.
      Guide to Programming with Python
    • String Methods (continued)
      • Table 2.4: Useful string methods
      Guide to Programming with Python
    • 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
    • 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
    • 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
    • Logical Errors (continued)
      • car = raw_input(&quot;Lamborghini Tune-Ups: &quot;)
      • rent = raw_input(&quot;Manhattan Apartment: &quot;)
      • jet = raw_input(&quot;Private Jet Rental: &quot;)
      • gifts = raw_input(&quot;Gifts: &quot;)
      • food = raw_input(&quot;Dining Out: &quot;)
      • staff = raw_input(&quot;Staff (butlers, chef, driver, assistant): &quot;)
      • guru = raw_input(&quot;Personal Guru and Coach: &quot;)
      • games = raw_input(&quot;Computer Games: &quot;)
      • 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
    • 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
    • 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
    • Converting Types
      • int() function converts a value to an integer
        • car = raw_input(&quot;Lamborghini Tune-Ups: &quot;)
        • car = int(car)
      • Can nest multiple function calls
        • rent = int(raw_input(&quot;Manhattan Apartment: &quot;))
      Guide to Programming with Python
    • Converting Types (continued)
      • Table 2.5: Selected type conversion functions
      Guide to Programming with Python
    • 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
    • Augmented Assignment Operators (continued)
      • Table 2.6: Useful augmented assignment operators
      Guide to Programming with Python
    • Printing Multiple Values
      • To print multiple values in single print statement, separate values by commas
        • print &quot; Grand Total: &quot;, total
      Guide to Programming with Python
    • 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
    • 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
    • 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
      Guide to Programming with Python