1 / 86

Guide to Programming with Python

Guide to Programming with Python. 2. Objectives. Introduce PythonDemonstrate how to install Python Explain how to print text to the screenDescribe comments and how to use themDemonstrate Python's development environment, IDLE, using it to write, edit, run, and save programsCourse mechanics. Guide to Programming with Python.

caden
Download Presentation

Guide to Programming with Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

    2. 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 Course mechanics

    3. Guide to Programming with Python 3 Examining the Game Over Program Figure 1.1: Game Over Program Output The all-too familiar words from a computer game

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

    5. Where we’ll 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?

    6. Programming! Getting your computer to do stuff…. By being very specific—like 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 don’t ever program again, you’ll learn valuable skills for tackling problems by breaking them down into smaller problems and thinking logically

    7. Guide to Programming with Python 7 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

    8. Monty Python Demonstrates Why Programming Computers is Hard… Guide to Programming with Python 8

    9. Guide to Programming with Python 9 Why Python? It’s 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 they’re the right tools for the job

    10. Guide to Programming with Python 10 Python Is Easy to Use (continued) Python Program print "Game Over!" C++ Program #include <iostream> int main() { std::cout << "Game Over!" << std::endl; return 0; }

    11. Guide to Programming with Python 11 Python Is Powerful Used by large organizations NASA Google Microsoft Used in published games Battlefield 2 Civilization IV Disney’s Toontown Online Used throughout academia and the scientific community

    12. Guide to Programming with Python 12 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#

    13. Guide to Programming with Python 13 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

    14. Guide to Programming with Python 14 Python Runs Everywhere Platform independent: Independent of the specific computer operating system Python runs on Windows DOS Mac OS X Linux Many more

    15. Guide to Programming with Python 15 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"

    16. Guide to Programming with Python 16 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

    17. Python is Popular All those advantages make Python a commonly used (and liked) language (http://www.langpop.com/):

    18. Guide to Programming with Python 18 Installing Python Do NOT install anything from the textbook’s CD-ROM Instead, follow the instructions on the class web page Don’t 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

    19. Guide to Programming with Python 19 Installing Python (continued) 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 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/download/

    20. Guide to Programming with Python 20 Introducing 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

    21. Guide to Programming with Python 21 Programming in Interactive Mode

    22. Guide to Programming with Python 22 Programming 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 <version>, IDLE (Python GUI) Mac: Launch /Applications/Enthought/IDLE.app On STC Lab machines Windows: Will be in Start menu > All Programs > Departmentally Sponsored > Informatics > 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

    23. Guide to Programming with Python 23 Programming in Interactive Mode (continued) At command prompt (>>>), type: print "Game Over" Python responds with: Game Over

    24. Guide to Programming with Python 24 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

    25. Guide to Programming with Python 25 Programming 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. Guide to Programming with Python 26

    27. Guide to Programming with Python 27 Programming in Script Mode

    28. Guide to Programming with Python 28 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

    29. Guide to Programming with Python 29 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

    30. Guide to Programming with Python 30 Programming in Script Mode (continued) Figure 1.6: Python after a script has been run The results of running the Game Over program

    31. Guide to Programming with Python 31 The Game Over Program # Game Over # Demonstrates the print command print "Game Over" raw_input("\n\nPress the enter key to exit.")

    32. Guide to Programming with Python 32 The 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 you’re ready to end it

    33. Guide to Programming with Python 33 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

    34. Guide to Programming with Python 34 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

    35. Guide to Programming with Python 35 Summary (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 program’s purpose 

    36. Summary (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 Guide to Programming with Python 36

    37. Summary (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) Guide to Programming with Python 37

    38. Summary (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 code—we’ll 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! Guide to Programming with Python 38

    39. Guide to Programming with Python Chapter Two Types, Variables, and Simple I/O: The Useless Trivia Program

    40. Guide to Programming with Python 40 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

    41. Guide to Programming with Python 41 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.

    42. Guide to Programming with Python 42 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

    43. Guide to Programming with Python 43 The Game Over 2.0 Program Figure 2.2: Sample run of the Game Over 2.0 program Ah, the game is really over.

    44. Guide to Programming with Python 44 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 \

    45. Guide to Programming with Python 45 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

    46. Guide to Programming with Python 46 The Fancy Credits Program Figure 2.3: Sample run of the Fancy Credits program So many people to thank, so many escape sequences

    47. Guide to Programming with Python 47 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\"."

    48. Guide to Programming with Python 48 Escape Sequences (continued) Table 2.1: Selected escape sequences

    49. Guide to Programming with Python 49 Concatenating and Repeating Strings Can combine two separate strings into larger one Can repeat a single string multiple times

    50. Guide to Programming with Python 50 The Silly Strings Program Figure 2.4: Sample run of the Silly Strings program Strings appear differently than in the program code.

    51. Guide to Programming with Python 51 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",

    52. Guide to Programming with Python 52 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"

    53. Guide to Programming with Python 53 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

    54. Guide to Programming with Python 54 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.

    55. Guide to Programming with Python 55 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

    56. Guide to Programming with Python 56 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

    57. Guide to Programming with Python 57 Mathematical Operators (continued) Table 2.2: Mathematical operators with integers

    58. Guide to Programming with Python 58 Mathematical Operators (continued) Table 2.3: Mathematical operators with floats

    59. Guide to Programming with Python 59 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

    60. Guide to Programming with Python 60 The Greeter Program Figure 2.6: Sample run of the Greeter program Using a variable for the name

    61. Guide to Programming with Python 61 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"

    62. Guide to Programming with Python 62 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

    63. Guide to Programming with Python 63 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

    64. Guide to Programming with Python 64 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

    65. Guide to Programming with Python 65 Getting User Input Variables important for Getting user input Storing user input Manipulating user input

    66. Guide to Programming with Python 66 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.

    67. Guide to Programming with Python 67 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)

    68. Guide to Programming with Python 68 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

    69. Guide to Programming with Python 69 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

    70. Guide to Programming with Python 70 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.

    71. Guide to Programming with Python 71 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

    72. Guide to Programming with Python 72 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.

    73. Guide to Programming with Python 73 String Methods (continued) Table 2.4: Useful string methods

    74. Guide to Programming with Python 74 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

    75. Guide to Programming with Python 75 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.

    76. Guide to Programming with Python 76 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

    77. Guide to Programming with Python 77 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

    78. Guide to Programming with Python 78 Converting Values Can convert one type of value to another Use built-in functions Solution to Trust Fund Buddy–Bad program

    79. Guide to Programming with Python 79 The Trust Fund Buddy–Good Program Figure 2.10: Sample run of the Trust Fund Buddy-Good program Now the total is right.

    80. Guide to Programming with Python 80 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: "))

    81. Guide to Programming with Python 81 Converting Types (continued) Table 2.5: Selected type conversion functions

    82. Guide to Programming with Python 82 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

    83. Guide to Programming with Python 83 Augmented Assignment Operators (continued) Table 2.6: Useful augmented assignment operators

    84. Guide to Programming with Python 84 Printing Multiple Values To print multiple values in single print statement, separate values by commas print "\nGrand Total: ", total

    85. Guide to Programming with Python 85 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

    86. Guide to Programming with Python 86 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

    87. Guide to Programming with Python 87 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

More Related