Chapter 2

Running Python

Python code can be input and run in a variety of ways:

  • Active code window (or box or cell)
  • in a shell or console - input lines are typed one-by-one, following the prompt >>> and interpreted. The response is given on the following line
  • in a file created using some editor or integrated development environment (IDE) - we will be using PyCharm as an IDE. It also include a console option.
\(\boxdot\) Active Code Windows and pythontutor.com

Please 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

Sections 2.1 - 2.6

\(\boxdot\) Values, Objects and Class
  • A value can be a number or a word
  • value == object (the words value and object are used interchangeably)

In Python, everything is an object.

  • All objects are classified by Class or Data Type (pretty much interchangeable with some finer points)
  • Three basic classes in Python are:
    • str – string, denoted by single (‘’), double (" “), or triple quotes (‘’’ ‘’’, or”“” “”“), e.g. ‘blue sky’
    • int – integer, whole numbers (no decimal points), e.g. 1200 (with NO COMMA)
    • float – floating point (decimal) numbers, e.g. 569.32
  • Remember (from your mathematics background) that a function is a process that takes one or more inputs, and creates (and returns) one or more outputs. A function is well-defined because the same inputs (in the same order) always returns the same outputs (in the same order)
  • 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).

\(\boxdot\) Type Conversion Functions

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"))
\(\boxdot\) Variables or Object References
  • Objects are either immutable or mutable. That is, invariable or variable
  • The str object ‘Hello, World!’ is immutable.
  • The 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)
\(\boxdot\) Variable Names and Keywords

Variable names:

  • unlimited length
  • can contain both letters and digits
  • no spaces
  • must begin with a letter (lowercase, by convention, but can be an uppercase letter) or underscore _
  • underscores are used to create variable names made from multiple words e.g. student_name = ‘Mary Jones’
  • case sensitive
  • cannot be a keyword, words that make up the language’s syntax and structure
\(\boxdot\) Statement and Expressions
  • 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.

Sections 2.7 - 2.11

\(\boxdot\) Input Function
  • 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.

\(\boxdot\) Operators and Operands
  • 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

\(\boxdot\) Operators of Note
print(10 / 3)  
print(10 // 3)  
print(10 % 3)  
\(\boxdot\) Order of Operations
  • Expressions typically have multiple operands.

  • The execution order matters, so rules dictating the order of operations, or precedence, must be established.
    • exponentiation (**) precedes multiplication (*) and division (/), and the latter precedes addition (+) and subtraction (-)
    • operations of equal precedence are executed in left-to-right order (left-association)
      • 16 / 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
\(\boxdot\) Reassignment & Updating Variables
  • 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

\(\boxdot\) Further Activities (These activities will not be graded. Use the corresponding active code window number for the corresponding chapter lab exercises found on the course assignment list to work out and save a solution for future reference.)
  • 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 //.

\(\boxdot\) Homework & Quiz Comments
  • 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

    • Avoid leaving blank lines
    • pi = float(3.1415) - the parentheses are unnecessary
    • separate items in the print function parameter list with commas

      print(t_minutes, "minutes are the same as", hrs, "hour(s) and", min, "minutes." )