1 / 20

Python Programming - Goals

Python Programming - Goals. By the end of this unit, you will be able to: Understand the difference between interactive and script mode in IDLE Understand variables, subroutines, loops and branches, strings, and lists in Python Get input from the user and display output Draw simple graphics

duane
Télécharger la présentation

Python Programming - Goals

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. Python Programming - Goals By the end of this unit, you will be able to: • Understand the difference between interactive and script mode in IDLE • Understand variables, subroutines, loops and branches, strings, and lists in Python • Get input from the user and display output • Draw simple graphics • Understand the importance of proper software documentation and testing

  2. Interactive and Script Modes in IDLE • IDLE is the Python programming environment we will use in this class • IDLE has two modes: interactive (called shell in "The Way of the Program") and script • In interactive mode, you type a command and it is executed right away. • In script mode, you write a set of commands into a file (called a Python script, ending in .py) and then execute the script:

  3. Two ways to run IDLE • There are two shortcuts on your desktop, one for IDLE, the other "IDLE for graphics". IDLE for graphics starts IDLE in a special mode that is required for the Livewires graphics package that we use. when you start IDLE, it looks like this: when you start "IDLE for graphics", it looks like this: (If your graphics program doesn't work, this could be the reason!)

  4. Variables in Python Programs use variables when they need to ”remember” some information. A variable allows you to give a name to a piece of information stored in a computer. You can then read the value, or set it to something different in another part of your program. myName = "Mr. Judkis" # set the value print myName # get the value myAge = 22 # set the value myAge = myAge + 1 # get it and set it You cannot get a value before it has been set! Python will complain: >>> foo = foo + 1 NameError: name 'foo' is not defined

  5. Rules and Guidelines for Variables Rules for naming variables: • Variables can contain only letters, numbers, and underscores • Variables cannot begin with numbers • Variables cannot be any of the Python reserved words (listed below) Guidelines for naming variables: • Names should be descriptive – score instead of s (except for variables that are used only briefly) • Variable names should be consistent within the program: high_score and low_score or highScore and lowScore • Variable names shouldn’t start with underscores or uppercase letters • Variable names shouldn’t be too long - generally no longer than 15 chars

  6. and assert break class continue def del elif else except exec finally if in lambda not or pass Reserved Words in Pythonthe following words are all special: • print • raise • return • try • while • yield Do the following variable names obey the rules? The guidelines? • blah • x • routeLength • first-name • lambda • last_name • 24_hour_count • twentyFourHourCountValue • _height • Width • while • length

  7. Integers, Floats, and Strings • An int is an integer number. my_int = 7 • A float (floating point) is a number that includes some fractional part, using a decimal point. my_float = 3.1415926 • You can do arithmetic with integers and floats, and you can combine them: >>> print my_int + my_float 10.1415926 • A string is a sequence of ASCII characters. You can’t do arithemetic on a string. my_str = "howdy" • You can convert some strings to integers or floats: my_str = "3213" my_int = int(my_str) • You can convert any integer or float to a string: my_int = 3213 my_str = str(my_int) • Adding integers and/or floats does the arithmetic, but adding strings concatenates them (sticks them together): >>> print my_str + " pardner" howdy pardner

  8. Integers, Floats, and Strings - 2 • If you try to convert a string into an int or float and there’s a problem, Python will let you know: • >>> int("hi there") • Traceback (most recent call last): • File "<pyshell#2>", line 1, in -toplevel- • int("hi there") • ValueError: invalid literal for int(): hi there • If you try to combine numbers and strings in some way that doesn’t make sense, Python will let you know: • >>> print "hi there" + 7 • Traceback (most recent call last): • File "<pyshell#4>", line 1, in ? • print "hi there" + 7 • TypeError: cannot concatenate 'str' and 'int' objects • Why is this okay?: • >>> print "hi there" + str(7) • hi there7 • Okay, now you try it. . .

  9. Getting input from the user: raw_input() string_val = raw_input("prompt",) raw_input() always gives you what the user entered as a string. If you want to get an integer or floating point number, it’s up to you to do the conversion: int_val = int(raw_input("enter integer:",)) – or – int_val = raw_input("enter integer:",) int_val = int(int_val) float_val = float(raw_input("enter float:",)) – or – float_val = raw_input("enter float:",) float_val = float(float_val)

  10. Giving output: the print statement Separate values to be printed by commas: print "The values are", min, "and", max,"." Python will insert spaces between each value, and print: The values are 6 and 10 . Or, you can concatenate values to create your own string, controlling the spacing yourself: print "The values are " + str(min) + " and " + str(max) + "." Python will print: The values are 6 and 10. In script mode, a comma at the end of the print statement will keep the next output on the same line:

  11. Comments • Your python scripts should always start off with the program name, a brief description of what it does, your name, and the date. Like this: # guess_num.py # Picks a random number, then asks the user # to guess it # Ima Programmer 12/23/05 • Also include comments whenever the code may not be easy to understand, like this: # use the pythagorean formula to calculate # the distance between the points distance = math.sqrt((x1 –x2)**2 + (y1-y2)**2)

  12. Program File Structure # program file name # brief description of what it does # your name, date created Then import statements Then all subroutine definitions Finally, the "main line" of the code put a blank line between each subroutine, and between each section. put additional blank lines anywhere they improve readability

  13. Assignment and Equality A single equal sign=means assignment: The value on the right is assigned to the variable on the left: counter = 88 numTries = numTries + 1 Double equal ==tests for equality: the expression is True if the values on either side are equal: if yourName == "Mr. Judkis": print "So handsome!" else: print "meh" counter = 10 while counter > 0: print counter counter = counter – 1 print "Blast off!"

  14. Example if yourIQ > 120: print "perfect for AAHS!" elif yourIQ >= 100: print "perfect for MAST" elif yourIQ >= 80: print "maybe CHS" else: print "definitely HTHS. . . sorry"

  15. Combining logical tests Testing for several different conditions: resp = raw_input("Do you want to quit?") if resp == "Yes" or resp == "yes": print "Bye!" Don't do this: resp = raw_input("Do you want to quit?") if resp == "Yes" or "yes": print "Bye!" It won't do what you want it to do!

  16. Arithmetic

  17. for loop We saw this in RUR-PLE – a loop that runs the indented block of code a set number of times. for count in range(500): print "I will not be late to class" This is also sometimes known as a counting loop. Compare this to the while loop. . .

  18. while loop number = 1 while number < 1000: print number, number *= 2 1 2 4 8 16 32 64 128 256 512 The following program makes you guess a password: guess = "" while guess != "Fizzing Whizbee": guess = raw_input("what is the password?“, ) print "You may enter." The while is a conditional loop – it runs until some condition is not true

  19. Guessing Game, Take 1: import random print "I'm thinking of a number between 1 and 20." numToGuess = random.randint(1,20) userGuess = int(raw_input("Give a guess:")) while userGuess != numToGuess: print "Nope, try again" userGuess = int(raw_input("Give a guess:")) print "You got it!"

  20. break The break statement immediately pops you out of the for or while loop your program is in, regardless of how many times you’ve run through it, or whether the loop condition is true or false. Think of it as a jailbreak. . . import random print "I'm thinking of a number between 1 and 20." numToGuess = random.randint(1,20) while True: userGuess = int(raw_input("Give a guess:")) if userGuess == numToGuess: print "You got it!" break else: print "Nope, try again" Guessing Game, Take 2:

More Related