1 / 32

Python

Python. Crash Course by Monica Sweat. Python Perspective. is strongly typed, interpreted language is used to define scripts (Don't even need to define a function proper.) is used to define functions can be used in object-oriented style is an up and coming real language in industry.

artan
Download Presentation

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. Python Crash Course by Monica Sweat

  2. Python Perspective • is strongly typed, interpreted language • is used to define scripts(Don't even need to define a function proper.) • is used to define functions • can be used in object-oriented style • is an up and coming real language in industry

  3. Integrated Development Environment: IDLE • IDLE is provided with standard python installation • available for virtually any platform • provides an editing window • provides an interactive interpreter window

  4. Starting Simply can use IDLE / python as a calculator>>> 3 + 412>>> 4 ** 216>>> 6 / 23>>> 1 / 20  gotcha that begs anintroduction to types

  5. Common Types • sampling of types • int signed integer, 32 bits, ±2,147,483,647 • long arbitrarily long ends with L • float 64 bit double precision, like 1.23 or 7.8e-28 • str delimit in ' or " • bool Booleans True and False • type(x)yields the type of the data stored currently in variable x

  6. str Type • str is the type for strings in python • they can be single quote or double quote delimitedword = "can't" • multiline strings can be triple quoted (that's 3 single quotes or 3 double quotes in a row)poem = """Roses are red,violets are blue."""

  7. Comments (relates to strings) • comments in python are single line and use the # symbol# This program written by George Burdell • multiline comments can be faked by using the triple quoted string trick"""This program written by Monica SweatJuly 8, 2008"""

  8. Math Operations • () parens for grouping • + - unary plus, minus • ** exponentiation • * / % mult-style ops • + - add, subtract

  9. Simple Demo of Variables >>> age = 18 >>> print age 18 >>> age = age + 1 >>> print age 19

  10. Python Variables • Python is case-sensitive • variable names • function names • everything • Camel case is a common style in python, java, etc. firstName = 'George' lastName = 'Burdell' print firstName, lastName word = "don't"

  11. Python Variables • [a-zA-Z][a-zA-Z0-9 _]* • start with letter followed by letters and digits • any length • case matters • do not have to be declared! • python is strongly typed, but the "type" is bound to the data and not the variable

  12. Script Example Complete script using variables Assignment statement uses = hours = 35 rate = 25.50 pay = hours * rate print pay

  13. Printing Results Increasingly better ways to print pay hours = 35 rate = 25.50 pay = hours * rate print pay or print "Your pay is", pay or print "Your pay is $" + str(pay) or print "Your pay is $%.2f" % pay

  14. Easy User Input Use input for console input of a numeric value hours = input("How many hours? ") rate = input("Pay rate? ") pay = hours * rate print "Your pay is $%.2f" % pay

  15. Getting Input from the User • numeric inputage = input("Age? ") • string inputname = raw_input("Name? ")

  16. Type Conversion • x = int(3.9) • y = float(5) • print "Answer: " + str(2 * 3)(Useful if concatenating with a string) • age = int(raw_input("Age? "))(Useful if using raw_input to get all input from the user.) • average = float(sum)/float(total)(Forces float division)

  17. Conditionals • if • if/else • if/elif/elif/elif/…/else • all branches use colon : • all bodies are indentedPython uses indentation to denote blocks.

  18. Building Conditions • relational operators as expected<, >, <=, >=, ==, !=, <>(assignment uses single equals sign) • logical operators are lowercasenot, and, or(! can be used for not) • parentheses not necessary unless overriding precedence

  19. Conditionals age = input("Age? ") if age <= 12: ticketPrice = 5 elif age >= 65: ticketPrice = 7.5 else: ticketPrice = 9 print ticketPrice

  20. Defining a Function def rectangleArea(length, width): area = length * width return area

  21. Using Modules import math def circleArea(radius): area = math.pi * radius ** 2 return area http://docs.python.org/modindex.html math, random, re, os, …

  22. Importing Modules import math print math.pi x = math.sqrt(9) vs. from math import pi, sqrt print pi x = sqrt(9)

  23. Python Sequences (arrays) • python's answer to the array • is dynamic • behaves like a linked listed with indexing names = ["Fred", "Wilma"] names[0] = "Barney" print names[0]

  24. Python Sequences (arrays) common operations (there are many) names = names + ["Dino"] or names.append("Bambam")

  25. for Loop for-each style iterates through a sequence syntax: for item in sequence: block-of-code for flavor in ["chocolate", "vanilla"]: print "I like", flavor

  26. for Loop def average(array): sum = 0 count = 0 for num in array: sum = sum + num count = count + 1 return float(sum)/count

  27. Counting-style for Loop for loop with counting style using range: for num in range(1, 5): print num Output: 1 2 3 4

  28. Processing Array without/with range for-each style to iterate through a sequence: for flavor in ["chocolate", "vanilla"]: print "I like", flavor vs. index-driven style processing a sequence: flavors = ["chocolate", "vanilla", "mint"] for index in range(len(flavors)): print "I like", flavors[index]

  29. range Function Details • most commonly used to generate indices for iterating a sequence • may have 1, 2, or 3 parameters • stopping value is exclusive >>> range(5)(starts at 0 if one parameter) [0, 1, 2, 3, 4] >>> range(1995, 2000)(stopping value exclusive) [1995, 1996, 1997, 1998, 1999] >>> range(0, 55, 5) (3rd parameter is step value) [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

  30. range Function to Generate Data def summation(n): total = 0 for num in range(n + 1): total = total + num return total

  31. while Loop number = 1 while number <= 5: print number number += 1

  32. myro – Major Bonuses • myro defined as a proper module • programmer imports it as they would any module • natural way to incorporate added functionality • works with standard python • all of standard python is available to the user • other modules: math, random, os, etc are still available • materials for python still apply

More Related