LAB 1 - An Introduction to Python

VARIABLES

We use variables to represent locations in computer memory where we store data for our program. To initialize variables in a Python program, you simply type the variable name followed by an equals sign and then some expression that evaluates to the variable's initial value. Here are some examples:

x = 2
mass = 12.3
speed_of_light = 299792458
energy = mass * (speed_of_light ** 2)
raining = True
course_15105 = "Principles of Computation"

Variable names must start with a letter or an underscore, followed by any sequence of letters, digits and underscores. Variables are case-sensitive, so the variables salary and Salary are different. Variable names cannot include spaces.

The instructions above are called assignment statements since they assign a value to a variable. All assignment statements have a single variable followed by an equals sign followed by either a data value or an computation (expression) contains variables and/or data values. For numerical computations, here are the operators you can use:

+	addition
-	subtraction
*	multiplication
/	division
%	remainder (think: modulo)
**	exponentiation

When you type expressions with more than one arithmetic operator, they are evaluated based on the usual mathematical precedence, with exponentiation performed first, then multiplication, division and remainder next, and finally addition and subtraction last. If there is more than one operator of the same type (e.g. addition and subtraction), they are evaluated left to right. If you want to force a lower precedence operation to be performed first, use parentheses like you would in ordinary mathematics. For example, here is a Python statement that computes the total amount due for a loan using simple interest given the principal (amount borrowed), interest rate per month and time of loan in months:

total_amount = principal * (1 + rate * time)

INPUT AND OUTPUT

If you want to input numerical data into your program from the keyboard, you can use the input function:

tempF = input("Input the temperature in Fahrenheit: ")
The input function requires a string that is output to prompt the user with an instruction on what input is required. The numerical value the user types in is then stored in the variable tempF.

To output the value of a variable or expression, you simply use the print function. Here are three examples:

print "The temperature in Fahrenheit: "
print tempF
print "The temperature in Celsius is ", (5.0/9.0)*(tempF - 32.0)
print mass, " * ", speed_of_light, " ** 2 = ", energy 

In the first two examples, there is only one item being printed per line. In the last two examples, more than one item is printed on the same line.

WRITING PYTHON PROGRAMS

A simple Python program has the following format:

def main():
	---------------------------
	Python instructions go here	
	---------------------------
        <-- blank line here
main()

The instructions of the program are stored in the function definition (def) named main. The final instruction runs the main function it is defined. Here is an example of a short program that converts an input temperature in Fahrenheit to Celsius:

def main():
        tempF = input("Input the temperature in Fahrenheit: ")
        tempC = (5.0/9.0) * (tempF - 32.0)
        print tempF, " F = ", tempC, " C"

main()

Note that the instructions in the main function definition are all indented. We suggest you use one tab to line up all instructions in main.

LOOPS

If you want to repeat instructions a specific number of times, you can use the for instruction:

for i in range(10):
	print i

The loop above sets i to values in the range from 0 up to but not including 10. Another way to look at it is that it is a loop that repeats exactly 10 times. Here is the output:

0
1
2
3
4
5
6
7
8
9

Here is a slightly different version. Notice the extra comma at the end of the print statement:

for i in range(10):
	print i,

Since the print statement has a comma, the cursor stays on the same line to print the next item. Here is the new output:

0 1 2 3 4 5 6 7 8 9

Notice that the instruction that is repeated is indented below the for instruction. A loop can repeat more than one instruction, as a group, as shown below:

for i in range(10):
	print i, "\t",
	print i**2, "\t",
	print i**3

The loop consists of a block or set of 3 instructions that are repeated 10 times. This loop prints out a table of the squares and cubes of the integers 0 through 9. The "\t" string is a special symbol for one press of the tab key on the keyboard. The extra comma at the end of the first two print statements keeps the cursor on the same line until we get to the third print statement. The instruction(s) that repeat in a loop is called the loop body. Here is the output:

0 	0 	0
1 	1 	1
2 	4 	8
3 	9 	27
4 	16 	64
5 	25 	125
6 	36 	216
7 	49 	343
8 	64 	512
9 	81 	729

Sometimes you might have a computation that you have to repeat, but you don't know specifically how many times you must repeat the computation. You can use the while loop to handle this. Based on the condition you give, the loop will repeat as long as the condition holds. For example, let's say you want to print your table above until the cube value exceeds 500. Here's how we would write this:

i = 0
while i**3 < 500:
	print i, "\t",
	print i**2, "\t",
	print i**3
	i = i + 1

Note that we have to initialize i explicitly here before the loop begins, and we have to add 1 to i before we start our next iteration of the loop. (The for loop you saw above does this automatically, but the while loop has more flexibility and can run an arbitrary number of times.) Here is the output this time:

0 	0 	0
1 	1 	1
2 	4 	8
3 	9 	27
4 	16 	64
5 	25 	125
6 	36 	216
7 	49 	343

Here are the operators you can use to compare one value to another for the condition of a while loop:

<	is less than
>	is greater than
==	is equal to
<=	is less than or equal to
>=	is greater than or equal to
!=	is not equal to
The operators above are called relational operators since they allow you to determine the relation of one value to another.

As a final example, here is a Python program to compute the GCD of two integers:

# gcd.py
# Program to compute GCD

def main():
	x = input("Input the first integer: ")
	y = input("Input the second integer: ")
	print "The GCD of ", x, " and ", y, " is ",
	while y != 0:
		x_prime = y
		y_prime = x % y
		x = x_prime
		y = y_prime
	print x

main()

The program asks for values for x and y, then repeats the set of 4 instructions of the while loop while y is not equal to 0, and finally outputs the final value of x as the answer for the GCD calculation. The symbol # represents a comment which just a message for us to explain the purpose of the program. The text after the # on each line is ignored by the Python interpreter.

PRACTICE EXERCISES

  1. Write and run a Python program that outputs the value of each of the following expressions:

    5.0/9.0
    5.0/9
    5/9.0
    5/9
    9.0/5.0
    9.0/5
    9/5.0
    9/5
    

    Based on your results, what is the rule for arithmetic operators when integers and floating point numbers are used?

  2. Write and run a Python program that asks the user for a temperature in Celsius and converts and outputs the temperature in Fahrenheit. (Use the formula given in the example above and solve for tempF in terms of tempC.)

  3. Here is an algorithm to print out n! (n factorial) from 0! to 19!:

    1. Set f = 1
    2. Set n = 0
    3. Repeat the following 20 times:
       a. Output n, "! = ", f
       b. Add 1 to n
       c. Multiply f by n
    

    Using a for loop, write and run a Python program for this algorithm.

  4. Modify the program above using a while loop so it prints out all of the factorial values that are less than 1 billion. (You should be able to do this without looking at the output of the previous exercise.)