Introduction to Python

PART I: Practice

Using the Python Interpreter

We will use the Python interactive interpreter to learn various elements of the language. An interpreter is similar to a compiler (we will cover this topic in class) – it converts the high-level programming language (Python) into a language the CPU can understand. However, with an interpreter, you can enter your program one instruction at a time and the CPU will execute each instruction as soon as you enter it.

To start the Python interpreter: Select “Python 3.8” from the Windows program menu and select “IDLE (Python 3.8)”.

The prompt “>>>” is called the primary prompt. You can type Python expressions at this prompt.

Try the following command into the Python interpreter (Don’t type the >>>) and then press the Enter key on the keyboard.

>>> print (“Hello World!”)

This simply tells Python to print the characters “Hello World!” (without the quotation marks).

A collection of characters enclosed in a set of quotation marks is called a string. So the previous command told Python to print the string Hello World!

Python can also perform calculations. For example, type the following:

>>> print(4+8)

This command tells Python to perform the calculation 4+8 and the print it.

Python can also do subtraction. Type the following:

>>> print(90-48)

The symbols for multiplication and division are * and /, respectively.

Try the following examples:

>>> print(8*2)

>>> print(25/5)

You can use more than one arithmetic operator and mix arithmetic operators.

>>> print(5+7+8)

>>> print(8-2*3)

Notice that 8-2*3 produces the answer of 2. This is because Python performs mathematical operations according to the order of operations. According to the order of operations, multiplication must be done before subtraction.

According to the order of operations, mathematical operations are done in the following ordering: parenthesis, exponentiation, multiplication, division, addition, subtraction.

You can change the order of evaluation by placing mathematical expressions in parenthesis. For example:

>>> print ((8-2)*3)

This statement forces the expression 8-2 to be evaluated first and then the multiplication is performed.

Exponentiation is accomplished using the ** operator. For example to calculate we can calculate 5*5*5 using either of the following methods

>>> print (5*5*5)

>>> print (5**3)

Make sure you fully understand how Python calculates the answers to the following examples:

>>> print (2*4-3)

>>> print ((2*4)-3)

>>> print (10/(7-2))

>>> print (7+5-3)

>>> print (7+(5-3))

>>> print ((7*2)-(2+2))

>>> print ((3+2)**(4-2))

Notice the difference between string and arithmetic expressions. The Python interpreter evaluates arithmetic expressions, not strings.

Type in the following (notice the quotation marks):

>>> print (“7+3”)

You might think that Python would print 10. However, once you put the arithmetic expression in quotation marks it becomes a string and Python does not evaluate (perform mathematical operations on) strings. Therefore Python simply prints “7+3″ (without the quotes).

You can tell Python to print both strings and arithmetic expressions on the same line but you must separate them with a comma. For example:

>>> print (“7+5=”,7+5)

>>> print (7*8*2,” is the answer to 7 * 8 * 2″)

Variables in Python

A variable is just a name assigned to a particular value or string.

For example, if we want to store a year value in a variable name year then we type the following:

>>> year=2016

This tells Python to associate the value 2016 with the name year.

Note: When a # appears on a line in Python everything after the # sign is treated as a comment and is ignored by Python – it is only there for the benefit of the reader.

We can use the variable year just as if it were any other value.

Try the following examples.

>>> print (year)                 # notice that we DO NOT put year in quotes

>>> print (year+4)

>>> print (year-2)

>>> print ((year-2)+10)

>>> print (“The current year is “,year)    #remember to put in the comma

>>> print (“Two years from now it will be “, year+2)

You can overwrite variables with new values:

>>> year=2018      # the variable year now refers to 2018

>>> name=”John”

>>> name=”Jane”     # the variable name now refers to “Jane”

You can assign expressions to variables. Python evaluates the expressions and the resulting value is assigned to the variable.

Try the following examples:

>>> a=1+4         # the variable a now refers to the value 5

>>> b=5+9         # the variable b now refers to the value 14

>>> c=a+b         # the variable c now refers to the value 19

>>> c=c+1         # the variable c now refers to the value 20

The last example (c=c+1) requires some explanation. The variable c is assigned a value of one more than the old value of the variable c. Python first evaluates the right-hand side of the equal sign and then assigns the value to the variable. Therefore, the old value of c was 19 and we want Python to add one to it.

The new value of c is (19+1) which is equal to 20.

Python will remember variable values only while Python is running on your computer. Once you quit the Python interpreter, Python no longer remembers variable values. We will see how to get around this problem later.

The above is just an exercise to get yourself familiar with Python. You don’t need to save anything that you have done above.

To quit Python, select “Exit” from Python’s “File” pull-down menu.

PART II

In Part I, we used Python’s print statement to display strings, variables and the result of mathematical expressions. In Part II, we will write our Python programs in an editor. In addition, we will examine the “if statement”.

The Python Editor

We previously used the Python interpreter to enter very small programs. However, in order to write larger programs, we will use a program called an editor. An editor is similar to a word processor but with features designed to assist in writing a computer program (software).

Now, start IDLE (Python 3.8)” again. From the “File” pull-down menu select “New File”. A new “Untitled” window should appear. This is the window you will use to enter your Python program. Type (or copy) the following program into the “Untitled” window: (Make sure to type everything in lowercase letters – variable names and Python commands are case sensitive). Case sensitivity means that Python distinguishes between upper and lower case. So, for example, the variable “cis” is different from the variable “cIs” – they are considered distinct variable names in Python. Many modern programming languages are case sensitive.

revenue=1000

expenses=700

profit = revenue – expenses

print (“Goodbye!”)

From the “Run” pull-down menu in the “Untitled” window select “Run Module”. This tells Python to execute your program. However, before Python can run the program, you need to name the program so that it can be saved on disk. Click “OK” in the “Source must be saved” dialog box. You can save the program on the “Desktop” by selecting “Desktop” and then name the file – you can call it “first.py” (without the quotes). The “.py” ending is traditionally used for Python programs. Then click the “Save” button.

Once the file has been saved the program is executed in the Python Shell window. If you had any errors in your program, you will be brought back into the editor – the cursor will be situated at the point the error was found.

The previous program only allowed us to perform the addition operation on the variables. A better program would allow the user to select, from the keyboard, which operation should be performed on the variables. We can also read in the values used for revenue and expenses by using the input() statement. Select the “first.py” window and change the program so that it looks like the following.

revenue = int(input (“Your revenue?  “))

expenses = int(input (“Your expenses?  “))

profit = revenue – expenses

print (“Good bye!”)

Now run the program by selecting “Run Module” from the “Run” pull-down menu. You can keep the name “first.py” for this program.  The program now asks for you to enter a value for the revenue and another value for the expenses, and prints the result. You need to hit the “Enter” key after entering each value.

If Statement

Some solutions require that we compare two things and make a decision based on the result of the comparison.  We use if statement for these situations;

In the editor modify the program so that it looks like the following. Use the tab key to indent the line after the “if” statements. The statements indented under the “if” statement are only executed when the “if” statement evaluates to true.

revenue = int(input (“Your revenue?  “))

expenses = int(input (“Your expenses?  “))

if revenue > expenses:

profit = revenue – expenses

print (“Good bye!”)

Now run the program by selecting “Run Module” from the “Run” pull-down menu. The program now asks for you to enter a value for the score and prints the result. You need to hit the “Enter” key after entering each value.

If we also incorporate a feature that will tell us if there is a loss, we use the “else” statement for this purpose as follows:

revenue = int(input (“Your revenue?  “))

expenses = int(input (“Your expenses?  “))

if revenue > expenses:

profit = revenue – expenses

else:

loss = expenses-revenue

print (“This year, your firm lost “, loss, “dollars. “)

print (“Goodbye!”)

Now run the program again by selecting “Run Module” from the “Run” pull-down menu. The program now asks for you to enter a value for the score and prints the result. You need to hit the “Enter” key after entering each value.

To quit Python, select “Exit” from Python’s “File” pull-down menu.

Submit a copy of your first.py program via the Homework #8 Assignment of Moodle.

Part III: Questions

Answer the questions below (copy the questions to a new Microsoft Word document) and submit the document via the Homework #8 Assignment of Moodle.

1. What is a string?
• What is output from the following Python statement?

Print (5*6)

• What is the output from the following Python statement?

Print (“5*6”)

• Why does the Python interpreter produce different answers for questions 2 and 3?
• What is the output from the following Python statement?

Print (7-2*3)

• Why is the output for question 5 different from the output of the Python statement

Print ((7-2)*3)?

• What is a variable?

For Questions 8 through 12: Assume the following variable definitions (each question should be answered in isolation – the variable changes made in one question do not affect other questions).

B=10

C=20

D=30

• What is the output of the following Python statement?

print (B+C-D)

• What is the output of the following Python statements?

E=5

E=B+E

Print (E)

1. What is the final value assigned to variable C after the following Python statements are executed?

B=B+10

C=5

D=B+15

C=B+D

1. What is the final value assigned to the variable E after the following Python statements are executed?

B=2*2+5

E=B+2

E=E+1

1. What is the final value assigned to the variable F after the following Python statements are executed (note the quotation marks)?

C=”5+6″

D=”7*C”

F=”C+D”

1. Write a Python program that will display a message if a discount is applicable for a purchase. For this application, a discount will be applied if the purchase price is more than \$100. Your program will ask the user to enter a purchase price. Then your program will decide whether a discount should apply to this purchase. If a discount applies, your program should display “DISCOUNTED PRICE”, otherwise, it will display “FULL PRICE”. Your program should end with a “GOOD BYE” message.

Need help with this assignment or a similar one? Place your order and leave the rest to our experts!