This preview has intentionally blurred parts. Sign up to view the full document

View Full Document

Unformatted Document Excerpt

Elements CS313E: of Software Design Basic Python Dr. Bill Young Department of Computer Sciences University of Texas at Austin Last updated: October 9, 2012 at 13:10 CS313E Slideset 2: 1 Basic Java Acknowledgement Much of the material in this introductory slideset is from Dr. Shyamal Mitra, and used with his blessing. CS313E Slideset 2: 2 Basic Java Introduction to Python Python is a simple but powerful scripting language. It was developed by Guido van Rossum in the Netherlands in the late 1980s. The language takes its name from the British comedy series Monty Pythons Flying Circus. Python is an interpreted language unlike C or Fortran that are compiled languages. Clean syntax that is concise. You can say a lot more with fewer words. Design is compact. You can carry all the language constructs in your head. There is a very powerful library of useful functions available. This means that you can be productive quite easily and fast. You will be spending more time solving problems and writing code than grappling with the idiosyncrasies of the language. CS313E Slideset 2: 3 Basic Java Running Python: Interactively There are several ways to run Python. One is to start Python and run programs in the interactive loop. > python3 >>> print ("Hello World!") Hello World! This uses the read-execute-print loop. 1 Read in a legal Python form. 2 Execute the form. 3 Print the result to standard output. 4 Go to step 1. CS313E Slideset 2: 4 Basic Java Running Python: From File For longer programs you can store your program in a le that ends with a .py extension. Example: saved in a le called Hello.py is the single statement: print ("Hello World!") To run your program, type at the command line > python Hello.py You can also create a stand alone script. On a Unix / Linux machine you can create a script called Hello.py containing the following lines (assuming thats where your Python implementation lives): #!/lusr/bin/python print ("Hello World!") CS313E Slideset 2: 5 Basic Java Running Python: From File Lets try running this: > Hello.py Hello.py: Permission denied. What went wrong? Before you run it, you must tell Linux that its an executable le: > chmod +x Hello.py Then run it: > Hello.py Hello World! CS313E Slideset 2: 6 Basic Java Structure of a Computer Language Character set Variables Types Operators Assignments Conditionals Loops Functions Arrays Input / Output CS313E Slideset 2: 7 Basic Java Basic Syntax: Character Set Python uses the traditional ASCII character set. Recent versions also recognize the Unicode character set. The ASCII character set is a subset of the Unicode character set. Python does not have a separate character type. A character is represented as a string containing one item (e.g., "a"). CS313E Slideset 2: 8 Basic Java Identiers Python is case sensitive. These are rules for creating an indentier: Must start with a letter or underscore ( ) Can be followed by any number of letters, digits, or underscores. Cannot be a reserved word. Python reserved words are: False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, nally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield. CS313E Slideset 2: 9 Basic Java Variables A variable in Python denotes a memory location. In that location is the address where the value is stored in memory. Consider this assignment: x=1 A memory location is set aside for the variable x. The value 1 is stored in another place in memory. The address of that location is stored in the memory location denoted by x. This simple observation explains a lot about Python. CS313E Slideset 2: 10 Basic Java Variables and Values The values stored in variables are pointers (addresses). Thats why Python variables are untyped. Thats why its OK to assign a value of another type to x. If you later re-assign x: x = 2.75 the value 2.75 is stored in another memory location; its address is placed in the memory location denoted by x and the memory occupied by the value 1 may be reclaimed by the garbage collector. CS313E Slideset 2: 11 Basic Java Type Examples >>> x = 1 >>> type(x) <class int> >>> x = "abc" >>> type(x) <class str> >>> print (type(2.75)) <class float> >>> import math >>> print (type (math)) <class module> CS313E Slideset 2: 12 Basic Java Types in Python Is it correct to say that there are no types in Python? Yes and no. It is best to say that Python is dynamically typed. Variables in Python are untyped, but values have associated types which are actually classes. In some cases, you can convert one type to another. Most programming languages assign types to both variables and values. This has its advantages and disadvantages. Can you guess what the advantages are? CS313E Slideset 2: 13 Basic Java Mutable and Immutable A mutable type contains values that can be changed by the program. An immutable type cannot be changed. For example, the Python string type str is immutable. You can extract parts of a string, append it to another string, and perform various operations on it. But you cant change it. There are no operations that allow you remove the rst character or swap one character for another in a string. If you want to do that, you create a new string. new_string = old_string[1:] A list is an example of a mutable type; you can remove an item and still have the same list. CS313E Slideset 2: 14 Basic Java Mutable vs. Immutable Consider a list (mutable) versus a tuple (immutable). CS313E Slideset 2: 15 Basic Java Types in Python Type str Description An immutable sequence of characters. In Python 3 strings are Unicode by default. bytes An immutable sequence of bytes int An immutable xed precision number of unlimited magnitude An immutable oating point number (system-dened precision) An immutable complex number with real number and imaginary parts An immutable truth value Immutable, can contain mixed types Mutable, can contain mixed types Mutable, unordered, no duplicates A mutable group of key and value pairs oat complex bool tuple list set dict CS313E Slideset 2: 16 Basic Java Syntax example Wikipedia Wikipedia Spanning multiple lines bSome ASCII bSome ASCII 42 3.1415927 3+2.7j True, False (4.0, string, True) [4.0, string, True] {4.0, string, True} {key1: 1.0, 3: False} Operators: Arithmetic Operators These are the arithmetic operators that operate on numbers (integers or oats). The result of applying an arithmetic operator is a number. Addition: + Subtraction: Multiplication: Division: / (use // for integer division) Remainder: % Exponentiation: CS313E Slideset 2: 17 Basic Java Relational Operators Python has 6 comparison operators. The result of applying the comparison operators is a Boolean: True or False. Equal to: == Not equal to: != Greater than: > Greater than or equal to: >= Less than: < Less than or equal to: <= You may apply the comparison operator between two operands, e.g., (a > b), or in sequence like so (a > b > c). But this is not recommended. CS313E Slideset 2: 18 Basic Java Boolean Operators Python has two Boolean literals: True and False. But Python will also regard any of the following as False in a Boolean context: the number zero (0), the empty string (), the reserved word None. All other values are interpreted as True. What does the following code do? x=5 while x: print (x) x -= 1 CS313E Slideset 2: 19 Basic Java Boolean Operators There are 3 Boolean operators: not: unary operator that returns True if the operand is False and vice versa. x and y: if x is False, then that value is returned; otherwise y is evaluated and the resulting value is returned. x or y: if x is true, then that value is returned; otherwise y is evaluated and the resulting value is returned. Returning a value before all arguments are evaluated is called short circuit evaluation and can be very useful. if ( y != 0 and x / y > 0 ): print ( x / y ) CS313E Slideset 2: 20 Basic Java Assignments A variable can be assigned the value of a literal or expression. a b c d e f = = = = = = 1 2.3 False 5L 8 + 6j "Hello" # # # # # # 1 is an integer literal 2.3 is a floating point literal False is a boolean literal 5L is a long integer literal 8 + 6j is a complex literal "Hello" is a string literal Recall what actually goes into the variable! What do you think happens in each of these cases? An expression is composed of variables and operators. An expression is evaluated before its value is used. Python allows for multiple assignments at once. x, y = y, x CS313E Slideset 2: 21 Basic Java Conditionals In Python, a conditional allows you to make a decision. You can use the keyword elif that is a contraction of the words else and if. if (cond1): ... elif (cond2): ... else: ... The body of if, elif, and else parts need to be indented. CS313E Slideset 2: 22 Basic Java Conditional Example def letterGrade(score): if score >= 90: letter = A elif score >= 80: letter = B elif score >= 70: letter = C elif score >= 60: letter = D else: letter = F return letter CS313E Slideset 2: 23 Basic Java Loops The loop constructs of Python allow you to repeat a body code several of times. There are two types of loops: denite loops and indenite loops. You use a denite loop (for loop) when you know a priori how many times you will be executing the body of the loop. You use an indenite loop (while loop) when you do not know a priori how many times you will be executing the body of the loop. To write an ecient loop structure you must ask yourself these questions: Where do I start? When do I end? How do I go from one iteration of the loop to the next? CS313E Slideset 2: 24 Basic Java While Loops Syntactically the simplest loop construct is the while loop. while (cond): ... loop_body ... What is the semantics of this construct? I.e., what does this really do? CS313E Slideset 2: 25 Basic Java While Example def count_down(n): if n < 0: print(Youre trying to fool me!) return while n > 0: print (n) n -= 1 def ask_ok(prompt, retries=4, complaint=Yes or no, please!): while True: ok = input(prompt) if ok in (y, ye, yes): return True if ok in (n, no, nop, nope): return False retries = retries - 1 if retries < 0: print("What a loser!") break print complaint CS313E Slideset 2: 26 Basic Java Range When dening loops, a useful construct is range. You can think of range(10) as returning the list [0, 1, 2, ..., 9]. Thats what it does in Python 2. In Python 3, it creates an iterator, a function to return successive values in that list as needed. >>> range(10) range(0, 10) >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) [] CS313E Slideset 2: 27 Basic Java For Loops A denite loop requires a loop counter which takes on a series of values. Example: write a loop that executes the body 10 times. for i in range (10): ... loop_body ... The loop counter i goes through the values 0 through 9 as the loop iterates. We can also specify the beginning and ending value of i. for i in range (3, 15): ... loop_body ... What values does i take on in this loop? CS313E Slideset 2: 28 Basic Java For Loops We can also specify the step size for the loop counter. for i in range (1, 10, 2): ... loop_body ... What values will i take on here? How would you process the sequence backwards? You can also enumerate a sequence of values for the loop counter. for i in [7, 4, 18, 12]: ... loop_body ... CS313E Slideset 2: 29 Basic Java For Example What does the following code do? def printStringExploded(symbolString): for c in symbolString: print(c, end=" ") print() def compressExplodedString(explodedString): for c in explodedString: if c != " ": print(c, end="") print() printStringExploded("abcdefg") compressExplodedString("a b c d e f g") CS313E Slideset 2: 30 Basic Java Functions A function is an encapsulation of some functionality. Functions can be called at the top level or from within another function (or itself). A function may or may not return a value or values. The structure of a function denition is as follows: def function-name ([formal-parameters]): ... body-of-the-function ... The function-name is an identier. You can have zero or more formal parameters, but must have the parentheses. CS313E Slideset 2: 31 Basic Java Functions The formal parameters are placeholders that accept values sent to it from the calling function. When a function is called, the parameters that are passed to it are called actual parameters. For a complete list of built-in functions see: docs.python.org/library/functions.html. CS313E Slideset 2: 32 Basic Java Function Examples def addTwo (a, b): return a + b def divide (a, b): return a / b, a % b def isEven (x): return (x % 2 == 0) def gcd (m, n): while (m != n): if (m > n): m=m-n else: n=n-m return m CS313E Slideset 2: 33 Basic Java Function Examples (2) def coPrime (a, b): if (gcd(a, b) != 1): return else: print "%0d and %0d are co-prime" % (a, b) def main(): x=2 y=3 z = addTwo (x, y) p, q = divide (x, y) if (isEven(z)): print z coPrime (x, y) main() What does this program do? CS313E Slideset 2: 34 Basic Java User-Dened Functions To call a user dened function that is in the same program you simply call it by name without using the dot operator. If the function does not return a value, then call it on a line by itself. If it returns values then assign those return values to variables. CS313E Slideset 2: 35 Basic Java Import Modules A module is basically a le containing Python code. You can import the module in le modulename.py using the syntax: import modulename Many useful functions reside in pre-dened modules that must be imported before you can use them: string, math, random, etc. import string import math, random After importing the module, call on the functions using the module name and dot operator. x=7 y = math.sqrt (x) z = random.random() CS313E Slideset 2: 36 Basic Java Import vs. From Module Import Note that import module only adds the module name to the namespace. To use any function from that module, you need to qualify it. import math x = math.sqrt( 10 ) y = math.pi - 2 To add specic function names from the module, you can also do: from module import f1, f2, ..., fk In this case, the names are in the local namespace and dont need qualifying. from math import pi, sqrt x = sqrt( 10 ) y = pi - 2 CS313E Slideset 2: 37 Basic Java From Module Import * If you need all of the names from the module you can also use: from module import * Many folks believe that its not generally good to do this because your program may be harder to modify. from math import * x = sqrt( 10 ) y = pi - 2 Its not clear that pi and sqrt were dened in the math module. CS313E Slideset 2: 38 Basic Java Lists in Python The analogue of an array in Python is a list. A list is heterogenous and dynamic. What does that mean? The size is not specied at creation and can grow and shrink as needed. Python provides built-in functions to manipulate a list and its contents. There are several ways in which to create a list: enumerate all the elements create an empty list and then append or insert items into the list. CS313E Slideset 2: 39 Basic Java Lists in Python # Enumerate the items a = [1, 2, 3] # Create an empty list and append or insert a = [] a.append(1) # a = [1] a.append(2) # a = [1, 2] a.insert(1, 3) # a = [1, 3, 2] # Create a two dimensional list b = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] CS313E Slideset 2: 40 Basic Java Lists in Python (3) To obtain the length of a list you can use the len() function. a = [1, 2, 3] length = len (a) # length = 3 The items in a list are indexed starting at 0 and ending at index length - 1. You can also slice a list by specifying the starting index and the ending index and Python will return to you a sub-list from the starting index and upto but not including the end index. a = [1, 9, 2, 8, 3, 7, 4, 6, 5] b = a[2:5] # b = [2, 8, 3] CS313E Slideset 2: 41 Basic Java Lists in Python (4) One of the most important operations that you can do with a list is to traverse it, i.e. visit each element in the list in order. There are several ways in which to do so: a = [9, 2, 6, 4, 7] for item in a: print (item, end = " ") #92647 Other useful functions to sort, reverse, etc. lists are here: docs.python.org/release/3.1.3/tutorial/datastructures.html CS313E Slideset 2: 42 Basic Java Input and Output Python 2 has input and raw input functions. Python 3 has only input, which works like raw input in Python 2. That is, it always returns a string value. You can prompt the user to enter a string using the function input(). The function then waits for the user to enter the value and reads what has been typed only after the user has typed the Enter or Return key. n = input ("Enter a number: ") CS313E Slideset 2: 43 Basic Java Input and Output The print command allows you to print out the value of a variable. If you want to add text to the output, then that text has to be in single or double quotes. Print takes an arbitrary number of arguments separated by commas, and prints them separated by spaces. print (n = , n, end=" ") print ("name = ", name) Assuming n contains the string abc, what does the above print? CS313E Slideset 2: 44 Basic Java Input and Output An optional end argument allows specifying how to nish the print. The following are equivalent: print (n = , n, end="\n") print (n = , n) To suppress the newline, provide an explicit alternative. print("1"); print ("2") 1 2 print("1", "2") 12 >>> print("1", end=""); print("2") 12 CS313E Slideset 2: 45 Basic Java Input and Output An optional sep argument species what is printed between elements of a list: print (n = , n, sep=" ") print (n = , n) To suppress the space, provide sep="", or supply another alternative. >>> print("1", "2") 12 >>> print("1", "2", sep="") 12 >>> print("1", "2", sep="%") 1%2 >>> CS313E Slideset 2: 46 Basic Java ... View Full Document

End of Preview

Sign up now to access the rest of the document