1 / 139

>>> Python Basics

>>> Python Basics. Interpreted Not compiled like Java This means: type commands and see results Targeted towards short to medium sized projects Useful as a scripting language. A whaa?. script – short program meant for one-time use. Code. Compiler. Runtime Env. Computer. Code.

Download Presentation

>>> Python Basics

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 Basics • Interpreted • Not compiled like Java • This means: type commands and see results • Targeted towards short to medium sized projects • Useful as a scripting language A whaa? script – short program meant for one-time use. Code Compiler Runtime Env Computer Code Interpreter Computer

  2. >>> Getting it Going Windows Mac OSX Linux 1) Download Python from python.org. 2) Run 'python' using the run command. -or- Run Idle from the Start Menu. 1) Python is already installed. 2) Open a terminal and run python or run Idle from finder. 1) Chances are you already have Python installed. To check run python from the terminal. 2) If not, install python through your distribution's package system. Note: For step by step installation instructions, follow those provided on the course web site. Click on Python on the right hand side and follow the “Python Installation Instructions”

  3. Hello.java public class Hello { public static void main(String[] args){ System.out.println("Hello world!"); } } 1 2 3 4 5 Hello.java public class Hello { public static void main(String[] args){ hello(); } public static void hello(){ System.out.println("Hello world!"); } } 1 2 3 4 5 6 7 8 >>> Topic Review * printing - System.out.println(); * methods – public static void <name>() ...

  4. >>> Missing Main Hello.java public class Hello { public static void main(String[] args){ System.out.println("Hello world!"); } } 1 2 3 4 5 The entire file is interpreted as if it was typed into the interpreter. This makes it easy to write scripts with Python. hello.py print "Hello world!" 1 2 3 4 5

  5. hello.py print "Hello world!" print print "Suppose two swallows carry it together." 1 2 3 4 >>> Printing Hello.java public class Hello { public static void main(String[] args){ System.out.println("Hello world!"); System.out.println(); System.out.println("Suppose two swallows carry it together."); } } 1 2 3 4 5 6 7 8 Escape sequences: * \t – tab * \n – new line * \" - " * \\ - \

  6. hello.py def hello(): print "Hello \"world\"!" #main hello()‏ 1 2 3 4 5 >>> Methods Hello.java • Structure: • def <method name>(): • <statement> • <statement> • <statement> • ... • <statement> public class Hello { public static void main(String[] args){ hello(); } public static void hello(){ System.out.println("Hello \"world\"!"); } } 1 2 3 4 5 6 7 8 Note: Python does not have a main method. However, methods must be defined first. Calls to methods can then be made. This is similar to having a “main” section of code. It is good practice to label this section of code with a comment.

  7. >>> Whitespace Unlike in Java, in Python whitespace (think tabs and spaces) matters. Instead of using braces ({}) to designate code blocks, Python uses the indentation. This was done to promote readable code. In Java you may or may not indent and it will work. In Python you must indent. Hello.java public class Hello { public static void main(String[] args){ System.out.println(“Hello \"world\"!”); } } 1 2 3 4 5 hello.py def hello(): print "Hello \"world\"!" hello()‏ 1 2 3 4

  8. >>> Example 1 Example: Write a method that produces the following output. We are the Knights Who Say... "Nee!" (Nee! Nee! Nee!) NO! Not the Knights Who Say "Nee"... We are the Knights Who Say... "Nee!" (Nee! Nee! Nee!)

  9. >>> Example 1 Solution: def knights(): print "We are the Knights Who Say... \"Nee!\"" print "(Nee! Nee! Nee!)" print def poorSouls(): print "NO!\t Not the Knights Who Say \"Nee\"..." print knights() poorSouls() knights()

  10. >>> Example 2 Example: Write a method that produces the following output. ______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

  11. >>> Example 2 Example: Write a method that produces the following output. def egg(): top() bottom() print def cup(): bottom() line() print def stop(): top() print "| STOP |" bottom() print def hat(): top() line() print def top(): print " ______" print " / \\" print "/ \\" def bottom(): print "\\ /" print " \\______/" def line(): print "+--------+" egg() cup() stop() hat() ______ / \ / \ \ / \______/ \ / \______/ +--------+ ______ / \ / \ | STOP | \ / \______/ ______ / \ / \ +--------+

  12. >>>Types Python cares very little about types. In Java, one must declare a variable with a particular type and maintain that type throughout the existence of that variable. In other words, ints can be only stored in places designated for ints, same for doubles etc. This is not the case in Python. Python does not care about types until the very last moment. This last moment is when values are used in certain ways, such as concatenation of strings. Java python int double String char boolean 178 175.0 “wow” 'w' True int float str str bool

  13. >>>String concatenation Like Java, we can concatenate strings using a “+”. Unlike Java, when a number has to be concatenated with a string in python, you need to explicitly perform the conversion to a string using the str() function because it hasn’t made sure that the types match before run time. >>> "Suppose " + 2 + " swallows carry it together." Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> "Suppose " + str(2) + " swallows carry it together." 'Suppose 2 swallows carry it together.'

  14. >>>Python expressions • Python is very similar to Java in the way that it handles expressions such as: • + - * / % • Integer division – rounds down to nearest int • Precedence – same rules • Mixing types – numbers change to keep precision • Real numbers are kept as “floats” or floating point numbers

  15. >>>Differences in expressions There are a few things that differ between Python and Java, such as: You can multiply strings in python! There are no increment operators in python (++, --)‏ so we have to use -= and += >>> "Hello!"*3 'Hello!Hello!Hello!' >>> x = 1 >>> x += 1 >>> print x 2

  16. >>>Variables As we said earlier, Python cares less about types. When we create a variable in Python, the type of the variable doesn’t matter. As a result, in Python, creating a variable has the same syntax as setting a value to a variable. expressions.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 x = 2 x += 1 print( x) x = x * 8 print (x) d = 3.0 d /= 2 print (d) s = "wow" print (s) Variables.java 1 2 3 4 5 6 7 8 9 10 11 ... int x = 2; x++; System.out.println(x); x = x * 8; System.out.println(x); double d = 3.0; d /= 2; System.out.println(d);

  17. >>>Constants • Continuing Python's free spirited ways, it has much less restrictions than Java. Because of this, constants are possible but not in a commonly used manner. Instead, we'll designate constants in Python solely by the variable capitalization. • We do need to write the constants at the top of our program so that every function can see them! • Fixed values such as numbers, letters, and strings are called “constants” - because their value does not change • Numeric constants are as you expect • String constants use single-quotes (')or double-quotes (") constants.py 1 2 3 4 5 6 SIZE = 2 x = 10 * SIZE print x # main … >>> print 123 123 >>> print 98.6 98.6 >>>print'Hello world' Hello world

  18. Variables • A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name” • Programmers get to choose the names of the variables • You can change the contents of a variablein a later statement 12.2 x = 12.2 y = 14 100 x 14 x = 100 y

  19. Python Variable Name Rules • Must start with a letter or underscore _ • Must consist of letters and numbers and underscores • Case Sensitive • Good: spam eggs spam23 _speed • Bad: 23spam #sign var.12 • Different: spam Spam SPAM

  20. Reserved Words • Youcan not usereserved words as variable names / identifiers and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print

  21. Sentences or Lines x= 2 x=x+ 2 printx Assignment Statement Assignment with expression Print statement Constant Reserved Word Variable Operator

  22. Assignment Statements • We assign a value to a variable using the assignment statement (=) • An assignment statement consists of an expression on the right hand side and a variable to store the result x = 3.9 * x * ( 1 - x )

  23. 0.6 x A variable is a memory location used to store a value (0.6). 0.6 0.6 x =3.9 * x * ( 1 - x ) 0.4 Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) x. 0.93

  24. A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93). 0.6 0.93 x x =3.9 * x * ( 1 - x ) Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e. x). 0.93

  25. Numeric Expressions • Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations • Asterisk is multiplication • Exponentiation (raise to a power) looks different from in math.

  26. Numeric Expressions >>> xx = 2 >>> xx = xx + 2 >>> print xx 4 >>> yy = 440 * 12 >>> print yy 5280 >>> zz = yy / 1000 >>> print zz 5 >>> jj = 23 >>> kk = jj % 5 >>> print kk 3 >>> print 4 ** 3 64 4 R 3 5 23 20 3

  27. Order of Evaluation • When we string operators together - Python must know which one to do first • This is called “operator precedence” • Which operator “takes precedence” over the others x = 1 + 2 * 3 - 4 / 5 ** 6

  28. Parenthesis Power Multiplication Addition Left to Right Operator Precedence Rules • Highest precedence rule to lowest precedence rule • Parenthesis are always respected • Exponentiation (raise to a power) • Multiplication, Division, and Remainder • Addition and Subtraction • Left to right

  29. Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11

  30. Parenthesis Power Multiplication Addition Left to Right Note 8/4 goes before 4*5 because of the left-right rule. 1 + 8 / 4 * 5 1 + 2 ** 3 / 4 * 5 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> 1 + 2 * 5 1 + 10 11

  31. Parenthesis Power Multiplication Addition Left to Right Operator Precedence • Remember the rules top to bottom • When writing code - use parenthesis • When writing code - keep mathematical expressions simple enough that they are easy to understand • Break long series of mathematical operations up to make them more clear Exam Question: x = 1 + 2 * 3 - 4 / 5

  32. Python Integer Division is Weird! • Integer division truncates • Floating point division produces floating point numbers >>> print 10 / 2 5 >>> print 9 / 2 4 >>> print 99 / 100 0 >>> print 10.0 / 2.0 5.0 >>> print 99.0 / 100.0 0.99 This changes in Python 3.0

  33. Mixing Integer and Floating • When you perform an operation where one operand is an integer and the other operand is a floating point the result is a floating point • The integer is converted to a floating point before the operation >>> print 99 / 100 0 >>> print 99/ 100.0 0.99 >>> print 99.0 / 100 0.99 >>> print 1 + 2 * 3 / 4.0 - 5 -2.5 >>>

  34. What does “Type” Mean? • In Python variables, literals, and constants have a “type” • Python knows the difference between an integer number and a string • For example “+” means “addition” if something is a number and “concatenate” if something is a string >>> ddd = 1 + 4 >>> print ddd 5 >>> eee = 'hello ' + 'there' >>> print eee hello there concatenate = put together

  35. Type Matters >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> type(eee) <type 'str'> >>> type('hello') <type 'str'> >>> type(1) <type 'int'> >>> • Python knows what “type”everything is • Some operations are prohibited • You cannot “add 1” to a string • We can ask Python what type something is by using the type() function.

  36. Several Types of Numbers • Numbers have two main types • Integers are whole numbers: -14, -2, 0, 1, 100, 401233 • Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0 • There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) <type 'int'> >>> temp = 98.6 >>> type(temp) <type 'float'> >>> type(1) <type 'int'> >>> type(1.0) <type 'float'> >>>

  37. Type Conversions • When you put an integer and floating point in an expression the integer is implicitly converted to a float • You can control this with the built in functions int() and float() >>> printfloat(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 *float(3) / 4 - 5 -2.5 >>>

  38. String Conversions >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <type 'int'> >>> print ival + 1 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters

  39. User Input • We can instruct Python to pause and read data from the user using the raw_input function • The raw_input function returns a string nam = raw_input(‘Who are you?’) print 'Welcome', nam Who are you? Chuck Welcome Chuck

  40. Converting User Input • If we want to read a number from the user, we must convert it from a string to a number using a type conversion function • Later we will deal with bad input data inp = raw_input(‘Europe floor?’) usf = int(inp) + 1 print 'US floor', usf Europe floor? 0 US floor 1

  41. Comments in Python • Anything after a # is ignored by Python • Why comment? • Describe what is going to happen in a sequence of code • Document who wrote the code or other ancillary information • Turn off a line of code - perhaps temporarily

  42. # Get the name of the file and open it name = raw_input('Enter file:') handle = open(name, 'r') text = handle.read() words = text.split() # Count word frequency counts = dict() for word in words: counts[word] = counts.get(word,0) + 1 # Find the most common word bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # All done print bigword, bigcount

  43. String Operations • Some operators apply to strings • + implies “concatenation” • * implies “multiple concatenation” • Python knows when it is dealing with a string or a number and behaves appropriately >>> print 'abc' + '123’ Abc123 >>> print 'Hi' * 5 HiHiHiHiHi >>>

  44. Mnemonic Variable Names • Since we programmers are given a choice in how we choose our variable names, there is a bit of “best practice” • We name variables to help us remember what we intend to store in them (“mnemonic” = “memory aid”) • This can confuse beginning students because well named variables often “sound” so good that they must be keywords http://en.wikipedia.org/wiki/Mnemonic

  45. x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd a = 35.0 b = 12.50 c = a * b print c hours = 35.0 rate = 12.50 pay = hours * rate print pay What is this code doing?

  46. Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25

  47. Summary • Type • Resrved words • Variables (mnemonic) • Operators • Operator precedence • Integer Division • Conversion between types • User input • Comments (#)

  48. Repeated Steps n = 5 No Yes n > 0 ? Program: n = 5 while n > 0 : print n n = n – 1 print 'Blastoff!' print n Output: 5 4 3 2 1 Blastoff! 0 print n n = n -1 print 'Blastoff' Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.

  49. An Infinite Loop n = 5 No Yes n > 0 ? n = 5 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' print 'Lather' print 'Rinse' print 'Dry off!' What is wrong with this loop?

More Related