Python reference
This page is intended to serve as a brief, beginners reference to the Python programming language.
Contents
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.
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.