Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Math 503: Cryptography Fall 2016 Python tutorial Prof. Shahed Sharif 1 Getting started We’ll be using Python 3 in this class. You can install it on your own computer from https://www.python.org/getit/, or use the online service http://repl. it/languages/python3. There are many applications available for working with Python. In this tutorial, we will be using IDLE, a simple development environment which comes bundled with Python. Feel free to choose your own application; for example, PyCharm is a popular choice. Before we dive into coding, let’s review the basics of programming in general. 2 Basics of programming What a computer program does—and by extension, how we understand computer programming—can be divided up into five parts: I/O. This stands for “input/output”. That is, the program will often ask for some information from the user (input), and at some point will display results (output). This can be very complicated if, for example, your program is a video game. For us, I/O will be very simple. Arithmetic. Programs can do arithmetic. This means the 4 standard arithmetic operations. In this class, we will frequently deal with bit strings; that is, sequences of 1s and 0s. There are additional operations specific to these that we’ll also need. Data. A program stores and manipulates data. Data is, broadly, stored in variables, of which there are a number of different types. A program can change the content of a variable, and also read the contents of a variable. Booleans. A program can determine the truth or falsity of certain types of statements. A Boolean value is essentially either “true” or “false”, and a Boolean function is something that inputs a bunch of statements and, based on the truth of those statements, outputs a Boolean value. Control flow. Control flow refers to the order in which the computer executes commands. One way of looking at this is that control flow instructs the computer what it should do next. The most important part of control flow is iteration; that is, doing the same or similar tasks or calculations repeatedly. Computers are much better suited to iteration than humans! 1 of 10 Python tutorial Math 503: Cryptography Fall 2016 2.1 Putting the parts together Any algorithm can be put together out of these constituent parts. When writing a program, your first task should be to figure out how to write your algorithm out of these parts. You should do this away from the computer! Once you’ve done that, let’s look at how the various parts of a computer language are implemented in Python. 2.2 Writing programs in IDLE When you first open IDLE, the window is an interpreter shell.1 While you can write longer programs in the shell, the main purpose of the shell is to enter short, usually one-line commands. In the following, you should type each line followed by the Enter key, and try to figure out why you get whatever output Python gives you. I encourage you to experiment with you own commands. Also note that some of these commands will give errors. See if you can figure out why! 3 Arithmetic 5+3 5-3 5*3 5*(2+3) 5/3 5//3 Exercise 1: Without entering it into Python, guess the value of 9*(100//9). Then check your answer. Again, I encourage you to try variations. Here are some more useful operations; see if you can determine what they do: 2**3 17%5 ord(’A’) chr(65) bin(4) bin(5) 1 In repl.it, this is the dark right-hand window. 2 of 10 Python tutorial Math 503: Cryptography Fall 2016 4 Data There are three basic data types we’ll discuss: numbers, strings, and lists. There are actually two types of numbers: integers and decimals (or “floats”). We’ll mainly work with integers. x=5 x print(x) x+3 x,y = 3,5 y y=y+1 y Note that = denotes assignment; that is, the expression on the right is evaluated, then assigned to the variable on the left. x=3 x=x+1 x x=x*3 x y=7 x,y=y,x x y A string is just a sequence of characters, such as a text message. Strings are enclosed in quotes; either single or double-quotes are fine for simple cases. There are subtle differences between them which are relevant in more complex situations. x=’hi’ x print(x) print(’x’) y=’ there’ z=x+y print(z) x=’3’ x+1 x+’1’ You’ve already seen how to convert integers into binary. You can also set a variable to a binary number by starting the number with 0b.2 2 Octal and hexadecimal work similarly: use 0o and oct for octal, and 0x and hex for hexadecimal. 3 of 10 Python tutorial Math 503: Cryptography Fall 2016 x=0b1001 x bin(x) x.bit_length() w=’0b0111’ bin(w) y=int(w,2) y.bit_length() Note that if binary numbers are specified as strings (as in the first w line above), then one would need to use int(·,2) to convert into an honest-to-goodness number. Binary numbers come equipped with some basic operations. See if you can figure out what these do. bin(x << 2) bin(x << 5) bin(x >> 1) bin(x^y) bin(y^y) One warning: negative numbers are funny in binary, so you should avoid them. Lists are finite sequences of other data types. They are like arrays, except their length can change. Entries of a list can be numbers, strings, or even other lists. lst=[1,2,’apple’] lst[0] lst[2] len(lst) lst[len(lst)] lst[len(lst)-1] lst[-1] lst[1:2] lst[1:3] lst[1:] lst[:2] m=lst+lst m As you can see, list operations are mostly very intuitive. We refer to entries of a list by their index, which starts at 0. Some list operations can be used with strings. s=’hell’ s=s+’o’ s 4 of 10 Python tutorial Math 503: Cryptography Fall 2016 s[1] ’j’+s[1:] s[-1] The output of bin is actually a string, so if you would like to figure out the last binary digit of x, you’d do bin(x)[-1]. There’s much more to say about lists, and I’d strongly recommend doing some further reading on them. Exercise 2: Type x=’A’. Write a single command that converts x into the binary number representing its ASCII value. 5 Booleans We start with a single variable assignment (x = 3) and proceed with some truth tests and more complex boolean functions (such as AND and OR). Note the difference between = and ==. x=3 x==3 x==2 x<3 x<4 x!=4 x!=3 x==3 and x<4 x==3 and x<2 x==3 or x<2 not (x==3 or x<2) not x!=4 x=’hi’ x+’ there’==’hi there’ One handy trick that comes up when using control structures is that 0 and [] are equivalent to False, while all other values are considered True. 6 Control flow In the rest of this document, we’ll be entering multi-line commands. Use Enter to get a new line, as usual, but now pay attention to colons and indentation! Press Enter on a blank line to execute. Here’s a simple loop: for i in range(10): print(i) 5 of 10 Python tutorial Math 503: Cryptography Fall 2016 Observe the colon and indentation! If you typed the first line correctly, IDLE will automatically indent properly. If you ever need to dedent, just use backspace. What this does is start i at the value 0, execute the indented code, then increment i to the next value, 1. This continues until i hits the last value below 10; that is, 9. Incidentally, i is called the index for the loop. In mathematical programs, we usually use an additional variable within a loop which calculates something. For example, if we wanted to compute 1 + 2 + · · · + 9, we could do it as follows: sum = 0 for i in range(1,10): sum = sum + i sum (That last line could have been print(sum).) Note that here, range has two arguments: a start value and an end value. The start value is used in the loop, but the end value is not. Another way of making loops is with while. i=1 sum=0 while i<10: sum = sum + i i = i + 1 sum This executes the loop (the two indented lines) until the Boolean i < 10 is false. Exercise 3: What happens if you do the same program, but with the two indented lines reversed? Guess first, then try it! A common construction is to combine creating, reading, or changing a list with a loop. In the case of a for loop, we might use range(len(list)). The last control structure is the if/else declaration. Try to guess what happens with the next four lines before trying it out. if i%2==0: print(i, ’is even’) else: print(i, ’is odd’) The else is optional; that is, the last two lines could have been omitted. However, while there would be no error, the above lines would do something different for certain values of i! Exercise 4: Print the first 20 binary numbers using both a for loop and a while loop. (That is, do it twice.) Exercise 5: Compute 1 + 2 + 3 + · · · + 100 using both a for loop and a while loop. 6 of 10 Python tutorial Math 503: Cryptography Fall 2016 Exercise 6: Print the characters corresponding to the even ASCII codes between 50 and 100. (Hint: use an if statement.) 7 Functions and syntax We now figure out how to put everything together to write a program. As an example, we’ll recreate multiplication of positive integers; that is, given positive integers a and b, we want to write a program which outputs the product of the two using only addition. 7.1 Writing down the algorithm The first step should be done on paper! This step constructs the algorithm in plain English. We write down what we want: 1. Given positive integers a, b. 2. Write down a on a paper b times. 3. Add together. Okay, not too bad. However, this doesn’t use any of the constructions of computer algorithms, specifically loops. Note that the second step is an iterative step; thus, we should use a loop. One can use for or while; for this example, I will use while. 1. Input positive integers a, b. 2. Start a running total at 0. (a) Add a to our running total. (b) If we’ve done this b times, stop. Otherwise, repeat. 3. Output the running total. Notice that we’ve introduced two new quantites: the running total, and the number of times we’ve been in the loop. The first quantity we can call p for product, while the second quantity is a counter related to b. The counter can start at 0 and work its way up to b, or can start at b and count down to 0. I will choose the latter, for reasons that will become apparent. The key observation is that the termination condition for the loop is that the counter, whatever we call it, equals 0. 7.2 Typing up the program To type up actual programs, you’ll use a text window instead of the IDLE shell. Go to the File menu and click “New file.” In the resulting window, type in the 7 of 10 Python tutorial Math 503: Cryptography Fall 2016 program. When you are done, save, go to the Run menu, then click “Run module” (or just hit F5). Your program should then execute in the original window, the IDLE shell.3 Now for the program itself, you may have noticed that all flow commands end in a colon, and all instructions inside it are indented. The same formalism holds for functions, as you can see below. def dumb_multiply(a,b): ”””Multiply positive integers a and b.””” p = 0 while b!=0: p,b = p+a, b-1 return p Note that our counter is b itself! To understand how the program works, I recommend choosing small values of input and try executing the program yourself, on a piece of paper (not with the computer). Once you’ve typed the above and run it, you’ll have defined the function dumb_multiply as a function of two arguments. Now switch back to the shell window and type dumb_multiply(5,8) Note that the program ends with a return statement. Run on its own, return acts just like print. However, return is superior because the output of return can be used as the input of another program. Indeed, complex programs are typically split into pieces, where one function will call the results of another. Note however that a return statement, unlike print, ends the enclosing function immediately. Lastly, the variables a and b are localized, so even though their values are changed inside the function, they are not changed outside of the function. That is, if we did a=18 b=15 dumb_multiply(a,b) b then the value of b is still 15, even though the value of b appears to change inside dumb_multiply. Exercise 7: Write a new version of dumb_multiply which uses a for loop. Exercise 8: Write a program which takes a string as input and outputs that string reversed. That is, ’11010’ would become ’01011’ and ’Python’ would become ’nohtyP’. (Hint: use x[-i].) 3 In repl.it, use the left window. When ready, click the “Run” button. 8 of 10 Python tutorial Math 503: Cryptography Fall 2016 Exercise 9: Write a program which takes a binary number as input and outputs a binary number with all of the bits flipped. That is, 0b11010 would become 0b00101 and 0b1001 would become 0b0110. 8 8.1 Good practices Comments and doc strings Any text beginning with the hash symbol # is considered a comment; that is, it is ignored by Python. This is good to explain your program to someone else reading your code, or more importantly, yourself in a few weeks when you are reusing some code! Look at the second line of the dumb_multiply function above. The text inside the triple quotes is called the doc string for the function. It provides a brief description of the function, and is always a good idea to include. Here’s the dumb multiplication function with lots of comments: def dumb_multiply(a,b): ”””Multiply positive integers a and b.””” p = 0 # p will be the product while b!=0: # loop by decrementing b p,b = p+a, b-1 return p # we’re done with the program. Champagne time! 8.2 Bite-sized pieces For long, complicated programs, break up the problem into several pieces and program them separately. As a simple example, suppose you want to input the lengths of two legs of a right triangle, then compute the sine of the smallest angle. You could do this in pieces as follows: def hypotenuse(a,b): ”””Compute the hypothenuse of a right triangle. Legs have length a and b.””” return (a**2 + b**2)**(0.5) def triangle_sin(a,b): ”””Compute sine of smallest angle of right triangle. a, b are lengths of legs.””” c = hypotenuse(a,b) if a<b: return a/c else: 9 of 10 Python tutorial Math 503: Cryptography Fall 2016 return b/c 8.3 Debugging with print If your program isn’t giving the right output and you’re not sure why, one thing you can do is insert print statements inside your program, usually inside loops. Take the following example: def dumb_multiply(a,b): ”””Multiply positive integers a and b.””” p = 0 while b!=0: p,b = p+b, b-1 return p This program will not correctly compute the product of two numbers. (Try it!) Not obvious why? Try doing it like this: def dumb_multiply(a,b): ”””Multiply positive integers a and b.””” p = 0 while b!=0: p,b = p+b, b-1 print(a,b,p) # This helps us see what the program is doing return p Then you’ll see the values of the variables as the program iterates, and hopefully understand the problem. 8.4 Turning in programs When turning in programs as part of your homework, you should do the following: • Print out the program, preferably in a fixed-width font like Monaco. Make sure the program is appropriately commented! • Print out relevant output of the program. • Explain any functions from previous assignments. 9 Further reading This document is only meant to get you started. I encourage you to look online for more details on programming in Python! I’d especially suggest looking into lists (particularly list comprehension), printing, and the dictionary data type. 10 of 10