Python Tutorial

Share Embed Donate


Short Description

Python tutorial...

Description

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 itsounds 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!"

3

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

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 print print print print

"1 plus 1 =", 1 + 1 "20 divided by 2 =", 20 / 2 "100 minus 45 =", 100 - 45 "64 times 2 =", 64 * 2 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 fir st 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 theif 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.

<

Lessthan.

>=

Greater than or Equal to. => will not work.

= 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 for a 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 withinthe 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

Here is an example of a program that allows the user to choose

an item in the list:

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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF