Lab: Introduction to Python

 


Introduction

The objectives of this lab are to become familiar with the interactive and script modes in Python, and to learn the basics of input, processing, and output in Python.

You will submit a text document with your answers to the problems posed in the lab.



Becoming familiar with Spyder

  1. Start up Anaconda by clicking on the Navigator application in your Anaconda folder. Once that has opened, launch Spyder. (Spyder is the Scientific PYthon Development EnviRonment that we will be using to write, test, and debug our programs.)
    When Spyder launches for the first time, there are many panes already open. Since we are new to programming, most of these panes will not make any sense to us at this point. So we will close all except two of these panes. To do this, go to View->Panes at the top of the screen and unclick all of the options EXCEPT Editor and iPython console. Your screen should look much less complex now.
  2. To start becoming familiar with the Spyder graphical user interface, type some simple Python commands into the iPython console. (This is the right side of the Spyder window.) You might try something like the following commands:
    print(3 + 4)
    print("Hello class")
    print("Hello" + "class")
    print("Hello", "class")
    Stop and Think: (These questions are to think about; they do not need to be submitted.) What happened when you typed in these statements? Could you type them all at once and then get your output, or did you type them one at a time, getting a result after each one? Was that what you expected?
  3. Now click anywhere in the Editor, and then go to File->New File. This will create a new file in your Editor.
  4. In this new file, type the same four statements that you typed in the iPython console.
    Stop and Think: What happened this time? Did you get any output? Was this what you expected?
  5. This file you created is called a Python script. Save this script by going to File->Save As. Choose a name for this script such as Lab1.py, and then choose the folder in which you'd like to save your work. It would be a good idea to create a COMP108 folder to keep all of your work for this class in one place.
  6. You probably did not get any ouput from this script yet. A script gives us a way to write many statements and then save them in a file. The Python interpreter can then execute that block of statements. To execute these statements in Spyder, click on the green arrow in the tool bar at the top of the Editor pane. If you get a question about the Run settings, you can choose to execute in the current iPython console.
    Stop and Think: What happened now? Did you get any output? If so, where did your output appear?
  7. Problem 1: (This is the first of the problems to be typed up for submission.) Write a few sentences to describe the similarities and differences between using the iPython console and the Editor in Spyder.


Working with Strings

You may do this next set of exercises in either the iPython console or the Editor.
  1. In the previous exercises, you may have noticed that when you executed the statement print "Hello" + "class", the resulting output had no space between the two words. Experiment with this statement so that the output contains a space between the two words.
  2. Rewrite the second two print statements above using single quotes around the text instead of double quotes. You should still get the same output; do you?
  3. If we have a statement such as I'm here that needs to be printed, we could not enclose the string within single quotes. (Why not?) We must use double quotes. Type in a print statement to test this.
  4. Python also allows us to enclose string literals in triple quotes (either """ or '''). Triple quoted strings can contain both single quotes and double quotes as part of the string.
    For example, print """I'm reading "Hamlet" tonight.""" Type in this example and experiment with what happens when you replace the single quote with a double quote, the double quote with a triple quote and the triple quote with a single quote. .
  5. Problem 2: Write down a statement that displays the following text: COMP108's textbook is "A Primer on Scientific Progamming with Python". (You may want to try typing your line of code in the iPython console to be sure it works!)


Comments

Comments are an integral part of every program. They are explanations of different lines or sections of a program. The Python interpreter ignores them - they are included in a program so that people who read the code may better understand what it does.

Single line comments in Python begin with the # character. For good programming style, every script you write should contain comments at the beginning that give your name, the date, and a description of the purpose of the script. For example, the script containing the print statements above might look like the following:

# Pam Cutter
# September 12, 2017
# Modified on September 14, 2021 to update for Python 3
# This script contains a few print statements
# to explore different aspects of printing

print(3 + 4)
print("Hello class")
print("Hello" + "class")

Comments that span more than one line may be placed inside a pair of """. The previous example would look like the following, using the multi-line comment:

"""
Pam Cutter
September 12, 2017
This script contains a few print statements
to explore different aspects of printing
"""
print(3 + 4)
print("Hello class")
print("Hello" + "class")
  1. Add comments to the script you created for this lab.

Variables

Variables are names that represent values stored in the computer's memory. In this section we will practice creating, assigning, and using variables. The exercises in this section should be done in the Editor.
  1. In the same script you created for the previous exercises, create a variable that has your name as its value. (Put the statement that you write to do this after the other code in the script.)
  2. Write a statement that prints out your name by using your newly created variable.
  3. Problem 3: Write a statement that prints out Hello yourname. Today is dayOfTheWeek. where yourname gets its value from your variable and dayOfTheWeek is another variable that you create and initialize.

  4. Variables can also store numeric values. You may be familiar with the Celsius-Fahrenheit conversion formula. (See Section 1.3 if you need a reminder.) In this exercise, we are going to create variables for a Fahrenheit-Celsius conversion. Create variables F and C so that F is the independent variable and C is the dependent variable. (This means you need to first assign a value to the variable F, and can then determine the value for C based on the formula.) Print out the value of C.

Keyboard Input

Programs commonly need to read input from the user. In this section we will see how to do this with Python's built-in input function. (The input function in Python 3 works the same as the raw_input function in Python 2.7.)
  1. Use keyboard input to enter a name that gets stored in the variable name and then print out the value of that variable.

    Problem 4: Write down the statements that would be needed to get a name from the user and then print out "Hello" with that name. For instance, if the user entered Pam, the output would be Hello Pam.

  2. In a previous exercise, when you explored the Fahrenheit-Celsius conversion, you assigned a value to F and then computed the value of C. Now create a line of code that assigns the value of F from user input. Then calculate the value of C and print it out.

  3. Experiment with Exercise 4.6 (from the textbook, page 217). Where it states "Make a program that..." you may assume it means write a couple lines of code.
  4. Problem 5: In your own words, describe why the float and int functions are included with some input statements but not others. When do you need to apply the eval function?


Calculations

Python has numerous operators that can be used to perform mathematical calculations. Most of these are the same that you would use in a math class, although there are a few that may not have been encountered in a math class.
  1. Based on your understanding of the math operators in Python, write down what you expect the answers to these statements will be:
  2. Now type these statements in the iPython console or as print statements in your script to test your predictions.
  3. Stop and Think: How did the actual results of these statements compare with your expected results? Did they agree? If so, great job - you understand these operators! If not, make sure you understand what you missed. Feel free to discuss with the instructor or a TA if necessary.

  4. Based on your understanding of the precedence of math operators, write down what you expect the answers of these statements will be:

  5. Test your predictions in the iPython console or as print statements in your script.
    Stop and Think: How did your actual results compare with your predicted results? Discuss with an instructor or TA if you do not understand any differences.

  6. Type in and test the code in Exercise 1.8 in your text.

Problem 6: Write statements to complete the following program:


Submit

Turn in your answers to the problems in these exercises and the script you saved. (Submit these 2 documents on Kit. Be sure your name is on both of them.)