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
Programming Seminar 2009 Night 0 Why we’re holding this seminar • You’re probably not a computer science major – Or even anything remotely close (e.g. EE) • We think that programming is an important skill – Useful (sometimes) – Interesting (often) • This will be a combination of practice, theory, and examples. What I’m assuming about you • You have (almost) no experience writing code of any sort. • The words [“syntax”, “variable”, ”function”] might mean something. – If you took certain math or linguistics courses. • The methodology for building a program (or parts of it) is somewhat mysterious So what is a “program” anyway? • A number • A set of instructions and data – For a computer to execute • Human-readable source code – Readable for some humans, anyway • A (hopefully) consistent way to accomplish some task Enter Python • Python is a new, friendly, language with an amazing library of functionality • Most of the text is English, with a few abbreviations and some other characters • We will be using Python 3 – Unless the computers really don’t want to, in which case we will be using Python 2.6 • Or in the case they don’t have that either, Python 2.5 Let’s get started! • The first item for action is running the Python interpreter. – Or perhaps IDLE, a Python IDE • You can do this by finding Python in the system menu, or by starting a terminal and typing “python” • If you see a line beginning with >>>, you are fine. • All together? Good. As tradition dictates… • Type >>> print(“Hello World!”) • And Python prints “Hello World!” to the console window. – Don’t you feel accomplished? • Here’s what you’ve learned: >>> print(“(something)”) prints (something) • You can put two strings together with + On Statements • In general, code falls into one of four categories: – Declaration – saying that something exists – Assignment – telling the program to remember a value – Definition – detailing how something works – Control – ordering the program what to do next Assignments • Try telling Python >>> sentence = “Arma virumque cano” >>> print(sentence) • This does exactly what you might expect >>> print(“Arma virumque cano”) • Both print the first few words of the Aeneid – If you didn’t expect this, what did you expect? • Every time I say you might have expected something, please speak up if you didn’t! Assignments, continued • Try >>> x = 3 >>> print(x * x) – You might have guessed that this prints the number 9 to the console • What do you think these lines do? >>> x = 4 >>> y = 3 >>> print(x * y – (x + y)) So Python can do math… • Congratulations! Your computer can be used as a (very expensive) calculator. • Most arithmetic operators make sense –+-/* – This works for real numbers (e.g. 1.56), as well. • Quick! What is 1234*9876? …But programming math is (generally) not real math • If you say “x = 5” when proving that the natural numbers are in bijection with the rationals, x is always 5. • In Python (and most other programming languages) >>> x = 5 >>> x = 6 >>> print(“x = “ + x) prints 6 Assignment is storage • Remember when I said that assignment tells the program to remember a value? >>> x = 5 tells Python “x has the value 5” – And x holds the number 5 • But this value can change. >>> x = x + 1 increases the value of x from 5 to 6. Wait – what!? • x = x + 1 doesn’t even make sense! – Subtract x from both sides and you get 0 = 1. • But remember, programming “math” is not math • x = x + 1 can be read – “Increment x by 1” – Find the value I previously assigned to x. Add 1 to it. Now assign the new value to x. Other ways to assign >>> word = “coconut” tells Python to remember that word represents the value “coconut” • Which variables represent what ? – What is the output? >>> >>> >>> >>> pi = 3.14 radius = 5 area = pi * radius * radius print(area) So what good is any of this? • It gets a little more interesting when we have user input • We do this with the input() function. – In previous versions it was raw_input() • We can make programs interactive! >>> name = input(“What is your name?”) >>> print(“Hello, ” + name + “!”) Okay, but no program I’ve even used does only one thing every time I run it • Good point. • Enter Control statements • Conditional execution: – If condition is true, do something, otherwise do something else – While condition, do something, and continue to do that something until condition is false. – For each item in a collection, do something If statements >>> number = int(input(“Enter a number: ”)) >>> if number > 0: >>> print(“A square with side length”, number, “ has area ”, number * number) >>> else: >>> print(“I need a positive number!”) The general format is if condition: do_something() else: do_something_else() For statements >>> for item in (2,3,5,7,11,13): >>> print(item * item, “ has and odd number of factors.” ) • The general form is for var in collection: do_something() A few more examples… >>> limit = int(input(“Give me an upper limit: ”)) >>> if limit < 0: >>> print(“Too low!”) >>> elif limit > 50: >>> print(“Too high!”) >>> else: >>> for i in range(limit): >>> print(i, “squared is ”, i*i) …examples >>> sentence = input(“A sentence, please”) >>> words = 1 >>> for c in sentence: >>> if c == ‘ ’: >>> words = words + 1 >>> print(“The sentence you entered had”, words, “words”) Your turn! • Write a program to count the number of vowels in a sentence which the user inputs • Write a guessing game that gives the player 5 chances to guess a number correctly – We will make the number’s selection random later • Write a simple calculator; that is, a program which asks for two numbers and whether it should add, subtract, multiply, or divide them. The program should then output the calculation and its result. More about modules • As previously stated, Python has an extensive, useful library of functionality • Some of this functionality is included by default – E.g. abs(), print(), range(),… • The rest is in a number of modules – Math-related stuff is in the math module. >>> >>> import math print(math.sqrt(5)) Modules, continued • Can also import specific functions >>> import cos from math >>> from math import atan • There is a module for almost everything – Want to enter passwords? Import getpass – Want OS functionality? Import os, sys – Want to handle options passed on the command line? Import optparse On Functions • Certain pieces of code that are used repeatedly in a succinct fashion • Input(), split(), abs(), print() • Functions run specified code every time we “call” them. Programming is not Math, revisited • Programming functions are not like math functions! – The return value can change • Input() rarely returns the same result – Functions often do some action each time we “call” them • Print() prints output to the screen – We don’t evaluate functions, we “call” them to do their job Defining a Function >>> def name(arguments): >>> …actions… • Here is an example: >>> def square(n): >>> print(n*n) Your turn, once more • Create a function that will print a row of n stars (*), with n passed as an argument • Use this function to create a function that will print an isosceles right triangle of stars • Write a function fib(n), which prints the nth Fibonacci number. The first and second Fibonacci numbers are both considered to be 1 – Do not use recursion, if you know what it is.