Presentation is loading. Please wait.

Presentation is loading. Please wait.

1.

Similar presentations


Presentation on theme: "1."— Presentation transcript:

1 1

2 >>> 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

3 >>> 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

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

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

6 >>> Printing
Hello.java 1 2 3 4 5 6 7 8 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."); } Escape sequences: * \t – tab * \n – new line * \" - " * \\ - \ print "Hello world!" print print "Suppose two swallows carry it together." hello.py 1 2 3 4 6

7 >>> Methods Hello.java Structure: def <method name>(): <statement> ... 1 2 3 4 5 6 7 8 public class Hello { public static void main(String[] args){ hello(); } public static void hello(){ System.out.println("Hello \"world\"!"); 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. def hello(): print "Hello \"world\"!" #main hello()‏ hello.py 1 2 3 4 5 7

8 >>> 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 1 2 3 4 5 public class Hello { public static void main(String[] args){ System.out.println(“Hello \"world\"!”); } hello.py 1 2 3 4 def hello(): print "Hello \"world\"!" hello()‏ 8

9 >>> 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"... 9

10 >>> 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\"..." knights() poorSouls() 10

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

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

13 >>> 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 178 175.0 “wow” 'w' True int double String char boolean int float str bool 13

14 >>> 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 " " 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

15 >>> 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

16 >>> 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

17 >>> 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; double d = 3.0; d /= 2; System.out.println(d); 17

18 >>> 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

19 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 variable in a later statement 12.2 x = 12.2 y = 14 x 100 x = 100 14 y

20 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: spam #sign var.12 Different: spam Spam SPAM

21 Reserved Words and del for is raise assert elif from lambda return
You can not use reserved 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 Like a dog .... food ... food ...

22 Sentences or Lines x = 2 x = x + 2 print x Assignment Statement
Assignment with expression Print statement Constant Reserved Word Variable Operator

23 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 = * x * ( x )

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

25 A variable is a memory location used to store a value
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). x x = * x * ( 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

26 Numeric Expressions Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 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.

27 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 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 4 R 3 5 23 20 3

28 Order of Evaluation x = 1 + 2 * 3 - 4 / 5 ** 6
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 = * / 5 ** 6

29 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 Parenthesis Power Multiplication Addition Left to Right

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

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

32 Operator Precedence Remember the rules top to bottom
Parenthesis Power Multiplication Addition Left to Right 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 = * / 5

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

34 Mixing Integer and Floating
>>> print 99 / 100 >>> print 99 / 100.0 0.99 >>> print 99.0 / 100 >>> print * 3 / -2.5 >>> 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

35 What does “Type” Mean? >>> ddd = 1 + 4 >>> print ddd
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

36 Type Matters Python knows what “type” everything is
>>> 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(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.

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

38 Type Conversions >>> print float(99) / 100 0.99
>>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print * float(3) / 4 - 5 -2.5 >>> 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()

39 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) 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

40 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

41 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

42 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

43 # 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

44 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 >>>

45 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

46 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?

47 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

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

49 Repeated Steps n = 5 No Yes n > 0 ? Program: n = 5 while n > 0 : print n n = n – 1 print 'Blastoff!' Output: 5 4 3 2 1 Blastoff! 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.

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

51 Another Loop n = 0 while n > 0 : print 'Lather’ print 'Rinse'
Yes n > 0 ? print 'Lather' n = 0 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' print 'Rinse' print 'Dry off!' What does this loop do?

52 Breaking Out of a Loop while True: line = raw_input('> ')
The break statement ends the current loop and jumps to the statement immediately following the loop It is like a loop test that can happen anywhere in the body of the loop while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished finished > done Done!

53 Breaking Out of a Loop The break statement ends the current loop and jumps to the statement immediately following the loop It is like a loop test that can happen anywhere in the body of the loop while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished Finished > done Done!

54 line = raw_input('> ') if line == 'done' : break print line
while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' No Yes True ? .... break ... print 'Done'

55 Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done Done!

56 Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done Done!

57 line = raw_input('> ’) if line[0] == '#' : continue
No True ? Yes while True: line = raw_input('> ’) if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' .... .... continue ... ... print 'Done'

58 Indefinite Loops While loops are called "indefinite loops" because they keep going until a logical condition becomes False The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops" Sometimes it is a little harder to be sure if a loop will terminate

59 Definite Loops Quite often we have a list of items of the lines in a file - effectively a finite set of things We can write a loop to run the loop once for each of the items in a set using the Python for construct These loops are called "definite loops" because they execute an exact number of times We say that "definite loops iterate through the members of a set"

60 A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i
Blastoff! for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!'

61 A Definite Loop with Strings
friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done!

62 A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i
No Yes Done? Move i ahead 5 4 3 2 1 Blastoff! for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' print i print 'Blast off!' Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.

63 Looking at In... for i in [5, 4, 3, 2, 1] : print i
The iteration variable “iterates” though the sequence (ordered set) The block (body) of code is executed once for each value in the sequence The iteration variable moves through all of the values in the sequence Five-element sequence Iteration variable for i in [5, 4, 3, 2, 1] : print i

64 for i in [5, 4, 3, 2, 1] : print i Done? Move i ahead print i No Yes
The iteration variable “iterates” though the sequence (ordered set) The block (body) of code is executed once for each value in the sequence The iteration variable moves through all of the values in the sequence Move i ahead print i for i in [5, 4, 3, 2, 1] : print i

65 for i in [5, 4, 3, 2, 1] : print i i = 5 print i Done? Move i ahead
No Yes Done? Move i ahead print i for i in [5, 4, 3, 2, 1] : print i

66 Definite Loops Quite often we have a list of items of the lines in a file - effectively a finite set of things We can write a loop to run the loop once for each of the items in a set using the Python for construct These loops are called "definite loops" because they execute an exact number of times We say that "definite loops iterate through the members of a set"

67 Making “smart” loops The trick is “knowing” something about the whole loop when you are stuck writing code that only sees one entry at a time Set some variables to initial values for thing in data: Look for something or do something to each entry separately, updating a variable. Look at the variables.

68 Looping through a Set $ python basicloop.py Before 9 41 12
3 74 15 After print 'Before' for thing in [9, 41, 12, 3, 74, 15] : print thing print 'After'

69 Counting in a Loop $ python countloop.py zork = 0 Before 0
1 9 2 41 3 12 4 3 5 74 6 15 After 6 zork = 0 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thing print 'After', zork To count how many times we execute a loop we introduce a counter variable that starts at 0 and we add one to it each time through the loop.

70 Summing in a Loop Before 0 zork = 0 9 9 print 'Before', zork 50 41
$ python countloop.py Before 0 9 9 50 41 62 12 65 3 139 74 154 15 After 154 zork = 0 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thing print 'After', zork To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.

71 Finding the Average in a Loop
count = 0 sum = 0 print 'Before', count, sum for value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum, value print 'After', count, sum, sum / count $ python averageloop.py Before 0 0 1 9 9 4 65 3 After An average just combines the counting and sum patterns and divides when the loop is done.

72 Filtering in a Loop $ python search1.py Before Large number 41
print 'Before’ for value in [9, 41, 12, 3, 74, 15] : if value > 20: print 'Large number',value print 'After' $ python search1.py Before Large number 41 Large number 74 After We use an if statement in the loop to catch / filter the values we are looking for.

73 Search Using a Boolean Variable
found = False print 'Before', found for value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, value print 'After', found $ python search1.py Before False False 9 False 41 False 12 True 3 True 74 True 15 After True If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for.

74 Finding the smallest value
smallest = None print 'Before’ for value in [9, 41, 12, 3, 74, 15] : if smallest is None : smallest = value elif value < smallest : print smallest, value print 'After', smallest $ python smallest.py Before 9 9 9 41 9 12 3 3 3 74 3 15 After 3 We still have a variable that is the smallest so far. The first time through the loop smallest is None so we take the first value to be the smallest.

75 The "is" and "is not" Operators
Python has an "is" operaror that can be used in logical expressions Implies 'is the same as' Similar to, but stronger than == 'is not' also is a logical operator smallest = None print 'Before’ for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : print smallest, value print 'After', smallest

76 Summary While loops (indefinite) Infinite loops Using break
Using continue For loops (definite) Iteration variables Largest or smallest

77 >>> Python's For
Unlike Java's for loop, Python's for loop loops over elements in a sequence. To loop over a certain sequence of integers use the range() function. Later we will learn objects that we can use a for loop to go through all of the elements. for.py 1 2 3 4 5 6 7 8 9 10 11 12 for i in range(4): # (end)‏ print i for i in range(1,4): # (start,end)‏ for i in range(2,8,2): # (start,end,step_size)‏ # for <name> in range([<min>,] <max> [,<step>]): # <statements> 77

78 >>> Complex Printing
Sometimes more complex output is needed. To produce output but not go to the next line, just write a comma after the last quotes. This adds whitespace, so sometimes you need “sys.stdout.write()” which just writes what is in the quotes. You also have to import “sys”! Hello.java 1 2 3 4 System.out.print("Hello world! ")‏ System.out.print("This will all be")‏ System.out.println(" on the same line.")‏ hello2.py 1 2 3 4 5 import sys sys.stdout.write("Hello world! ")‏, print "This will all be", print " on the same line."

79 >>> Nested loops
In Python, a lot of the time we can do nested loops in a much more straightforward way using string multiplication. 5 44 333 2222 11111 Nested.java nested1.py 1 2 3 4 5 6 7 8 9 for (int i = 1; i <= 5; i++) { for (int j = 1; j <= (5 - i); j++) { System.out.print(" "); } for (int k = 1; k <= i; k++) { System.out.print(i); System.out.println(); 1 2 3 for i in range(5,0,-1): print " " * (i-1) + str(i)*(6-i)‏ nested2.py 1 2 3 4 5 import sys for i in range(5,0,-1): sys.stdout.write(" " * (i-1))‏ sys.stdout.write(str(i)*(6-i))‏ print 79

80 >>> Mirror scott @ yossarian ~ $ python mirror.py
// Marty Stepp, CSE 142, Autumn 2007 // This program prints an ASCII text figure that // looks like a mirror. // This version uses a class constant to make the figure resizable. public class Mirror2 { public static final int SIZE = 4; // constant to change the figure size public static void main(String[] args) { line(); topHalf(); bottomHalf(); } // Prints the top half of the rounded mirror. public static void topHalf() { for (int line = 1; line <= SIZE; line++) { // pipe System.out.print("|"); // spaces for (int j = 1; j <= -2 * line + (2 * SIZE); j++) { System.out.print(" "); // <> System.out.print("<>"); // dots . for (int j = 1; j <= 4 * line - 4; j++) { System.out.print("."); System.out.println("|"); // Prints the bottom half of the rounded mirror. public static void bottomHalf() { for (int line = SIZE; line >= 1; line--) { // Prints the #==# line at the top and bottom of the mirror. public static void line() { System.out.print("#"); for (int j = 1; j <= 4 * SIZE; j++) { System.out.print("="); System.out.println("#"); yossarian ~ $ python mirror.py #================# | <><> | | <>....<> | | <> <> | |<> <>| 80

81 >>> Parameters
Parameters are easy in Python once you know Java's. Simply remove all types from the method header and do the normal conversion. public static void printSum(int x, int y) { System.out.println(x + y); } PrintSum.java 1 2 3 4 def print_sum(x, y): print(str(x + y))‏ print_sum(2, 3)‏ print_sum.py 1 2 3 4

82 >>> Parameters Example
************* ******* *********************************** ********** * * ***** * *

83 >>> Example Solution
def draw_line(num): print "*" * num def draw_box(width, height): draw_line(width) for i in range(height-2): print "*" + " " * (width-2) + "*" #main draw_line(13) draw_line(7) draw_line(35) draw_box(10,3) draw_box(5,4)

84 >>> Defaults
Unlike Java, Python's parameters can have default values to use when one is not given. def print_range(start=1, end=1, interval=1, sep=" "): for i in range(start, end, interval): print str(i) + sep, print end print range(0,7)‏ print_range(1,7,1,“ ")‏ print_range.py 1 2 3 4 5 6 7

85 >>> Keywords
When calling a function with a number of parameters with defaults you can modify particular parameters with a keyword so that you do not need to specify all preceding parameters. def print_range(start=1,end=1,interval=1,sep=" "): for i in range(start,end,interval): print str(i) + sep, print end print range(0,7)‏ print_range(1,7,1,“ ")‏ print_range(end=7,sep=“ ")‏ print_range.py 1 2 3 4 5 6 7 8 9

86 String Data Type A string is a sequence of characters
>>> str1 = "Hello” >>> str2 = 'there' >>> bob = str1 + str2 >>> print bob Hellothere >>> str3 = '123' >>> str3 = str3 + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects >>> x = int(str3) + 1 >>> print x 124 >>> A string is a sequence of characters A string literal uses quotes 'Hello' or “Hello” For strings, + means “concatenate” When a string contains numbers, it is still a string We can convert numbers in a string into a number using int()

87 Reading and Converting
>>> name = raw_input('Enter:') Enter:Chuck >>> print name Chuck >>> apple = raw_input('Enter:') Enter:100 >>> x = apple – 10 Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for -: 'str' and 'int' >>> x = int(apple) – 10 >>> print x 90 We prefer to read data in using strings and then parse and convert the data as we need This gives us more control over error situations and/or bad user input Raw input numbers must be converted from strings

88 Looking Inside Strings
We can get at any single character in a string using an index specified in square brackets The index value must be an integer and starts at zero The index value can be an expression that is computed b a n a n a 1 2 3 4 5 >>> fruit = 'banana' >>> letter = fruit[1] >>> print letter a >>> n = 3 >>> w = fruit[n - 1] >>> print w n

89 A Character Too Far You will get a python error if you attempt to index beyond the end of a string. So be careful when constructing index values and slices >>> zot = 'abc' >>> print zot[5] Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: string index out of range >>>

90 Strings Have Length >>> fruit = 'banana'
There is a built-in function len that gives us the length of a string b a n a n a 1 2 3 4 5 >>> fruit = 'banana' >>> print len(fruit) 6

91 Len Function len() function >>> fruit = 'banana'
>>> x = len(fruit) >>> print x 6 A function is some stored code that we use. A function takes some input and produces an output. len() function 'banana' (a string) 6 (a number) Guido wrote this code

92 Len Function >>> fruit = 'banana' >>> x = len(fruit)
>>> print x 6 A function is some stored code that we use. A function takes some input and produces an output. def len(inp): blah for x in y: 'banana' (a string) 6 (a number)

93 Looping Through Strings
Using a while statement and an iteration variable, and the len function, we can construct a loop to look at each of the letters in a string individually fruit = 'banana' index = 0 while index < len(fruit) : letter = fruit[index] print index, letter index = index + 1 0 b 1 a 2 n 3 a 4 n 5 a

94 Looping Through Strings
A definite loop using a for statement is much more elegant The iteration variable is completely taken care of by the for loop b a n fruit = 'banana' for letter in fruit : print letter

95 Looping Through Strings
A definite loop using a for statement is much more elegant The iteration variable is completely taken care of by the for loop fruit = 'banana' for letter in fruit : print letter b a n index = 0 while index < len(fruit) : letter = fruit[index] print letter index = index + 1

96 Looping and Counting word = 'banana' count = 0 for letter in word :
This is a simple loop that loops through each letter in a string and counts the number of times the loop encounters the 'a' character. word = 'banana' count = 0 for letter in word : if letter == 'a' : count = count + 1 print count

97 Looking deeper into in for letter in 'banana' : print letter
The iteration variable “iterates” though the sequence (ordered set) The block (body) of code is executed once for each value in the sequence The iteration variable moves through all of the values in the sequence Iteration variable Six-character string for letter in 'banana' : print letter

98 for letter in 'banana' : print letter b a n a n a Done? Advance letter
Yes Done? b a n a n a Advance letter print letter for letter in 'banana' : print letter The iteration variable “iterates” though the string and the block (body) of code is executed once for each value in the sequence

99 Slicing Strings >>> s = 'Monty Python'
1 2 3 4 5 6 7 8 9 10 11 We can also look at any continuous section of a string using a colon operator The second number is one beyond the end of the slice - “up to but not including” If the second number is beyond the end of the string, it stops at the end >>> s = 'Monty Python' >>> print s[0:4] Mont >>> print s[6:7] P >>> print s[6:20] Python Slicing Strings

100 Slicing Strings >>> s = 'Monty Python'
1 2 3 4 5 6 7 8 9 10 11 If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively >>> s = 'Monty Python' >>> print s[:2] Mo >>> print s[8:] Thon >>> print s[:] Monty Python Slicing Strings

101 String Concatenation >>> a = 'Hello'
>>> b = a + 'There' >>> print b HelloThere >>> c = a + ' ' + 'There' >>> print c Hello There >>> When the + operator is applied to strings, it means "concatenation "

102 Using in as an Operator >>> fruit = 'banana’
>>> 'n' in fruit True >>> 'm' in fruit False >>> 'nan' in fruit >>> if 'a' in fruit : print 'Found it!’ ... Found it! >>> The in keyword can also be used to check to see if one string is "in" another string The in expression is a logical expression and returns True or False and can be used in an if statement

103 String Comparison if word == 'banana': print 'All right, bananas.'
print 'Your word,' + word + ', comes before banana.’ elif word > 'banana': print 'Your word,' + word + ', comes after banana.’ else: print 'All right, bananas.'

104 String Library Python has a number of string functions which are in the string library These functions are already built into every string - we invoke them by appending the function to the string variable These functions do not modify the original string, instead they return a new string that has been altered >>> greet = 'Hello Bob‘ >>> zap = greet.lower() >>> print zaphello bob >>> print greet Hello Bob >>> print 'Hi There'.lower() hi there >>>

105 >>> stuff = 'Hello world’
>>> type(stuff)<type 'str'> >>> dir(stuff) ['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

106

107 String Library str.replace(old, new[, count]) str.lower()
str.capitalize() str.center(width[, fillchar]) str.endswith(suffix[, start[, end]]) str.find(sub[, start[, end]]) str.lstrip([chars]) str.replace(old, new[, count]) str.lower() str.rstrip([chars]) str.strip([chars]) str.upper()

108 Searching a String b a n a n a 1 2 3 4 5 >>> fruit = 'banana'
We use the find() function to search for a substring within another string find() finds the first occurance of the substring If the substring is not found, find() returns -1 Remember that string position starts at zero 1 2 3 4 5 >>> fruit = 'banana' >>> pos = fruit.find('na') >>> print pos 2 >>> aa = fruit.find('z') >>> print aa -1

109 Making everything UPPER CASE
You can make a copy of a string in lower case or upper case Often when we are searching for a string using find() - we first convert the string to lower case so we can search a string regardless of case >>> greet = 'Hello Bob' >>> nnn = greet.upper() >>> print nnn HELLO BOB >>> www = greet.lower() >>> print www hello bob >>>

110 Search and Replace >>> greet = 'Hello Bob'
>>> nstr = greet.replace('Bob','Jane') >>> print nstr Hello Jane >>> nstr = greet.replace('o','X') >>> print nstrHellX BXb >>> The replace() function is like a “search and replace” operation in a word processor It replaces all occurrences of the search string with the replacement string

111 Stripping Whitespace Sometimes we want to take a string and remove whitespace at the beginning and/or end lstrip() and rstrip() to the left and right only strip() Removes both begin and ending whitespace >>> greet = ' Hello Bob ' >>> greet.lstrip() 'Hello Bob ' >>> greet.rstrip() ' Hello Bob' >>> greet.strip() 'Hello Bob' >>>

112 Prefixes >>> line = 'Please have a nice day’
>>> line.startswith('Please') True >>> line.startswith('p') False

113 >>> atpos = data.find('@') >>> print atpos 21
31 From Sat Jan 5 09:14: >>> data = 'From Sat Jan 5 09:14: ’ >>> atpos = >>> print atpos 21 >>> sppos = data.find(' ',atpos) >>> print sppos 31 >>> host = data[atpos+1 : sppos] >>> print host uct.ac.za Parsing and Extracting

114 Summary String type Read/Convert Indexing strings []
Slicing strings [2:4] Looping through strings with for and while Concatenating strings with + String operations

115 >>> Graphics
Graphics in Python are similar to graphics in Java drawingpanel.py needs to be in the same directory as your program that uses it The Graphics (g) in Python behaves like the Graphics (g) in Java and is passed as a parameter in the same fashion. To let the Python interpreter know that you want to use the drawingpanel.py file you must add “from drawingpanel import *” at the top of your file panel.mainloop() must be put at the end of the program

116 >>> Graphics Methods
Java Python g.drawLine(x1, y1, x2, y2); g.create_line(x1, y1, x2, y2) g.create_line(x1, y1, x2, y2, x3, y3,…, xN, yN) g.drawOval(x1, y1, width, height); g.create_oval(x1, y1, x2, y2) g.drawRect(x1, y1, width, height); g.create_rectangle(x1, y1, x2, y2) panel.setBackground(Color); g[“bg”] = “ <color> “

117 >>> Graphics Methods
DrawingPanel panel = new DrawingPanel(300, 200); Graphics g = panel.getGraphics(); panel.setBackground(Color.YELLOW); Java 1 2 3 4 panel = DrawingPanel(300, 200) g = panel.get_graphics() g["bg"] = "yellow" Python 1 2 3 4

118 >>> Graphics
What about...? g.setColor() g.fillRect(), g.fillOval() Fill colors and borders in Python are set as parameters in the methods. g.setColor(Color.RED); g.fillRect(x, y, w, h,); g.setColor(Color.BLACK); g.drawRect(x, y, w, h); Java 1 2 3 4 g.create_rectangle(x, y, x+w, y+h, fill=“red”, outline=“black”)‏ Python 1 2 3 4

119 >>> Graphics Example 1
from drawingpanel import * panel = DrawingPanel(400,380) g = panel.get_graphics() g["bg"]="black“ g.create_rectangle(100, 100, 200, 200, fill="red", outline="yellow") panel.mainloop() Python 1 2 3 4 5 6

120 >>> Graphics
What about...? Triangles Hexagons Etc. g.create_polygon(x1, y1, x2, y2,..., xN, yN) from drawingpanel import * panel = DrawingPanel(100,100) g = panel.get_graphics() g.create_polygon(50, 50, 100, 0, 100, 100, fill="green") panel.mainloop() Python 1 2 3 4 5

121 >>> Graphics Example 2
Let’s recreate the Java car example in Python: import java.awt.*; public class DrawCar { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(200, 100); panel.setBackground(Color.LIGHT_GRAY); Graphics g = panel.getGraphics(); g.setColor(Color.BLACK); g.fillRect(10, 30, 100, 50); g.setColor(Color.RED); g.fillOval(20, 70, 20, 20); g.fillOval(80, 70, 20, 20); g.setColor(Color.CYAN); g.fillRect(80, 40, 30, 20); }

122 >>> Example 2 (auf Python)
Let’s recreate the Java car example in Python: from drawingpanel import * panel = DrawingPanel(200,100) g = panel.get_graphics() g["bg"] = "gray" g.create_rectangle(10, 30, , 30+50, fill="black") g.create_oval(20, 70, 20+20, 70+20,fill="red“, outline=“red”) g.create_oval(80, 70, 80+20, 70+20, fill="red“, outline=“red”) g.create_rectangle(80, 40, 80+30, 40+20, fill="cyan”, outline=“cyan”)

123 >>> Example 2 - Parameterized
Now, let’s use parameters so that we can place the cars all over the DrawingPanel.

124 >>> Example 2 - Parameterized
from drawingpanel import * def draw_car(g, x, y): g.create_rectangle(x, y, x+100, y+50, fill="black") g.create_oval(x+10, y+40, x+10+20, y+40+20, fill="red", outline="red") g.create_oval(x+70, y+40, x+70+20, y+40+20, fill="red", outline="red") g.create_rectangle(x+70, y+10, x+70+30, y+10+20, fill="cyan“, outline=“cyan”) # main panel = DrawingPanel(260,100) g = panel.get_graphics() g["bg"] = "gray" draw_car(g, 10, 30) draw_car(g, 150, 10)

125 >>> Overview
* if else * returns * input

126 >>> if Like many things in the transition from Java to Python, curly braces are replaced with colons and whitespace, the parentheses are dropped and &&, || and ! change. < > <= >= == != or and not || && ! Java python // 1 for english // 2 for german int translator = 1; if (translator == 1) { english(); } else if (translator == 2) { german(); } else { System.out.println("None"); } Translator.java 1 2 3 4 5 6 7 8 9 10 Notice: "else if" becomes "elif" translator = 1 if translator == 1: english()‏ elif translator == 2: german()‏ else: print "None" translator.py 1 2 3 4 5

127 >>> strings Just like in Java, strings are objects. Lets look at different things that we can do with them: s = "wow" s = "wOw" s = "hmmm" s = " ack " string methods s.capitalize() => "Wow" s.endswith("w") => True s.find("o") => 1 s.islower() => True s.isupper() => False s.lower() => "wow" s.startswith("hm") => True s.strip() => "ack" s.swapcase() => "WoW" s.upper() => "WOW"

128 "shocking" >>> strings as sequences Indexing
Like arrays in Java, strings have zero-based indexes, and we can access parts of them with square brackets instead of using Java's substring() and charAt() methods. Lets look at things we can do if we have the string s = "shocking" s[<index>] s[3] => "c" s[-1] => "g" s[<start>:<end>] s[4:] => "king" s[3:5] => "ck" s[-3:] => "ing" len(s) len(s) => 8 sequence operations Indexing from the front "shocking" from the back example: s[2:-4] => "oc"

129 >>> return Returns in python are straightforward. Simply "return <value>" instead of "return <value>;" and forget about the types. def f_to_c(degreesF): degreesC = 5.0 / 9.0 * (degreesF – 32)‏ return degreesC #main temp = f_to_c(68)‏ print ("Temperature is: " + str(temp))‏ degrees.py 1 2 3 4 5 6 7 def slope(x1, y1, x2, y2): return (y2 - y1) / (x2 - x1) #main slope = slope(0, 0, 5, 5)‏ print ("Slope is: " + str(slope))‏ slope.py 1 2 3 4 5 6 7

130 >>> math in python
Most of the math functions are the same in python. Here is a list with a short description. In order to use them, we have to import math The constants are the same as Java, except lower case. math.pi = math.e = Random comes from its own class: import random random.random()‏ math functions ceil(x)‏ fabs(x)‏ floor(x)‏ exp(x)‏ log(x,[base])‏ log10(x)‏ pow(x, y)‏ sqrt(x)‏ cos(x)‏ hypot(x, y)‏ sin(x)‏ tan(x)‏ degrees(x)‏ radians(x)‏

131 >>> input() vs. raw_input()‏
There are two ways of getting input. The first is input(). It takes in input until enter is hit and then tries to interpret it into python. However, this way only works well for numbers. The second way is to use raw_input() which returns The raw_input()` function doesn't evaluate, it will just read whatever you enter. >>> x = input("yes? ")‏ yes? y Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'y' is not defined yes? 2 >>> print x 2 >>> x = input("num? ")‏ num? 2.0 2.0 name = input("what is your name?") print(name) name = raw_input("what is your name ?") inputs.py 1 2 3 4 5 6 7 8 9 10

132 >>> Overview
* boolean * while * random * tuples

133 >>> boolean Just like Java, there are boolean values. These values are True and False. >>> True True >>> False False >>> 2==3 >>> "this"=="this" >>> 2==3 and 4==4 >>> x = not 1 == 2 >>> x True False < > <= >= == != or and not

134 >>> while n = 10 # initialize sum and counter sum = 0 i = 1
while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum) sentinel.py 1 2 3 4 5 6 7 8 9 The while loop translates nicely from Java to Python. Scanner console = new Scanner(System.in); int sum = 0; System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); while (number != -1) { sum = sum + number; number = console.nextInt(); } System.out.println("The total is " + sum); Sentinel.java 1 2 3 4 5 6 7 8 9 10

135 >>> random Just like in Java, python also has random object. Here is an example: >>> from random import * >>> randint(0,9)‏ 1 4 >>> choice(range(10))‏ 7 random.randint(a,b)‏ returns an int between a and b inclusive random.choice(seq)‏ returns a random element of the sequence

136 >>> tuples as points
Python does not have Point Objects. Instead we use tuples. A tuple is able to hold multiple values. These values can correspond to the x and y coordinates of a point. The syntax for a tuple is: <variable name> = (value1, value 2, ..., valueN) For a point, we only need two values. Creates a tuple where the first value is 3 and the second value is 5. This can represent a 2D point where the “x” value is 3 and the “y” value is 5. >>> p = (3, 5) >>> p‏ (3, 5)

137 >>> retrieving tuple values
If we wish to use the values in a tuple, we can assign each value to a vairable. This creates two new variables x and y, and assigns the first value in our tuple to x, and the second value to y. >>> p = (3, 5) >>> p (3, 5) >>> (x, y) = p >>> x 3 >>> y 5

138 >>> parameters and returns
Tuples can be passed just like any other variable. Once inside a method, we will want to access its values. Example: def equal(p1, p2): (x1, y1) = p1 (x2, y2) = p2 return x1==x2 and y1==y2 Additionally, we can return tuples. Assume we wanted to add two two. This does not make much sense for points, but does for 2D vectors. def addVectors(p1, p2): return (x1 + x2, y1 + y2) NOTE: Tuples are “immutable.” This means that the values within a tuple cannot be altered once it has been created. Because of this, if we would like to change the value of our tuples, we must create a new tuple with the values we want, and use it instead.

139 >>> point distance method
# Calculates the distance between two points def distance(p1, p2): (x1, y1) = p1 (x2, y2) = p2 dx = abs(x1 - x2) dy = abs(y1 - y2) return sqrt(dx * dx + dy * dy)


Download ppt "1."

Similar presentations


Ads by Google