Difference between revisions of "Python reference"

Line 9: Line 9:
 
<code>message = "hello"</code>
 
<code>message = "hello"</code>
 
This would store the string 'hello' in the variable 'message'. Be sure to remember quotation marks for strings.
 
This would store the string 'hello' in the variable 'message'. Be sure to remember quotation marks for strings.
 +
 +
== '''FILES''' ==
 +
Typing in stuff is fun, but if you have a lot of data, it is more likely to be stored somewhere on your hard drive. So we need to be able to read data from a file.
 +
 +
And similarly, printing works for short things, but if you want to look at something later, it needs to be written to a file.
 +
 +
The trickiest part of the process is putting the file in the right place so Python knows where to find it. You can use IDLE to make a new window, type a few sentences into it, and then save it as a txt file (like sentences.txt). IDLE should choose the appropriate directory automatically.
 +
 +
To do anything with a file, the first thing to do is to open it. Here's how:
 +
<code>myFile = open('sentences.txt', 'r')</code>
 +
 +
myFile is a variable to hold the file object that the open function returns. The function itself takes two parameters. The first is a string with the name of the file.
 +
 +
The second indicates what you want to do with the file. The options are as follows:
 +
<code>open('sentences.txt', 'r')</code>
 +
The above code opens a file for reading, thus the 'r' above. You can access the contents of the file in this manner.
 +
 +
<code>open('sentences.txt', 'w')</code>
 +
The above code opens a file for writing, thus the 'w' above. You can append to documents in this manner.
 +
 +
=== '''FILE USE IN PIG LATIN PROGRAM''' ===
 +
 +
 +
 +
  
 
== '''LISTS''' ==
 
== '''LISTS''' ==

Revision as of 17:21, 22 November 2010

This page is intended to serve as a brief, beginners reference to the Python programming language.

VARIABLES

In Python, there is no need to specify a type when storing information in a variable. It is basic and straightforward to store information.

number = 1 This would store the integer value 1 in the variable 'number'.

message = "hello" This would store the string 'hello' in the variable 'message'. Be sure to remember quotation marks for strings.

FILES

Typing in stuff is fun, but if you have a lot of data, it is more likely to be stored somewhere on your hard drive. So we need to be able to read data from a file.

And similarly, printing works for short things, but if you want to look at something later, it needs to be written to a file.

The trickiest part of the process is putting the file in the right place so Python knows where to find it. You can use IDLE to make a new window, type a few sentences into it, and then save it as a txt file (like sentences.txt). IDLE should choose the appropriate directory automatically.

To do anything with a file, the first thing to do is to open it. Here's how: myFile = open('sentences.txt', 'r')

myFile is a variable to hold the file object that the open function returns. The function itself takes two parameters. The first is a string with the name of the file.

The second indicates what you want to do with the file. The options are as follows: open('sentences.txt', 'r') The above code opens a file for reading, thus the 'r' above. You can access the contents of the file in this manner.

open('sentences.txt', 'w') The above code opens a file for writing, thus the 'w' above. You can append to documents in this manner.

FILE USE IN PIG LATIN PROGRAM

LISTS

Lists are used very frequently in Python. An example of a list is below:

ls = [1,2,3,4,5] The above code instantiates a list that contains the values 1,2,3,4, and 5. These all have indices associated with them. The 1 is in position 0, the 2 in position 1, and so on, all the way to position 4, which holds the value 5.

LIST FUNCTIONS

ls = [1,2,3,4,5]

In order to access certain elements in a list, we can use methods such as: ls[0] This would return the number 1, because that is the element at position 0 (the front) of the list.

len(ls) This would return 5, which is the length of the list (number of elements in it).

ls[-1] This would return 5, which is the last element in the list. An index of -1 starts from the back of the list and gives you that element, so ls[-2] would give you 4 as a result because it is 2 positions from the back.

ls[1:3] This would return the list [2,3] because it returns everything from the first number's index (inclusive) to the second number's index (but not including this number). In other words, this returns everything from position 1, including position 1, all the way to position 3, not including position 3. This is called a slice.

ls[:3] This is another example of slicing. When no first number is given, it automatically starts from the beginning, so this would be from the beginning up to position 3 (not including position 3). This would return the list [1,2,3].

ls[1:] Similar to the above code, this will begin at position 1, including position 1, and go all the way to the end (because no number was specified for the second number. This would return the list [2,3,4,5].

ls[:] This gives you a copy of the entire list [1,2,3,4,5]. This can be helpful for list manipulation.

ls[::2] This gives you every other element in the list. So it will go through all of the list and return the number every 2 steps, which is what the 2 means. This will return the list [1,3,5].

ls + [6,7,8] This is simple concatenation. It would result in the list [1,2,3,4,5,6,7,8]

ls*2 This is a multiplier, and would result in the list [1,2,3,4,5,1,2,3,4,5].

3 in ls This is a conditional statement that would return True because it would search the list for 3 and find it. If we searched for something like 100, it would return False.

min(ls) This would return 1 in our case. It checks the list for the smallest element and returns it.

max(ls) Works similarly to min() except it returns the largest element. If we were working with the original value of ls (which is [1,2,3,4,5]) then this would return 5.

sum(ls) This would return 15, which is the sum of all of the elements of the list (1+2+3+4+5).

Lists are mutable, which means we can change values within them by making calls like the one below: ls[0] = 10 This would set the value of position 0 to 10 (and change it from its previous value of 1). If we printed the list after this change, the list would now be: [10,2,3,4,5]

Similarly, we can use slices to do this: ls[1:3] = [0,0] This would set the positions 1 and 2 in ls to 0, so if we used the original values in ls (which is [1,2,3,4,5]), then the new list would be [1,0,0,4,5]

What do we do if we don't know where a value is in a list? ls.index(3) This checks the list for 3 as a value and returns the index. This would return 2 because 3 is in position 2 of this list.

ls.count(3) This checks how many times the value 3 is in the list. In this case, it would only return 1.

ls.append(6) This would add 6 to the end of the list, giving it the new value of [1,2,3,4,5,6].

Let's make a new list, called ls2 and it will be the following: ls2 = [3,4,2,1,5]

This list contains the same elements as the ls we had before, but it is in a different order. How can we make them the same?

ls2.sort() This would sort the list and it would end up being [1,2,3,4,5], which is what ls was.

TUPLES

A tuple is very similar to a list.

One major difference is that it uses parentheses:

tup = (1,2,3,4)

Almost everything you can do with a list you can do to a tuple: access by index with [] take a slice concatenate with + repeat with * use in to check for membership use for/in to iterate over the elements in a tuple use len, max, min, or sum the methods index and count

Things you cannot do with a tuple: assignment deletion reverse sort etc.

The things you cannot do are the things that change the tuple. This is where lists and tuples are different. Tuples are immutable objects. They cannot be altered.


FOR-LOOPS

In Python, as well as in most programming languages, you can do for-loops to accomplish many things in a program.

for i in range(5):

   print("hey")

This code will print the word "hey" five times.

You could also do something like this:

for i in range(5):

   print (i)

This code will print the numbers 0 through 4 on different lines. Each time the it would go through the loop, the i is updated by one. It starts at 0, then prints 0, then after it prints, it is incremented (one is added to it), then it prints its new value (1). It does this all the way until it reaches the number in the range (exclusive), so in this case it stops at 4, because when 1 is added to it, it is no longer strictly less than 5.

for number in ls:

   print (number)

This code will step through the list and instead of incrementing the value of the variable "number" in each iteration, it will be set to the next element in the list. If the list (ls) were [2,4,6,1] then for the first iteration of the loop, the value of number would be 2, followed by 4, followed by 6, and finally by 1. This is an extremely useful for-loop to know and use. You can also do this type of loop with strings. See below for an example.

for letter in word:

    print (letter)

If the string stored in word was "fish" then on the first iteration, it would print f, and then i, and then s, and finally h.

INPUT AND OUTPUT

INPUTS This will help you learn how request inputs and store them in variables.

We have learned how to store values into variables already. Now we will learn how to request information from the user and store that information in a variable.


entree = input('How much is the entree?')


When this line of code is entered into python, it will immediately print a message (in this case "How much is the entree?"). After the message pops up, there will be a place to type and press enter. Once some text is entered, it will be stored in the entree variable.

If the above code was run and the user typed in 5.50 as the price, the variable entree would contain the value 5.50 afterwards.

This would be fine if we wanted to print it, but we are in a heap of trouble if we want to add 2 to this value or add it to another price. We must convert it to another datatype before we can do this.

In order to make this conversion, we can type the following:

entree = float(entree)


Now we can manipulate the value of entree by typing something like:

entree + 2


You can also do you this with int(variable) to convert it to an integer.

Finally, if we want to print this value in a sentence, we can do something like the following:

print ("The total is " ,entree)

The total is 5.50


"The total is 5.50" is what is printed when the above is run.

EXAMPLE INPUT PROGRAM

The following program prompts a user for the radius of a circle and it returns the diameter, the circumference, and the area of that circle.

# Computes statistics about a circle
# by Scott Weiss

radius = input('Enter the radius of the circle: ')
radius = float(radius)

diameter = 2 * radius
circumference = 3.14 * diameter
area = 3.14 * (radius ** 2)

print('The diameter is: '+str(diameter))
print('The circumference is: '+str(circumference))
print('The area is: '+str(area))

FUNCTIONS

It's most closely tied to the mathematical idea of a function. Here's a simple one: f(x) = x + 5, which adds five to the input.

If I give you a value for x, say 2, you put it into the equation on the right side to get 2 + 5 or 7. So we would say f(2) is 7.

In programming, we use a function in the same way. We give a function some inputs, it does some computations, and (probably) gives us an output.

In general, we use a function to do a particular subtask that's part of a larger program. Let's look at some examples.

getAverage()

def getAverage(x, y):
    return (x+y)/2

This straightforward function will return the average of two numbers that it takes as input.

MODULES

Let's figure out the sine of a 30-degree angle in Python!

It should be 1/2 or 0.5.

Just like in trig class, it's sin. So evaluate sin(30) should give us the answer, right?

Actually not. It doesn't seem to know what sin means. The error says that 'sin' is not defined.

Python does know about sin. But it's not part of the system when you start Python up. Why can't Python just load all possible functions at startup?

If we loaded every possible function, we'd overwhelm your computer's memory! There'd be no room for your actual program. So we'll only bring in most functions when we say that we need them.


MATH MODULE

Functions are grouped into files called modules. For example, all the trigonometric functions are in a module called math.

So to use sin, we need to tell Python to bring the math module into the shell.


SIN() FUNCTION

Here's the statement we need: import math Note the orange color of import. That shows it is a reserved word.

Now Python knows about this module, and we can use it! Go ahead and figure out sin(30) by calling the name of the module:

OK, to use a function from a module (after importing the module), give the name of the module, then a period (.), then the name and any parameters.

The call for the sin function would be:

math.sin(30)

so give it a try. Remember the result should be 0.5.

-0.9880316240928618?? 

This does not give us 0.5. Why is that? The reason is that the sin() function expects to receive its parameter in a unit called radians (and we gave it in degrees). How do we fix this?

There's a function called radians() that takes a value in degrees and converts it to radians. That's exactly what we want.

So how do we use it? This is really cool.

math.sin(math.radians(30))


Remember to read it inside out (just like nested math functions f(g(x))). Take 30, convert it to radians, then take the sine of that angle.

That gets us really close to 0.5 (we discussed why it was off in class last week). How do we push it the rest of the way?

How about round? Can you add that to the call?

round(math.sin(math.radians(30)), 1)


SQRT() FUNCTION

Let's see how we would use the math module to calculate the square root of a number:

>>> import math
>>> math.sqrt(4)
2.0


LOG() FUNCTION

Let's see how we would use the math module to calculate the log of a number:

>>> import math
>>> math.log(2)
0.6931471805599453

The way the log() function works as shown above is to calculate the natural log of a number. If we wanted to specify the base of the number, you would just add it after the 2 with a comma. For example, if I wanted to calculate the log (base 10) of 2, I would type the following:

>>> import math
>>> math.log(2, 10)
0.30102999566398114


EXP() FUNCTION

The last thing we will look at in the math module is the concept of e. In order to calculate e in Python, you need to make the call to the function exp(), as follows:

>>> import math
>>> math.exp(2)
>>> 7.38905609893065

This function returned e raised to the second power.

RANDOM MODULE

There is also a module called Random. This can be used to bring in random numbers for a program that might need them.

RANDINT() FUNCTION

import random
randNum = random.randint(1,30)

The randint function returns a value in the range from 1 to 30 inclusive.