L 02 W S P P: CSC121 Python Programming
L 02 W S P P: CSC121 Python Programming
OBJECTIVES
In this lesson, students will learn:
- To use variables to store data
- To write statements to get input
- To write statements to perform calculations
- To write statements to display output
2.1 INTRODUCTION
In this lesson, we will learn how to write Python code to implement these steps.
2.2 VARIABLES
Before we look at how to write Python statements to get input, perform calculations
and display output, let’s start with a very important concept: variables.
Most computer programs need to work with data. Many programs start with asking
user to enter input. For example, a program that calculates the sum of two numbers
may ask the user to enter two numbers when the program begins. The two numbers
entered by the user are data. The program must store the input values in computer
memory so they can be used later in the program.
memory space to store the sum. If the sum is not stored in memory, it will be
unavailable when the program tries to display or use it later.
Inside a Python program, we use something called variables to represent data stored
in computer memory. Each variable in a program is associated with a cell in the
computer’s memory. The data item stored in the memory cell is called the value of the
variable.
Every variable in a simple Python program must have a unique name. The program
uses the variable name to tell the computer which memory location it wants to access.
We usually make up a meaningful name so we can tell what is stored in that memory
cell from the name. For example, we may use the name sum for the variable that
stores the sum of two numbers.
1. A name consists of a series of characters, but not all characters can be used in a
name. Only letters, digits, and the underscore symbol can be used. For example,
the names ssn and s_s_n are valid but the name s.s.n. is invalid because
periods are not allowed.
2. The first character of a name can be a letter or underscore, but it cannot be a digit.
For example, the name 1st_test is invalid because it starts with a digit.
3. Uppercase and lowercase letters are different. For example, height and Height
are considered two different names because the letter H is in lowercase in the first
name but in uppercase in the second name.
4. Python has a set of keywords. Every keyword has a special meaning. We cannot
name a variable which is exactly the same as one of the keywords. For example,
the word raise is a keyword in Python. Therefore, we cannot name a variable as
raise. The following are keywords in Python:
and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class exec in pass yield
continue finally is raise
def for lambda return
5. We cannot have space in a name. For example, the name midterm exam score
is invalid because there are spaces between words.
______________________________________________________________________________________________________________________________________________________________________________________________________________________
In addition to the rules listed above, there are some conventions we should follow when
we name Python variables:
1. Use all lowercase letters. Variable names such as height, age and gpa are good,
while Height, Age and GPA are not good variable names.
2. If a variable name consists of multiple words, separate the words with underscores
to improve readability. Examples: midterm_exam_score, discount_price.
You don’t have to have complete words, especially when they are long. Examples:
soc_sec_num, avg_score.
3. Variable names should be descriptive. Avoid using meaningless names such as x
and y unless these variables are really trivial.
age = 16
When the computer executes this statement, it stores 16 in a memory cell. Each
memory cell has a unique address. The computer uses memory address to keep track
of where a data item is stored. Suppose 16 is stored in the memory cell with the
address 501462. Later when the program needs to retrieve this data item, it must go
to the memory cell 501462 to retrieve 16 from there.
The left hand side of the assignment statement creates a variable named age. The
computer will find a memory cell for this variable. Later when we need to access the
data item, we can use the variable name to access it. We don’t need to know the
memory address of the cell. Example:
age_next_yr = age + 1
The computer will do three things when it executes this assignment statement:
(1) Retrieves 16 from the memory cell associated with the variable age
(2) Calculates 16 + 1
(3) Store the result 17 in a memory cell and associate the memory cell with the
variable age_next_yr. Programmers typically simply say “store 17 in variable
age_next_yr”.
______________________________________________________________________________________________________________________________________________________________________________________________________________________
Let’s introduce a technical terms. A literal is something in the program code that should
be taken at its “face value”. For example, 16 in the following statement is a literal
because it simply means the numerical value 16:
age = 16
Similarly, 3.52 in the following statement is a literal because it simply means the
numerical value 3.52:
gpa = 3.52
In the opposite, age and gpa are not literals. They are variables. Their values depend
on what are stored in the memory cells associated with them.
We can store different types of data in Python programs. The most common types
include text, integers and floating point numbers (i.e. numbers with decimal point).
Different types of data are stored in computer memory in different ways, and some
operations may be inappropriate for some types. For example, it makes sense to divide
a number by 2.5, but it does not make sense to divide the text Hello by 2.5.
Python has a few built-in data types to store texts and numbers. The type str, which
is also called string type, is used to store text. A string is a sequence of characters. For
example, when Wake Tech is stored in a variable, its type is str and it is encoded in
computer memory in a way specially designed to store characters.
The string literal Wake Tech is stored in the variable college. You need to enclose
string literals in quotes. In fact, the Python interpreter uses the quotes to tell Wake
Tech is a string literal. Without the quotes, the Python interpreter will get confused
when it reads the statement:
It will mistakenly view Wake Tech as the name of a variable and give you a syntax
error.
You can choose to use either single or double quotes for string literals. Example:
This statement is the same as the previous statement that uses single quotes. Both
statements stores the 9-character string literal Wake Tech in the variable college.
Python allows us to use either single quotes or double quotes to avoid possible
confusions. Look at the following example,
This statement will successfully store the 15-character literal in the variable
movie_name, but the following statement will not:
The problem with the statement that uses single quotes is that the Python interpreter
will mistakenly view the apostrophe between the letter e and s as a quote and think
you have syntax error in the statement.
Python has two types for numerical values: int and float. They are also called
integer type and floating point type. Integer type stores whole numbers such as 17
and -25. Floating point type stores numbers with decimal point such as 3.27 and
-16.2548. Integers and floating point numbers are encoded in computer memory in
very different ways. Exactly how they are encoded is beyond the scope of this course.
age = 16
Since 16 is a whole number, Python will store 16 as an integer. That means in the
memory cell associated with age, 16 is encoded in the format designed for integers.
The following statement stores 3.52 as a floating point number because 3.52 has a
decimal point:
gpa = 3.52
Look at the following statement. What type will be used to store 17.0?
age = 17.0
Since 17.0 has a decimal point, it will be stored as a floating point number.
course = 'CSC121'
Look at the following statement. What type will be used to store 17?
age = '17'
17 will be stored as a string because the quotes make Python view 17 as a two-
character string instead of an integer.
age = '17'
age_next_yr = 1 + age
Python cannot add 1 to age because age is not a number. The following is the error
message:
2.3.2 OPERATORS
half_price = full_price / 2
______________________________________________________________________________________________________________________________________________________________________________________________________________________
half_price = full_price // 2
The result of this operation is the largest integer smaller than the result of division. If
full_price is 15, half_price will be 7. The reason is that 15 / 2 equals 7.5 The
largest integer smaller than 7.5 is 7. Similarly, if full_price is 8, half_price will
be 8.
r = p % q
r = p ** q
2.3.3 EXPRESSIONS
x = 2 + 5 * 4
______________________________________________________________________________________________________________________________________________________________________________________________________________________
x = (2 + 5) * 4
We need statements to display output in a program. The computer will not display any
output if the program does not tell it to do so. A program is pretty useless if the user
does not see any output.
The string literal This is my first program is displayed because this string literal
is placed inside the parenthesis of the print function. Similarly, the statement
print('Programming is fun!')
Programming is fun!
If we place the name of a variable inside the parenthesis, the computer will display the
value of the variable. See this example:
age = 16
age_next_yr = age + 1
print(age_next_yr)
______________________________________________________________________________________________________________________________________________________________________________________________________________________
The program above displays 17, which is the value stored in the variable age_next_yr.
The user may get confused if we only display the value of age_next_yr. we should
display some description to explain what that output is:
age = 16
age_next_yr = age + 1
print('Age next year:')
print(age_next_yr)
We can shorten the program by combining the two print functions into one:
age = 16
age_next_yr = age + 1
print('Age next year:', age_next_yr)
You can display as many items as you want with one single print function. Simply
place all the items you want to display inside the parenthesis and separate them with
commas. When those items are display, a space will be inserted between them by
default. Example:
age = 16
age_next_yr = age + 1
print('You are', age_next_yr, 'years old next year.')
The print function displays three items: the string You are, the value of
age_next_yr, and the string years old next year. The following is the new
output:
The age program we saw earlier is quite useless because it only calculates new age of
persons who are 16 years old this year. It cannot be used for people who are not 16.
What is missing from these programs is the ability for the user to enter data into the
program when the program is running.
In Python, we use the input function to input data from keyboard. If we put the input
function on the right hand side of an assignment statement, the computer will read user
input from keyboard and store it in the variable on the left hand side. Example:
first_name = input()
The statement above stores whatever entered by the user in the variable first_name.
We need to display some text on the screen so the user will know what to enter. We
can insert a string inside the input function, which will display the string before it waits
for the user to enter input:
When the computer executes this statement, it will show Enter first name: on
the screen and then wait for the user to enter first name. Let’s use it in a program:
Instead of calculating and displaying age next year, the program actually gets the
following error message:
The reason is that when the input function is used to read user input from keyboard,
whatever entered by the user is stored as a string literal. That means when the user
type 17 on the keyboard, it is captured and stored as a string literal ‘17’. Since it is not
stored as a number, Python cannot use it in calculation.
2.5.2 TYPECASTING
Now we know that the age entered by the user is stored as a string literal. What can
we do to fix the problem? Fortunately there is a way to convert a string to a numerical
value. Look at the following code:
age = int(age)
right after we have got age from the user. What does this statement do? The right
hand side is an int function. What it does is finding the equivalent integer value of the
string age. For example, if the string '17' is stored in age, its equivalent integer value is
the integer 17. This integer is stored in the variable on the left hand side of the
assignment statement. Since the variable on the left hand side is the same variable
age, the integer 17 will be stored in age to replace the string '17'. When the computer
executes the next statement:
age_next_yr = 1 + age
Sometimes we need to convert input strings into floating point numbers. The float
function, which is similar to the int function, can be used to achieve this goal. The
following is an example:
______________________________________________________________________________________________________________________________________________________________________________________________________________________
Since we expect the user to enter numbers with decimal points, we need to use the
float function to convert the input strings into floating point numbers.
If you are not sure whether the user will enter integers or floating point numbers, you
should use float. It is okay to store a whole number as a floating point value. For
example, we can use the float function in the age program:
Suppose the user enters 17. The input string, which is stored in the variable age by
the first statement, will be converted to the floating point number 17.0 and stored in
age by the second statement. 1 + 17.0 is 18.0. Therefore 18.0 is stored in
age_next_yr by the third statement and displayed in the console window by the
fourth statement.
The example above uses one statement to store input string and another statement to
convert it into a numerical value. In fact, we can shorten the code by combining the
two statements into one. For example,
We directly put the input function inside the parenthesis of the float function.
When the computer executes this statement, it executes the input function first. As
soon as an input string is read from the keyboard by the input function, the input
string is sent to the float function immediately to be converted into a floating point
value before it is stored in the variable age. That means the input string was never
______________________________________________________________________________________________________________________________________________________________________________________________________________________
stored in the variable age. As soon as the variable age is created, a floating point
value is stored there. The following is the complete program code:
A store pays its hourly workers every two weeks. Write a program to calculate and
display the gross pay for an hourly worker.
Python Code:
The power of an air conditioner is measured in British Thermal Units (BTU). The higher
the BTU, the more heat the air conditioner can bring away. When people buy an air
conditioner, they need to know how many BTU they need to keep the room cool. Write
a program to estimate how many BTU we need when we install a window air
conditioner in a room. This number is determined by the volume of the room. The rule
of thumb is that we need 3.5 BTU per cubic foot. The program should ask the user to
enter the length, width and height of the room. It should calculate and display the
number of BTU needed for the air conditioner.
Python Code:
It is good to know how Python interacts with computer memory. When we create a
new variable, Python stores its value in a memory cell and associates the variable to
that cell. Example:
score = 75
print(score)
Suppose 75 is stored in memory cell with the address 524617 and score is associated
to that cell. When the computer executes the print statement, 75 will be retrieved
from cell 524617 and displayed.
score = 75
score = 85
print(score)
Python will store the new value 85 in a new cell (suppose the cell 524700 is used) and
will change the association of score to this new cell. When we use the print
statement to display score, the computer retrieves the value 85 from cell 524700 and
displays 85.
score
Memory cell 524700
Data stored: 85
______________________________________________________________________________________________________________________________________________________________________________________________________________________
Since the memory cell 524617 is not associated to score, it will be reclaimed and
reused to store something else.
Next, let’s see what happens when we copy the value of one variable to another
variable.
x = 17
y = x
When the first statement is executed, Python stores 17 in a memory cell (suppose the
cell 411456 is used) and associate the variable x to it. When the second statement is
executed, Python does not use a new memory cell to store the value of y. Instead, it
associates the variable y to cell 411456, which is the same cell associated to x. In
other words, there is only one cell in the memory that stores 17 and it is associated to
two variables.
x
Memory cell 411456
Data stored: 17
x = 17
y = x
y = 24
Python will store 24 in another cell (suppose cell 422167 is used) and the association of
y is changed:
x
Memory cell 411456
Data stored: 17
y
Memory cell 422167
Data stored: 24
We can use the addition operator to combine two strings into one. Example:
first_name = 'Thomas'
last_name = 'Edison'
full_name = first_name + last_name
print(full_name)
The strings Thomas and Edison are concatenated to form a new string. Output:
ThomasEdison
We can modify the program above to insert a space between first and last names.
first_name = 'Thomas'
last_name = 'Edison'
full_name = first_name + ' ' + last_name
print(full_name)
Output:
Thomas Edison
String functions can be used to convert a number into a string. For example, str(17)
converts the integer 17 into the string ‘17’. String function is useful when we want to
concatenate a string and a number to form a new string. Example:
unit_price = 1.50
quantity = 4
total = unit_price * quantity
output_string = 'Please pay $' + str(total)
print(output_string)
In the program above, total is a number. Python does not allow us to concatenate a
string and a number. Therefore, we use the string function to convert total into a
string before it is concatenated with another string. Output:
We can insert some special characters, such as tab or new line, into a string to format
output. These are called escape characters. Two of the most commonly used escape
characters are \n and \t.
The escape character \n inserts a new line character into a string. Example:
Output:
DBA110
Tuesday 2-4 PM
When the string course_info is displayed, the new line character sends the cursor to
the next line after DBA110 so Tuesday 2-4 PM is displayed in a separate line.
Another example:
unit_price = 1.50
quantity = 4
total = unit_price * quantity
output_string = 'Unit price: $' + str(unit_price) + '\n' +
'Total: $' + str(total)
print(output_string)
In the program above, an output string is created and displayed. A new line character
is inserted in the output string so it will be displayed in two separate lines. Output:
print('10\t201\t410')
print('276\t62\t56')
The program above displays two lines of numbers. Tab characters are inserted in the
strings to align the numbers properly . Output:
10 201 410
276 62 56
______________________________________________________________________________________________________________________________________________________________________________________________________________________
We saw how to use commas to separate items we want to display with the print
function. In fact, Python allows us to insert items into a string, and this can be used to
display multiple items with the print function. Example:
The %s in the string 'Course added: %s' is a place holder. It tells Python we want
to insert another string right there. The %course right after the string specifies what
we want to insert. Sample test run:
We can use %s multiple times to insert multiple items into a string. Example:
This time we use two %s to insert two items. The %(course, prerequisites)
right after the string tells Python we want to put course and prerequisites where
the first and second place holders are, respectively. Sample test run:
In addition to inserting strings into another string, we can also insert numbers.
Example:
Enter age: 17
You will be 18.0 years old next year
______________________________________________________________________________________________________________________________________________________________________________________________________________________
17 is entered by the user, which is converted into 17.0 by the float function and
stored in age. The value of age_next_yr, which is 18.0, is converted into a string
and inserted into the other string.
When we insert a number into a string, we can use %d or %f to control how the number
is displayed. When %d is used, the number will be displayed as an integer. If the
number itself is a floating point number, the decimal point and digits after the decimal
point will be dropped. Example:
Since age is 17.7, age_next_yr is 18.7. However, since %d is used as place holder,
age_next_yr is truncated from 18.7 to 18 when it is inserted into the string.
Enter age: 17
You will be 18.000000 years old next year
The place holder %.2f tells Python that we want two decimal places when the number
is inserted into the string. Sample test run:
Enter age: 17
______________________________________________________________________________________________________________________________________________________________________________________________________________________
Another example:
2.8.4 F-STRINGS
F-string is a new way in Python to insert items into a string. Also called “formatted
string literals,” f-strings are string literals that have the letter ‘f’ or ‘F’ before it and curly
braces containing expressions that will be replaced with their values. Example:
Enter age: 17
You will be 18.0 years old next year
The syntax {age_next_yr:.2f} specifies two decimal places. That’s why 18.5678 is
rounded to 18.57 when it is inserted into the f-string.