You are on page 1of 12

Python is a very powerful and flexible programming language and is said by many to be the easiest to learn.

You can write anything from simple scripts to full-fledged games and applications. An editor - Python comes bundled with IDLE, a very good editor to start with as you can use it as a command line or full editor, also you can run your programs straight from it just by hitting F5. I recommend starting with IDLE and branching out from there. In command prompt mode enter: print "Hello, world!" Output is: Hello, world! Exciting stuff. Now lets make that into a program. In your editor type the same thing (IDLE users go to File, then New, type your program in and hit F5 to run your program, it will ask you to save. Make sure you add a .py extension at the end). If you have decided not to use IDLE: Linux, unix, or dos users - save your program with a .py extension, and then go into the directory containing the program. type python filename.py Window users- Save your program with a .py extension and then go into My Computer or Windows explorer and find your file. Right click on that file and go to Open With. If python is on that list select that, otherwise go to browse, then to the directory python is in. Select python.exe.(Note: If you run the above program this way, it will probably just flash on screen really fast, your other option is to go into command prompt(dos)) So whats going on in this program? Very simple. We use the print command to output our text string to the screen. A string is just what it sounds like. A line of characters that are grouped together. In this case with quotation marks. Be aware that you can use " " or ' ' . Lets try another one. If you want you can write over your first program, or you can save them all for reference. print "Hello world! " * print "Goodbye!" Output: Hello world! Hello world! Hello world! Goodbye! The first line in this one you see something new, the '*' operation. '*' means to multiply. Notice I used a couple spaces after Hello world! in the quotation marks. If I hadn't, the output would've been: Hello world!Hello world!Hello world! Also notice that "Goodbye!" automatically outputs on the next line.If you want to add new lines from the same print command use \n in the quotation marks. For example in our previous program change the first line to look like this: print "Hello world!\n" * 3 Output being: Hello world! Hello world! Hello world! USING NUMBERS: While outputting numbers, they need not go in quotation marks. Numbers in quotation marks act just like text. While without the quotation marks you can use math functions and operators. For example, in your command prompt type in this: print "1" + "1" now type: print 1 + 1 3

Your first output should have been 11 and your second one should have been 2. What happened in the first example was you just added the two "strings" together. In the second one you actually added the numbers together. Keep in mind you cannot add a string and a number. Try this program. print "1 plus 1 =", 1 + 1 print "20 divided by 2 =", 20 / 2 print "100 minus 45 =", 100 - 45 print "64 times 2 =", 64 * 2 print 2 + 100 / 2 Output: 1 plus 1 = 2 20 divided by 2 = 10 100 minus 45 = 55 64 times 2 = 128 52 This is program is pretty self explanatory, but there are a few things to clear up. the comma automatically adds a space. Also, on the last line, notice that python divided before adding. In python, mathematics are done the same way as in real life. If you wanted to add before dividing, you would simply use parenthesis: (2 + 100) / 2, output: 51 The order of operations is as follows: Parenthesis Exponent/Square Root Multiply/Divide Add/Subtract The operation symbols are: ** * / % + Exponent (i.e 5 ** 3 = 125, which is 5 * 5 * 5) Multiply Divide Remainder (i.e 7%2 = 1, because 7/2 is 3, with the remainder being 1) Add Subtract

Practice

Writing your own programs helps you with problem solving and to think like a programmer. At the end of each chapter I will give you a few programs to write. Hopefully we can cram all this info into your head! :-) 1. Write a program that produces the following output using the mathematic operations mentioned above: Welcome! Welcome! Three times three plus six is 15 What is 8 times 8? 64 2. Write a program that uses at least 3 of the above operators to come up with the number 2 Variables A variable is basically just a storage place to put your numbers and strings. You can use variables just as if they are regular numbers or strings, and even create new variables with them. To use them type the name of the variable first, then "=" then what you are assigning Example: a=1 b=2 c = "My new number is:" d=a+b print "a is", a print "b is", b print c, d b=1 print c, d Output: a is 1 b is 2 My new number is: 3 My new number is: 3 What's going on? We have assigned the number 1 to a, the number 2 to b, and the string "My new number is:" to c. In d, we assigned the value of a plus the value of b. Notice that the value of d doesn't change after we changed the value of b in line 8. d actually holds the number 3, it doesn't hold a and b. Another example: a=3 b=1 print a, b a=b print a, b Output: 31 11 The first three lines should be obvious. Let's take a closer look at the 4th line. When we called a = b we assigned the value of b into a, making the output '1 1'. The order is very important. Had we called b = a this would have made the value of each 3. Just remember left side is the storage, right side is the assignment. It is also possible to assign the same value to more than one variable: a = b = c = 50 which is the same as:

a = 50 b = 50 c = 50 Practice 1. Make a variable for the string "My favorite number is: ". Make a variable with any number. print the output. 2. Add on to the first program by making another variable with the value of. Make your output My favorite number squared is: (your # squared). Make sure to use both number variables. User Input Input is described as anything we send to the program whether it be by keyboard, mouse, webcam, microphone, etc. We will be using the keyboard and collecting information from users, making our programs interactive. Example: print "What is your name?" name = raw_input() print "Hi,", name Output: What is your name? foobar Hi, foobar Basically we used a built-in function 'raw_input()' to collect information from the user and assign it to a variable. Once in the variable we can spit it back out at the user. We can also manipulate it as the next example will show. Alternatively, we could have used name = raw_input("What is your name?"), instead of using print, with the only difference being that the user input would be on the same line as our "What is your name?" string. Now for numbers we use a little different function. print "Addition" a = input("Please select a number:") b = input("And another one:") c=a+b print a, "plus", b, "equals", c Output: Addition Please select a number: 32 And another one: 31 32 plus 31 equals 63 Using the input() function we can assign the user input as numbers. If you try to assign a letter or character other than a number our program will shut down and give you an error. Also, assigning numbers with raw_input() will just put the numbers into a string (i.e. "63") meaning you can't manipulate them. Practice 1. Make a program that gets the user's name, favorite color, and a number. Output hello, "their name"! and then their favorite color times the number they entered. if Statements

Up 'til now, we haven't had too much control over our programs. if statements are one of the basic building blocks of almost any program (along with while and for, more on those later). These are what we we call flow control, because they give us options for different scenarios in our program. Let's start with a simple example program: number =input("Choose a number:") if number >= 100: print "That is a high number!" else:print "That number is less than 100! #Prompt the user for a number

Lets examine this line by line. The first line just prompts the user for a number. At the start of the if statement, it says if the users input is >= (greater than or equal to) than 100, then do all the indented statements right under it. The else statement is part of the if statement, it means that if number is anything else, then do every statement that is indented under it. Python is sensitive to white space, so indentation is very important, if you leave it out, you will get an error. Here are all the various conditional operators you can use in your if statements: == != > < >= <= Equal to. Make sure you don't confuse this with =, which assigns variables.

Not Equal to Greater than. Less than. Greater than or Equal to. => will not work. Less than or Equal to. =< will not work.

I am going to give you a more sophisticated example now, which we will edit and improve upon in the next chapter: print "************MENU************" #Make a menu print "1. Add numbers" print "2. Find perimeter and area of a rectangle" print "0. Forget it!" print "*" * 28 option = input("Please make a selection: ")#Prompt user for a selection if option == 0: #If option is 0, quit statement quit elif option == 1: #If option is 1, get input and calculate firstnumber = input("Enter 1st number: ") secondnumber = input("Enter 2nd number: ") addit = firstnumber + secondnumber print firstnumber, "added to", secondnumber, "equals", addit #show results elif option == 2: #If option is 2, get input and calculate length = input("Enter length: ") width = input("Enter width: ") perimeter = length * 2 + width * 2 area = length * width print "The perimeter of your rectangle is", perimeter #show results

print "The area of your rectangle is ", area else: #if the input is anything else its not valid print "That is not a valid option!" Now lets go through this one. The first block of it is just to print the menu. Then we get a selection from the user. If they choose 0 then we use the quit command, and break out of the whole if statement (which in this case is the rest of the program). Meaning it won't do anything else in that specific if statement. The next statement you see something new, elif. elif is just a shortened version of "else if" if we just used if there it wouldn't keep the whole statement together. It would just start a brand new if statement. By using elif it binds that statement to the first one. Which is important once we get down to else. Because we have the whole statement binded, else examines if it is option 0, 1, or 2 and if not prints "That is not a valid option". Had we just used if on the other two statements it would have only examined the last option (i.e. if option == 2). So would have returned the "That is not a valid option" output if we had chosen option 1. Nesting if statements We also have the ability to nest if statements. Meaning we can have one inside another that it will only examine and do if the first if statement is true. Let's tweak the example above to give you an idea of what I mean. if option != 0: #Only do this if the option is not 0 if option == 1: #If option is 1, get input and calculate firstnumber = input("Enter 1st number: ") secondnumber = input("Enter 2nd number: ") add = firstnumber + secondnumber print firstnumber, "added to", secondnumber, "equals", add #show results elif option == 2:#If option is 2, get input and calculate length = input("Enter length: ") width = input("Enter width: ") perimeter = length * 2 + width * 2 area = length * width print "The perimeter of your rectangle is", perimeter #show results print "The area of your rectangle is", area else:#if the input is anything else its not valid print "That is not a valid option!" So if they choose option 0, python will not even look at anything that is indented under it. Now your probably wondering how we can make this program go on until we tell it to quit. For that we need a loop... Practice 1. Design a program that has the user guess a password, if it is wrong say "LOCKED OUT!" Loops Loops are an essential part of programming. Basically a loop lets you run a specific part of your program until a certain condition is met. The first loop we will be working with is...

while Statements Let's start with an example using our last program: option = 1 while option != 0:

print "/n/n/n************MENU************" #Make a menu print "1. Add numbers" print "2. Find perimeter and area of a rectangle" print "0. Forget it!" print "*" * 28 option = input("Please make a selection: ") #Prompt user for a selection if option == 1: #If option is 1, get input and calculate firstnumber = input("Enter 1st number: ") secondnumber = input("Enter 2nd number: ") add = firstnumber + secondnumber print firstnumber, "added to", secondnumber, "equals", add #show results elif option == 2: #If option is 2, get input and calculate length = input("Enter length: ") width = input("Enter width: ") perimeter = length * 2 + width * 2 area = length * width print "The perimeter of your rectangle is", perimeter #show results print "The area of your rectangle is", area else: #if the input is anything else its not valid print "That is not a valid option!" All we had to do was wrap most of our program in a while statement. ( I also added some "/n" to the top for aesthetic reasons). This while statement will continue to loop until the user's picks 0 as an option. Now we can run the program indefinitely until we decide to quit! Let's add a little bit more to our code so that we can add as many numbers as we like together, instead of just two. Assign a variable with any number besides 0, and a variable that equals 0 at the top of our code: number = 1 sum = 0 Now change your first if statement to this: if option == 1: print "Use 0 to quit adding numbers." sum = sum + number while number != 0: number = input("Enter number: ") print "The total is: ", sum

If you did this correctly, when you choose option 1, you should be able to add unlimited numbers together. The only way to exit that part of the program is to input 0. Which will then print the total. The number 1 that we assigned at the beginning never gets added because the user inputs a number that changes number's value before it gets added to sum. Oops. While testing that last code, i noticed one thing that needs debugged! (This happens to the best programmer. At least half the time spent making a program is debugging!) When we enter 0 to quit it says "That is not a valid option" before the program quits. The way around this is with the break command. Add this new elif before your else statement: elif option == 0: break This will effectively break us out of the loop before it reads the else statement! Let's see a fresh example of the while statement: counter = input("Enter a number to start the countdown: ") while counter >= 0: print counter counter = counter - 1 #alternatively you can use counter += -1, same thing print "SPLAT!"

This will loop the while statements x number of times, x being the user input. for Statements There is another way we could have done the lastprogram and that is with a for statement. Try this on for size: counter = input("Enter a number to start the countdown: ") for x in range(counter, 0, -1): print x print "SPLAT" Now there are a couple of new things in this example first and foremost, for. What for does is assigns x to each number in a list of numbers (temporarily), or even a list of words(more on that later). Also notice that you do not need to assign anything to x. for does that for you! You can use any variable you want in its place. Now what list am i talking about? I don't see any list? Ah, but that is what the range function is for. The first field in range is the starting number, the second field is for the number right before the ending number (it doesn't count the last number). And the third field is for the increments you want to move. The third field is optional, if you do not put anything there it defaults to increments of 1. Lets see an example of how that works: for x in range(1, 10):print x What do you suppose the output will be? This: 1 2 3 4 5 6 7 8 9 Like I said before it won't count the last number, so if we wanted to count to 10 we would have to use range(1, 11). Let's try one more and then I am going to loose you to your practice. ;) Lets count odd numbers up to a user specified number: for anything in range(1, number, 2): print anything Ok...hopefully you have a good idea of how these loops work your ... because here is

Practice 1. Design a program that gives a menu for counting down and counting up to a user specified number (extra credit if you make count up and count down a submenu), also have an option that gives the output of the fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13, 21--the next number in the sequence is always the sum of the two numbers before it), and then give an option to quit of course! ;)

Functions Functions are a wonderful tool to use while writing programs. In a nutshell, they just allow you to write a piece of code ONE time and reuse it as much as you want within your program. As a matter of fact, you have already been using functions if you've followed this tutorial: raw_input() and input(). These are built in functions, and there are many more. Let's try an easy example:

def new_function(): print "I'm in a function!" print "I'm out of function" new_function()

#defines our

new function

Now this is a very simple function. The first line simply defines the function. The second line is a part of that function. Anything that is indented after the function is considered part of it. When you name a function, it is common practice to add an underscore in between words. This just makes it easier to recognize within the code. Now you may be wondering what the paranthesis are for. We are able to put data into the function in order to manipulate it. Like this: def add_it(x, y): #define our function and have it call for two inputs print x + y #print the output x + y a = 50 #make two variables b = 100 add_it(a, b) #use our function to output our two variables added together Notice that in this function we have x and y. These are considered variables only in the function. If you try to call x or y outside of the function, it won't work. So when we call our function, we put in 2 variables, which effectively makes them x and y within the function. This would also work with just plain numbers. Now its great to manipulate the variables within the function, but lets say we want to keep that sum in a global variable(variable that is seen by entire program). def add_it(x, y): return x + y a = 50 b = 100 sum1 = add_it(a, b) So in the previous code, we have added return. Your function will only return one variable at a time (unless you use lists, covered later). So on the last line we just made another variable that will be whatever value the function returns. Another thing you can do with functions is specify a value when you are defining it. If you don't add that parameter in when you call the function, that value will be used. def add_it(x, y, z = 13): return x + y + z add_it(1, 2) add_it(1, 2, 3) I also give you an example of how you can just add numbers instead of first making them variables. So as you can see functions are pretty simple. They are handy in making your code neat, and definitely cut down on typing your program. Try the practice below! Practice Rewrite the menu program we have been working with to include functions for all the options! Lists and Tuples

Lists are a very useful part of programming. A list is essentially a variable that stores more than one value and can be changed. A tuple is a list that is immutable, or cannot be changed. Both of these can hold text or numbers or even other variables. We declare a list like this mylist = [1, "hi", 2, "what's", 3, "up"] or like this: my list = 1, "hi", 2, "what's", 3, "up" We can then output our list just like we would with any other variable! print mylist Now let's say we only want to output one item in the list. How would we do this? Well each item in the list is assigned a number, the first one being 0. So we could output just one like this: print mylist[1] Which outputs the second variable in the list. We can also assign another variable to an object in the list like so. x = mylist[1] print x an item in the list: Here is an example of a program that allows the user to choose

names = ["George", "Henry", "Theresa", "Janet", "Mark","Justin", "Michelle"] option = 0 #declare our input variable while option != 99: #have the program run until user enters 99 option = input("Please enter a number between 0 and %d to quit enter (len(names)-1)) if 0 <= option < len(names): print names[option] #print the name elif option == 99: #If option is 99 break out of if statement quit else: print "That is not a valid option!" #If option is anything else, tell user

99:"

Now there are probably a couple different things in this one we haven't covered. My main focus is on the len() function. This is a function that returns the length of your list. Used: len(list). You may also notice the %d on the input line. This is an alternative way to get the value of a variable into a string. Usage: print "number is %d" %23 (or %(24-1)). This would put the number 23 into the string. Now on that same line, where I put len(names)-1, that is because the length of the list is alway going to be 1 higher than the number assigned to the last variable. This is no problem when you use a range() function though. names = ["George", "Henry", "Theresa", "Janet", "Mark", "Justin", "Michelle"] for x in range(len(names)): print names[x] This will simply output each name. Now what if we want to change in the list to something else. This is very simple: names[3] = "Bob" And "Theresa" will be changed to "Bob" If we just want to add a name to the end of the list we can use the append() function: names.append("Georgina") If we want to delete an item, we just use the remove() function. an item

names.remove("Henry") Lets use the information we have so far to write an example program: def menu(): print "\n\n\n1. List all employees " print "2. Add employee" print "3. Delete employee" print "4. Number of employees" print "0. Quit\n\n\n" def list_employees(list): for x in range(len(employees)): print "%d." %(x+1), employees[x] def add_employee(list): addit = raw_input("Employee's name? ") list.append(addit) return list def del_employee(list): delit = raw_input("What employee do you want to delete? ") if delit in list: list.remove(delit else: print "That employee is not in the database." return list option = 1 employees = ["Jack Stark", "Fred Johnson", "Elise Smith"] x=0 while option != 0: menu() option = input("Please pick an option: ") print "\n\n\n" if option == 1: list_employees(employees) elif option == 2: employees = add_employee(employees) elif option == 3: employees = del_employee(employees) elif option == 4: x = len(employees) print "There are", x, "employees." elif option == 0: quit else: print "That is not a valid option"

print delit, "deleted!"

This may seem like a sizable program, but once you read through it you should understand just about everything in it. There is only one thing I haven't covered and that is in. In the line "if delit in list:", the program just checks to see whether or not that item is in the list. There are many more functions you can use with list, but I will get to those as we need them. You should have enough information on lists to use for multiple applications. Now I mentioned tuples earlier. Basically they are the same as lists without all the functionality. They are declared like this:

mytuple = (1, 2, 3, 4, 5) You can still access all the objects in tuples, but you are unable to change them in anyway. You can't even add to them. Honestly, in most of my programs I use list as they are more flexible. Practice 1. Make a counter that goes up to ten, using a list. 2. Now add on to that so that the user can specify a number to count up to.

You might also like