Python Basics Interpreted Not compiled like Java This
>>> 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 Code Runtime Env Compute r Interpreter Compute r
>>> Getting it Going Windows 1) Download Python from python. org. 2) Run 'python' using the run command. -or. Run Idle from the Start Menu. Mac OSX 1) Python is already installed. 2) Open a terminal and run python or run Idle from finder. 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” Linux 1) Chances are you already have Pythoninstalled. To check run python from the terminal. 2) If not, install python through your distribution's package system.
>>> Topic Review * printing - System. out. println(); * methods – public static void <name>(). . . Hello. java 1 public class Hello { 2 public static void main(String[] args){ System. out. println("Hello world!"); 3 4 } Hello. java 5 } 1 public class Hello { 2 public static void main(String[] args){ hello(); 3 4 } 5 public static void hello(){ System. out. println("Hello world!"); 6 7 } 8 }
>>> Missing Main Hello. java 1 public class Hello { 2 public static void main(String[] args){ System. out. println("Hello world!"); 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 1 print "Hello world!" 2 3 4 5
>>> Printing Hello. java 1 public class Hello { 2 public static void main(String[] args){ System. out. println("Hello world!"); 3 System. out. println(); 4 System. out. println("Suppose two swallows carry it together. "); 5 6 } 7 } 8 Escape sequences: * t – tab * n – new line * " - " * \ - hello. py 1 print "Hello world!" 2 print 3 print "Suppose two swallows carry it together. " 4
>>> Methods Hello. java 1 public class Hello { 2 public static void main(String[] args){ hello(); 3 4 } 5 public static void hello(){ System. out. println("Hello "world"!"); 6 7 } 8 } hello. py 1 def hello(): print "Hello "world"!" 2 3 4 #main 5 hello() Structure: def <method name>(): <statement>. . . <statement> 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.
>>> 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 public class Hello { 2 public static void main(String[] args){ System. out. println(“Hello "world"!”); 3 4 } 5 } hello. py 1 def hello(): print "Hello "world"!" 2 3 4 hello()
>>> Example 1 Example: Write a method that produces the following output. We are the Knights Who Say. . . "Nee!" (Nee!) NO! Not the Knights Who Say "Nee". . . We are the Knights Who Say. . . "Nee!" (Nee!)
>>> Example 1 Solution: def knights(): print "We are the Knights Who Say. . . "Nee!"" print "(Nee!)" print def poor. Souls(): print "NO!t Not the Knights Who Say "Nee". . . " print knights() poor. Souls() knights()
>>> Example 2 Example: Write a method that produces the following output. ______ / ______/ / / ______/ +----+ ______ / / | STOP ______/ | / ______ / +----+
>>> Example 2 Example: Write a method that produces the following output. ______ / ______/ / / ______/ +----+ ______ / / | STOP ______/ | / ______ / +----+ def egg(): top() bottom() print def top(): print " ______" print " / \" print "/ \" def cup(): bottom() line() print def bottom(): print "\ /" print " \______/" def stop(): top() print "| STOP |" bottom() print def hat(): top() line() print def line(): print "+----+" egg() cup() stop() hat()
>>> 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 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. 178 175. 0 “wow” 'w' True Java int double String char boolean python int float str bool
>>> 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> Type. Error: cannot concatenate 'str' and 'int' objects >>> "Suppose " + str(2) + " swallows carry it together. " 'Suppose 2 swallows carry it together. '
>>> 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
>>> Differences in expressions There 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!' >>> x = 1 >>> x += 1 >>> print x 2
>>> 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. Variables. java 1. . . 2 int x = 2; 3 x++; 4 System. out. println(x); 5 x = x * 8; 6 System. out. println(x); 7 8 double d = 3. 0; 9 d /= 2; 10 System. out. println(d); 11 expressions. py 1 x=2 2 x += 1 3 print( x) 4 x=x*8 5 print (x) 6 7 d = 3. 0 8 d /= 2 9 print (d) 10 11 s = "wow" 12 print (s) 13 14 15 16
>>> 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! v. Fixed values such as numbers, letters, and strings are called “constants” - because their value does not change v. Numeric constants are as you expect v. String constants use single-quotes (') or double-quotes (") constants. py 1 SIZE = 2 2 x = 10 * SIZE 3 print x 4 5 # main 6 … >>> print 123 >>> print 98. 6 >>> print 'Hello world' Hello world
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 x = 12. 2 y = 14 x 12. 2 100 x = 100 y 14
Python Variable Name Rules • Must start with a letter or underscore _ • Must consist of letters and numbers and underscores • Case Sensitive • Good: spam eggs spam 23 _speed • Bad: 23 spam #sign var. 12 • Different: spam SPAM
Reserved Words • 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
Sentences or Lines x=2 x=x+2 print x Variable Operator Assignment Statement Assignment with expression Print statement Constant Reserved Word
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 )
A variable is a memory location used to store a value (0. 6). x 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
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 0. 6 0. 93 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
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. Operator Operation + * Addition Subtractio n Multiplicat ion / Division ** Power % Remaind er
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 Operato Operatio r n + * 3 Subtracti on Multiplica tion / Division ** Power % Remaind er 23 20 Addition
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
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
>>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1+8/4*5 1+2*5 1 + 10 11
>>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> Note 8/4 goes before 4*5 because of the left-right rule. Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1+8/4*5 1+2*5 1 + 10 11
Operator Precedence • Remember the rules top to bottom • When writing code - use parenthesis Power Multiplication Addition Left to Right • 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
Python Integer Division is Weird! • Integer division truncates • Floating point division produces floating point numbers This changes in Python 3. 0 >>> 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
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 >>>
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
Type Matters 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. >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> Type. Error: cannot concatenate 'str' and 'int' objects >>> type(eee) <type 'str'> >>> type('hello') <type 'str'> >>> type(1) <type 'int'> >>>
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'> >>>
Type Conversions >>> print float(99) / 100 0. 99 • When you put an >>> i = 42 integer and floating >>> type(i) point in an expression <type 'int'> the integer is implicitly >>> f = float(i) converted to a float >>> print f 42. 0 • You can control this >>> type(f) with the built in <type 'float'> functions int() and >>> print 1 + 2 * float(3) / 4 - 5 float() -2. 5 >>>
String Conversions • 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 >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> Type. Error: 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> Value. Error: invalid literal for int()
User Input • We can instruct Python to pause and read data from the user using the raw_input function nam = raw_input(‘Who are you? ’) • The raw_input print 'Welcome', nam function returns a string Who are you? Chuck Welcome Chuck
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
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
# 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
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’ Abc 123 >>> print 'Hi' * 5 Hi. Hi. Hi >>>
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
x 1 q 3 z 9 ocd = 35. 0 x 1 q 3 z 9 afd = 12. 50 x 1 q 3 p 9 afd = x 1 q 3 z 9 ocd * x 1 q 3 z 9 afd print x 1 q 3 p 9 afd What is this code doing? hours = 35. 0 rate = 12. 50 pay = hours * rate print pay a = 35. 0 b = 12. 50 c=a*b print c
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
Summary • Type • Resrved words • Variables (mnemonic) • Operators • Operator precedence • Integer Division • Conversion between types • User input • Comments (#)
n=5 Repeated Steps No Yes n>0? print n n = n -1 print 'Blastoff' Program: n=5 while n > 0 : print n n=n– 1 print 'Blastoff!' print n Output: 5 4 3 2 1 Blastoff! 0 Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.
n=5 No Yes n>0? print 'Lather' print 'Rinse' An Infinite Loop n=5 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' What is wrong with this loop?
n=0 No Yes n>0? print 'Lather' print 'Rinse' print 'Dry off!' Another Loop n=0 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' What does this loop do?
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 > finished > done Done!
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 > finished Finished > done Done!
while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' No Yes True ? . . break . . . http: //en. wikipedia. org/wiki/Transporter_(Star_Trek) print 'Done'
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 > # don't print this > print this! > done Done!
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 > # don't print this > print this! > done Done!
No while True: line = raw_input('> ’) if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' Yes True ? . . continue . . . print 'Done'
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
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"
A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff!
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!
No Yes A Simple Definite Loop Done? Move i ahead print i for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff! 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.
Looking at In. . . 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
No Yes Done? Move i ahead print i • • • 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
i=5 No Yes Done? Move i ahead print i i=4 print i i=3 print i for i in [5, 4, 3, 2, 1] : print i i=2 print i i=1 print i
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
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.
Looping through a Set $ python basicloop. py Before 9 print 'Before' for thing in [9, 41, 12, 3, 74, 15] : 41 12 print thing 3 print 'After' 74 15 After
Counting in a Loop zork = 0 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thing print 'After', zork $ python countloop. py Before 0 19 2 41 3 12 43 5 74 6 15 After 6 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.
Summing in a Loop $ python countloop. py zork = 0 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thing print 'After', zork Before 0 99 50 41 62 12 65 3 139 74 15 After 154 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.
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 / count $ python averageloop. py Before 0 0 199 2 50 41 3 62 12 4 65 3 5 139 74 6 154 15 After 6 154 25 An average just combines the counting and sum patterns and divides when the loop is done.
Filtering in a Loop print 'Before’ for value in [9, 41, 12, 3, 74, 15] : if value > 20: print 'Large number', value print 'After' $ python search 1. 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.
Search Using a Boolean Variable found = False $ python search 1. py print 'Before', found Before False for value in [9, 41, 12, 3, 74, 15] False : 9 if value == 3 : False 41 found = True False 12 print found, value True 3 True 74 print 'After', found 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.
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 : smallest = value print smallest, value print 'After', smallest $ python smallest. py Before 99 9 41 9 12 33 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.
The "is" and "is not" Operators smallest = None print 'Before’ for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, value print 'After', smallest 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
Summary While loops (indefinite) Infinite loops Using break Using continue For loops (definite) Iteration variables Largest or smallest
>>> Python's Unlike Java's for loop, Python's for 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 for. py 1 for i in range(4): # (end) 2 print i 3 4 for i in range(1, 4): # (start, end) 5 print i 6 7 for i in range(2, 8, 2): # (start, end, step_size) 8 print i 9 10 # for <name> in range([<min>, ] <max> [, <step>]): 11 # <statements> 12
>>> 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 System. out. print("Hello world! ") 2 System. out. print("This will all be") 3 System. out. println(" on the same line. ") 4 hello 2. py 1 import sys 2 3 sys. stdout. write("Hello world! "), 4 print "This will all be", 5 print " on the same line. "
>>> Nested loops In Python, a lot of the time we can do nested loops in a much more straightforward way using string multiplication. Nested. java 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(); } 5 44 333 2222 11111 nested 1. py 1 for i in range(5, 0, -1): 2 print " " * (i-1) + str(i)*(6 -i) 3 nested 2. py 1 import sys 2 for i in range(5, 0, -1): 3 sys. stdout. write(" " * (i-1)) 4 sys. stdout. write(str(i)*(6 -i)) 5 print
>>> 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 Mirror 2 { public static final int SIZE = 4; // constant to change the figure size public static void main(String[] args) { line(); top. Half(); bottom. Half(); line(); } // Prints the top half of the rounded mirror. public static void top. Half() { 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. print("<>"); // spaces for (int j = 1; j <= -2 * line + (2 * SIZE); j++) { System. out. print(" "); } // pipe System. out. println("|"); } } // Prints the bottom half of the rounded mirror. public static void bottom. Half() { for (int line = SIZE; line >= 1; 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. print("<>"); // spaces for (int j = 1; j <= -2 * line + (2 * SIZE); j++) { System. out. print(" ");
>>> Parameters are easy in Python once you know Java's. Simply remove all types from the method header and do the normal conversion. Print. Sum. java 1 public static void print. Sum(int x, int y) { System. out. println(x + y); 2 3 } 4 print_sum. py 1 def print_sum(x, y): 2 print(str(x + y)) 3 4 print_sum(2, 3)
>>> 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) + "*" draw_line(width) #main draw_line(13) draw_line(7) draw_line(35) draw_box(10, 3) draw_box(5, 4)
>>> Defaults Unlike Java, Python's parameters can have default values to use when one is not given. print_range. py 1 def print_range(start=1, end=1, interval=1, sep=" "): 2 for i in range(start, end, interval): 3 print str(i) + sep, 4 print end 5 6 print range(0, 7) 7 print_range(1, 7, 1, “ ")
>>> 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. print_range. py 1 def print_range(start=1, end=1, interval=1, sep=" "): 2 for i in range(start, end, interval): 3 print str(i) + sep, 4 print end 5 6 print range(0, 7) 7 print_range(1, 7, 1, “ ") 8 9 print_range(end=7, sep=“ ")
String Data Type �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() >>> str 1 = "Hello” >>> str 2 = 'there' >>> bob = str 1 + str 2 >>> print bob Hellothere >>> str 3 = '123' >>> str 3 = str 3 + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module>Type. Error: cannot concatenate 'str' and 'int' objects >>> x = int(str 3) + 1 >>> print x 124 >>>
Reading and Converting • 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 >>> 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>Type. Error: unsupported operand type(s) for -: 'str' and 'int' >>> x = int(apple) – 10 >>> print x 90
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 0 1 2 3 4 5 >>> fruit = 'banana' >>> letter = fruit[1] >>> print letter a >>> n = 3 >>> w = fruit[n - 1] >>> print w n
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>Index. Error: string index out of range >>>
Strings Have Length • There is a built-in function len that gives us the length of a string b a n a 0 1 2 3 4 5 >>> fruit = 'banana' >>> print len(fruit) 6
Len Function >>> fruit = 'banana' >>> x = len(fruit) >>> print x 6 'banana' (a string) A function is some stored code that we use. A function takes some input and produces an output. len() function Guido wrote this code 6 (a number)
Len Function >>> fruit = 'banana' >>> x = len(fruit) >>> print x 6 'banana' (a string) 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: blah 6 (a number)
Looping Through Strings • Using a while statement and an fruit = 'banana' iteration variable, 0 and the len function, index = 0 1 while index < len(fruit) : we can construct a 2 letter = fruit[index] loop to look at each of the letters in a print index, letter 3 string individually index = index + 1 4 b a n 5 a
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 a
Looping Through Strings • A definite loop using a for statement is much more elegant • The iteration variable is completely taken care of by fruit = 'banana' for letter in fruit : print letter index = 0 while index < len(fruit) : letter = fruit[index] print letter index = index + 1 b a n a
Looping and Counting • 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
Looking deeper into in �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 Six-character string Iteration variable for letter in 'banana' : print letter
Yes Advance Done? letter b a n a 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
M o n t y P y t h o n 0 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
M o n t y P y t h o n 0 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
String Concatenation • When the + operator is applied to strings, it means "concatenati on" >>> a = 'Hello' >>> b = a + 'There' >>> print b Hello. There >>> c = a + ' ' + 'There' >>> print c Hello There >>>
Using in as an Operator • 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 >>> fruit = 'banana’ >>> 'n' in fruit True >>> 'm' in fruit False >>> 'nan' in fruit True >>> if 'a' in fruit : . . . print 'Found it!’. . . Found it! >>>
String Comparison if word == 'banana': print 'All right, bananas. ' if word < 'banana': print 'Your word, ' + word + ', comes before banana. ’ elif word > 'banana': print 'Your word, ' + word + ', comes after banana. ’ else: print 'All right, bananas. '
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 >>> greet = 'Hello Bob‘ >>> zap = greet. lower() >>> print zaphello bob >>> print greet Hello Bob >>> print 'Hi There'. lower() hi there >>>
>>> stuff = 'Hello world’ >>> type(stuff)<type 'str'> >>> dir(stuff) ['capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] http: //docs. python. org/lib/string-methods. html
http: //docs. python. org/lib/string-methods. html
String Library 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. upper() http: //docs. python. org/lib/string-methods. html
Searching a String • 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 b a n a 0 1 2 3 4 5 >>> fruit = 'banana' >>> pos = fruit. find('na') >>> print pos 2 >>> aa = fruit. find('z') >>> print aa -1
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 >>>
Search and Replace >>> greet = 'Hello Bob' �The replace() >>> nstr = greet. replace('Bob', 'Jane') function is like >>> print nstr a “search and Hello Jane replace” >>> nstr = greet. replace('o', 'X') operation in a >>> print nstr. Hell. X BXb word processor >>> �It replaces all occurrences of the search string with the replacement string
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 >>> greet = ' Hello Bob ' >>> greet. lstrip() 'Hello Bob ' >>> greet. rstrip() ' Hello Bob' >>> greet. strip() 'Hello Bob' >>>
Prefixes >>> line = 'Please have a nice day’ >>> line. startswith('Please') True >>> line. startswith('p') False
21 31 From stephen. marquard@uct. ac. za Sat Jan 5 09: 14: 16 2008 >>> data = 'From stephen. marquard@uct. ac. za Sat Jan 5 09: 14: 16 200 >>> atpos = data. find('@') >>> print atpos 21 >>> sppos = data. find(' ', atpos) >>> print sppos 31 Parsing and >>> host = data[atpos+1 : sppos] Extracting >>> print host uct. ac. za
Summary • String type • Read/Convert • Indexing strings [] • Slicing strings [2: 4] • Looping through strings with for and while • Concatenating strings with + • String operations
>>> 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
>>> Graphics Java Methods Python g. draw. Line(x 1, y 1, x 2, y 2); g. create_line(x 1, y 1, x 2, y 2) g. create_line(x 1, y 1, x 2, y 2, x 3, y 3, …, x. N, y. N) g. draw. Oval(x 1, y 1, width, height); g. create_oval(x 1, y 1, x 2, y 2) g. draw. Rect(x 1, y 1, width, height); g. create_rectangle(x 1, y 1, x 2, y 2) panel. set. Background(Color); g[“bg”] = “ <color> “
>>> Graphics Methods Java 1 Drawing. Panel panel = new Drawing. Panel(300, 200); 2 Graphics g = panel. get. Graphics(); 3 panel. set. Background(Color. YELLOW); 4 Python 1 panel = Drawing. Panel(300, 200) 2 g = panel. get_graphics() 3 g["bg"] = "yellow" 4
>>> Graphics • What about. . . ? • g. set. Color() • g. fill. Rect(), g. fill. Oval() • Fill colors and borders in Python are set as parameters in the methods. Java 1 g. set. Color(Color. RED); 2 g. fill. Rect(x, y, w, h, ); 3 g. set. Color(Color. BLACK); 4 g. draw. Rect(x, y, w, h); Python 1 2 g. create_rectangle(x, y, x+w, y+h, fill=“red”, outline=“black”) 3 4
>>> Graphics Example 1 Python 1 2 3 4 5 6 from drawingpanel import * panel = Drawing. Panel(400, 380) g = panel. get_graphics() g["bg"]="black“ g. create_rectangle(100, 200, fill="red", outline="yellow") panel. mainloop()
>>> Graphics • What about. . . ? • Triangles • Hexagons • Etc. • g. create_polygon(x 1, y 1, x 2, y 2, . . . , x. N, y. N) Python 1 2 3 4 5 from drawingpanel import * panel = Drawing. Panel(100, 100) g = panel. get_graphics() g. create_polygon(50, 100, fill="green") panel. mainloop()
>>> Graphics Example 2 Let’s recreate the Java car example in Python: import java. awt. *; public class Draw. Car { public static void main(String[] args) { Drawing. Panel panel = new Drawing. Panel(200, 100); panel. set. Background(Color. LIGHT_GRAY); Graphics g = panel. get. Graphics(); g. set. Color(Color. BLACK); g. fill. Rect(10, 30, 100, 50); g. set. Color(Color. RED); g. fill. Oval(20, 70, 20); g. fill. Oval(80, 70, 20); g. set. Color(Color. CYAN); g. fill. Rect(80, 40, 30, 20); } }
>>> Example 2 (auf Python) Let’s recreate the Java car example in Python: from drawingpanel import * panel = Drawing. Panel(200, 100) g = panel. get_graphics() g["bg"] = "gray" g. create_rectangle(10, 30, 10+100, 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”)
>>> Example 2 - Parameterized Now, let’s use parameters so that we can place the cars all over the Drawing. Panel.
>>> 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=“cy # main panel = Drawing. Panel(260, 100) g = panel. get_graphics() g["bg"] = "gray" draw_car(g, 10, 30) draw_car(g, 150, 10)
>>> Overview * if else * returns * input
>>> 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. Translator. java 1 // 1 for english 2 // 2 for german 3 int translator = 1; 4 if (translator == 1) { 5 english(); 6 } else if (translator == 2) { 7 german(); 8 } else { 9 System. out. println("None"); 10 } Java < > <= >= == != || && ! python < > <= >= == != or and not Notice: "else if" becomes "elif" translator. py 1 translator = 1 2 if translator == 1: 3 english() 4 elif translator == 2: 5 german() else: print "None"
>>> strings Just like in Java, strings are objects. Lets look at different things that we can do with them: string methods s = "wow" s = "w. Ow" s = "hmmm" s = " ack " s = "w. Ow" s = "wow" s. capitalize() s. endswith("w") s. find("o") s. islower() s. isupper() s. lower() s. startswith("hm") s. strip() s. swapcase() s. upper() => "Wow" => True => 1 => True => False => "wow" => True => "ack" => "Wo. W" => "WOW"
>>> strings as sequences Like arrays in Java, strings have sequence operations zero-based indexes, and we can access parts of them with square s[<index>] brackets instead of using Java's substring() and char. At() methods. s[<start>: <end>] Lets look at things we can do if we have the string s[3] => "c" s[-1] => "g" s[4: ] => "king" s[3: 5] => "ck" s[-3: ] => "ing" len(s) => 8 len(s) s = "shocking" Indexing from the front 0 1 2 3 4 5 6 7 "shocking" from the back -8 -7 -6 -5 -4 -3 -2 -1 example: s[2: -4] => "oc"
>>> return Returns in python are straightforward. Simply "return <value>" instead of "return <value>; " and forget about the types. degrees. py 1 def f_to_c(degrees. F): 2 degrees. C = 5. 0 / 9. 0 * (degrees. F – 32) 3 return degrees. C 4 5 #main 6 temp = f_to_c(68) 7 print ("Temperature is: " + str(temp)) slope. py 1 def slope(x 1, y 1, x 2, y 2): 2 return (y 2 - y 1) / (x 2 - x 1) 3 4 #main 5 slope = slope(0, 0, 5, 5) 6 print ("Slope is: " + str(slope)) 7
>>> 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 = 3. 1415926. . . math. e = 2. 7182818. . Random comes from its own class: import random() math functions ceil(x) fabs(x) floor(x) exp(x) log(x, [base]) log 10(x) pow(x, y) sqrt(x) cos(x) hypot(x, y) sin(x) tan(x) degrees(x) radians(x)
>>> 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. >>> x = input("yes? ") yes? y Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> Name. Error: name 'y' is not defined >>> x = input("yes? ") yes? 2 >>> print x 2 >>> x = input("num? ") num? 2. 0 >>> print x 2. 0 The second way is to use raw_input() which returns The raw_input()` function doesn't evaluate, it will just read whatever you enter. inputs. py 1 name = input("what is your name? ") 2 print(name) 3 name = raw_input("what is your name ? ") 4 5 6 7 8 9 10
>>> Overview * boolean * while * random * tuples
>>> boolean Just like Java, there are boolean values. These values are True and False. True False < > <= >= == != or and not >>> True >>> False >>> 2==3 False >>> "this"=="this" True >>> 2==3 and 4==4 False >>> x = not 1 == 2 >>> x True
>>> while The while loop translates nicely from Java to Python. sentinel. py 1 n = 10 2 # initialize sum and counter sum = 0 3 i=1 4 while i <= n: 5 sum = sum + i 6 i = i+1 # update counter 7 # print the sum 8 print("The sum is", sum) 9 Sentinel. java 1 2 3 4 5 6 7 8 9 10 Scanner console = new Scanner(System. in); int sum = 0; System. out. print("Enter a number (-1 to quit): "); int number = console. next. Int(); while (number != -1) { sum = sum + number; System. out. print("Enter a number (-1 to quit): "); number = console. next. Int(); } System. out. println("The total is " + sum);
>>> random Just like in Java, python also has random object. Here is an example: >>> from random import * >>> randint(0, 9) 1 >>> randint(0, 9) 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
>>> 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> = (value 1, value 2, . . . , value. N) For a point, we only need two values. >>> p = (3, 5) >>> p (3, 5) Creates a tuple where the first value is 3 and the second value is 5. This can represent a 2 D point where the “x” value is 3 and the “y” value is 5.
>>> retrieving tuple values If we wish to use the values in a tuple, we can assign each value to a vairable. >>> p = (3, 5) >>> p (3, 5) >>> (x, y) = p >>> x 3 >>> y 5 This creates two new variables x and y, and assigns the first value in our tuple to x, and the second value to y.
>>> 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(p 1, p 2): (x 1, y 1) = p 1 (x 2, y 2) = p 2 return x 1==x 2 and y 1==y 2 Additionally, we can return tuples. Assume we wanted to add two. This does not make much sense for points, but does for 2 D vectors. def add. Vectors(p 1, p 2): (x 1, y 1) = p 1 (x 2, y 2) = p 2 return (x 1 + x 2, y 1 + y 2) 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.
>>> point distance method # Calculates the distance between two points def distance(p 1, p 2): (x 1, y 1) = p 1 (x 2, y 2) = p 2 dx = abs(x 1 - x 2) dy = abs(y 1 - y 2) return sqrt(dx * dx + dy * dy)
- Slides: 139