Python code can be input and run in a variety of ways:
>>>
and interpreted. The response is given on the following linePlease use either an active code window or the pythontutor.com application for the Activities highlighted in this document. There is a link to the pythontutor.com site on the course web page. Active code windows assigned to chapter are found under the Assignments link in the course text book Table of Contents
In Python, everything is an object.
The first Python function we will use is the print
function. Type, or Copy and Paste (CAP), the following code into an active code scratch window.
print('Hello World!')
print(17)
print('17')
print(17.9)
print('ten')
print(ten)
Python has a built-in function called type
that returns the type of a input object. It is shown below in composition with the Python function print
.
type('Hello World')
print(type('Hello World!'))
print(type(17))
print(type(9.7))
The print
function is required to see the result of the type
function (Not needed when using the Python shell).
Python provides a way of changing (converting) the class (or type) of an object using the functions with names representing the data types. For example
print(int('678'))
print(str(7.8))
print(float('678'))
results in the following output:
678
'7.8'
678.0
Activity: Type or CAP (copy and paste) the following code in the active code scratch window and note the results. Explain why the results are what they are. HINT: What type is each of the different inputs?
print(int(3.2))
print(int(3.9))
print(float("3.2"))
print(int("3.2"))
print(float("three point two"))
str
object ‘Hello, World!’ is immutable.float
37.8 is immutable.Create a variable, known as an object reference, by using an assignment statement and the =
token
s = 'green'
Here, s is an object reference (a variable). The equal sign is not the same as equality in mathematics. As an object, s is automatically of class str because ‘green’ is of class str
.
Unlike in mathematics, this relationship is not reflexive. That is, it is not possible to change the roles in this statement. The statement
'green' = s
is invalid. The str
object ‘green’ is immutable. It cannot be assign a different value. However,
green = s
is a valid assignment statement. Here, green is now the name of an object reference to s.
Activity: Type or CAP the following in the scratch window. First, “guess” what the result will be, and then run the code to confirm the result.
s = 'green'
green = 'red'
print(s, green)
The object reference type will change automatically (dynamically) by simply assigning the object reference to an object of a different class.
Activity: Look at the code shown below and decide what values will be printed for s and t. Then, type or CAP the code in the scratch window to see the Python result.
s = 'green'
t = s
s = 783
print(s, t)
Variable names:
_
A statement is an instruction that Python can execute
An expression is a combination of such item as values, variables, and functions that needs to be evaluated
The evaluation of an expression produces one or more values. Therefore, they often appear on the right-hand-side of an assignment statement.
The Python built-in function input
allows the programmer to ask and receive input from the user. As an example:
age = input("How old are you (in years)?")
The string within the parentheses, “How old are you (in years)?”, is the prompt. The user responds by typing the correct digits and hitting the return key. The object reference age points to the response.
All input is of data type str
.
Operators are special tokens that represent computations such as addition (+), multiplication (*) and division (/)
The values on which operators work, or are applied to, are the operands
Mostly, operators are binary operators because they have two operands
print(10 / 3)
print(10 // 3)
print(10 % 3)
Expressions typically have multiple operands.
/
2 *
4 = (16/
2)*
4 = 32. It does not equal 2.parentheses can be used to over-ride precedence and clarify order for the programmer or reader
2**
3 *
3 -
2 = 22
2**
3 *
(3 -
2) = 8
if you are unsure of the precedence, use parentheses to insure your intended order is used
Refer to the text for a more complete information on order of operation or precedence
Activity: First, apply rules of precedence to determine the value of the expression shown below without the aid of Python. Then, type or CAP the expression into an active code window to check your calculation. Next, use one set of parentheses so that the expression evaluates to 52.0 (HINT: 52 = 2 + 2*25, and 25 = 5**2). How many different possible results can be obtained using a single pair of parentheses placed at various spots in the expression?
2 + 2 * 10 / 4 * 2 ** 2
variable names are references to objects, and their references can change
Activity: Look at the code shown below and decide what values will be printed for a and b. Then, type the code in an active code window to find the Python result.
a = 6
b = a
a = 2
print(a, b)
An example of updating a variable is shown below:
x = 2
x = x + 1
print(x)
The output is 3
Activity 1: The density \(\rho\) of an object is defined by \(\rho = m/V\), where \(m\) is the mass of the object in kilograms, and \(V\) is its volume in cubic meters. Write a program that asks the user to input the mass and volume of an object and prints out the objects density in kilograms per meter cubed. The output should be formatted in the following way for the example case of \(m\) = 10 and \(V\) = 5:
mass : 10 kilograms
volume : 5 meters cubed
desity : 2 kilograms per meter cubed
Activity 2: The modulo operator - %
. This is a useful hint for Exercise 2.4 in homework #2. Type or CAP the following code in your active window, then save and run.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
print(number % 7)
Activity 3: The for
loop is a very useful Python programming compound statement. This activity will show how it can be used in conjunction with the +
operator to update a variable in a meaningful way. Type the following code in an active code window. Use the code lens in pythontutor.com to step through the program’s sequence of statements.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = 0
for number in numbers:
sum = sum + number
print('sum = ', sum)
Activity 4: The process in activity 3 can be accomplished using the range
function instead of explicitly defining the list of integers. Run the following code and figure out what happens. Do you get the same result as in the previous activity? If not, adjust the code so that you do. Next, experiment with the following form: range(10, 0, -1)
sum = 0
for number in range(10):
sum = sum + number
print('sum = ', sum)
Activity 5: Modify the code structure in the previous activity so that the list is that of the following words (NOTE: enclose each item in quotes and separate each using a comma) : A, big, blue, house, in, the, green, woods. The accumulating process constructs a sentence from the words. Save and run your code. You will likely have to make some adjustment(s) to your code so that the result truly looks like a sentence when the process is complete.
Activity 6: The “handshake” problem… a natural application of the for
loop. Suppose there are \(n\) people in a room, and each person shakes the hand of every other person exactly once. Determine the total number of handshakes.
Activity 7: An auditorium for stage plays has 20 rows of seats, and each row has 40 seats for a total of 800 seats. Play-goers are assigned to a specific seat based on the number, ranging from 1 (for row 1 and seat 1) to 800 (row 20 and seat 40) printed on their ticket stub. Write a program that takes a number between 1 and 800 and prints out the corresponding row and seat number for the ticket holder. NOTE: You will likely need to use both the modulus operator %
and integer division operator //
.
A solution for the return day of the week problem.
leave_day = input("What day of the week will you leave (0 = Sunday ... 6 = Saturday)?")
nights = input("How many nights will you be gone?")
return_day = (int(leave_day) + int(nights)) % 7
print("Return day number =", return_day)
In most cases, it is better (necessary) to convert input data to float
than int
to prevent a runtime value error.
miles_f = float(input("How many miles were driven?"))
gallons_f = float(input("How many gallons were used?"))
print("Average miles per gallon (mpg) :", miles_f / gallons_f)
Lab Quiz One Comments
separate items in the print
function parameter list with commas
print(t_minutes, "minutes are the same as", hrs, "hour(s) and", min, "minutes." )