Computer Programming
-- Python
Lecture 1
Introduction, Variables,
and I/O
Dr. I-Fan Lin Copyright © 2018 Pearson Education, Ltd.
Using Python
• Python must be installed and configured
prior to use
– One of the items installed is the Python
interpreter
• Python interpreter can be used in two
modes:
– Interactive mode: enter statements on keyboard
– Script mode: save statements in Python script
2
Interactive Mode
• When you start Python in interactive mode,
you will see a prompt
– Indicates the interpreter is waiting for a Python
statement to be typed
– Prompt reappears after previous statement is
executed
– Error message displayed If you incorrectly type a
statement
• Good way to learn new parts of Python
3
Writing Python Programs and
Running Them in Script Mode
• Statements entered in interactive mode are
not saved as a program
• To have a program use script mode
– Save a set of Python statements in a file
– The filename should have the .py extension
– To run the file, or script, type
python filename
at the operating system command line
4
The IDLE Programming
Environment
• IDLE (Integrated Development Program):
single program that provides tools to write,
execute and test a program
– Automatically installed when Python language is
installed
– Runs in interactive mode
– Has built-in text editor with features designed to
help write Python programs
Text Editor Interpreter/Compiler Debugger
5
Designing a Program
• Programs must be designed before they are
written
• Program development cycle:
– Design the program
– Write the code
– Correct syntax errors
– Test the program
– Correct logic errors
6
Flowcharts
• Flowchart: diagram that graphically depicts
the steps in a program
– Ovals are terminal symbols
– Parallelograms are input and output
symbols
– Rectangles are processing symbols
– Symbols are connected by arrows
that represent the flow of the program
7
Colaboratory
• a document that allows you to write, run, and
share Python code within your browser.
• access Google Colab at
colab.research.google.com
• to create a new document from any screen,
select “File” in the top left corner, then select
“New Notebook” from the dropdown box
8
Colaboratory
1. 2.
3. (optional)
9
Colaboratory
To add a code cell or a text cell
• Use Markdown to edit the text
https://www.markdownguide.org/basic-syntax/
• Edit text
10
Input, Processing, and Output
• Typically, computer performs three-step
process
– Receive input
• Input: any data that the program receives while it is
running
– Perform some process on the input
• Example: mathematical calculation
– Produce output
11
Displaying Output with the
print Function
• Function: piece of prewritten code that performs an
operation
• print function: displays output on the screen
• Argument: data given to a function
– Example: data that is printed to screen
• Statements in a program execute in the order that
they appear
– From top to bottom
Show the result
12
Strings and String Literals
• String: sequence of characters that is used as data
• String literal: string that appears in actual code of a
program
– Must be enclosed in single (') or double (") quote marks
– String literal can be enclosed in triple quotes (''' or """)
• Enclosed string can contain both single and double quotes and
can have multiple lines
13
Checkpoint
• Write a statement that displays your name
• Write a statement that displays the following text:
Python’s the best!
The cat said "meow."
14
Comments
• Comments: notes of explanation within a program
– Ignored by Python interpreter
• Intended for a person reading the program’s code
– Begin with a # character
• End-line comment: appears at the end of a line of
code
– Typically explains the purpose of that line
15
Literals
Int Float String Bool
• 12 • 3.14 • “abc”
• 105 • -2.666 • “-123” • True
• -3 • 1.23e-10 • ‘Hello’ • False
• 0 • 0.00 • ‘10.39’
• Use Type to check the literals
16
Variables
• Variable: name that represents a value stored in
the computer memory
– Used to access and manipulate data stored in memory
– A variable references the value it represents
• Assignment statement: used to create a variable
and make it reference data
– General format is variable = expression
• Example: age = 29
• Assignment operator: the equal sign (=)
17
Variables
• In assignment statement, variable receiving
value must be on left side
• A variable can be passed as an argument to
a function
– Variable name should NOT be enclosed in quote
marks
• You can only use a variable if a value is
assigned to it
18
Variable Naming Rules
• Rules for naming variables in Python:
– Variable name cannot be a Python key word
– Variable name cannot contain spaces
– First character must be a letter or an underscore
– After first character may use letters, digits, or
underscores
– Variable names are case sensitive
• Variable name should reflect its use
19
Variable Examples
20
Variable Examples
21
Numeric Data Types, Literals,
and the str Data Type
• Data types: categorize value in memory
– e.g., int for integer, float for real number, str used
for storing strings in memory
• Numeric literal: number written in a program
– No decimal point considered int, otherwise, considered
float
22
Reassigning a Variable to a
Different Type
• A variable in Python can refer to items of any
type
2024/8/27 23
Checkpoint
• Which of the following are illegal variable names in Python?
x
99bottles
july2009
theSalesFigureForFiscalYear
r&d
grade_report
• What will the following code display?
val = 99
print('The value is', 'val')
• What will be displayed by the following program?
my_value = 99
my_value = 0
print(my_value)
24
Reading Input from the
Keyboard
• Most programs need to read input from the user
• Built-in input function reads input from keyboard
– Returns the data as a string
– Format: variable = input(prompt)
• prompt is typically a string instructing user to enter a value
– Does not automatically display a space after the prompt
25
Reading Numbers with the
input Function
• input function always returns a string
• Built-in functions convert between data types
– int(item) converts item to an int
– float(item) converts item to a float
– Nested function call: general format:
function1(function2(argument))
• value returned by function2 is passed to function1
– Type conversion only works if item is valid numeric value,
otherwise, throws exception
26
input Function Example
27
Performing Calculations
• Math expression: performs calculation and gives a
value
– Math operator: tool for performing calculation
– Operands: values surrounding operator
• Variables can be used as operands
– Resulting value typically assigned to variable
• Two types of division:
– / operator performs floating point division
– // operator performs integer division
• Positive results truncated, negative rounded away from zero
28
Calculations Example
A retail business is planning to have a storewide sale where the prices of all items will be 20 percent off.
1. Get the original price of the item
2. Calculate 20 percent of the original price. This is the amount of the discount
3. Subtract the discount from the original price. This is the sale price
4. Display the sale price
29
Operator Precedence and
Grouping with Parentheses
• Python operator precedence:
1. Operations enclosed in parentheses
• Forces operations to be performed before others
2. Exponentiation (**)
3. Multiplication (*), division (/ and //), and remainder (%)
4. Addition (+) and subtraction (-)
• Higher precedence performed first
– Same precedence operators execute from left to right
30
Example
Determining the average of a group of values.
1.Get the first test score
2.Get the second test score
3.Get the third test score
4.Calculate the average by adding the three test scores and dividing the sum by 3
5.Display the average
31
The Exponent Operator and
the Remainder Operator
• Exponent operator (**): Raises a number to
a power
– x ** y = xy
• Remainder operator (%): Performs division
and returns the remainder
– a.k.a. modulus operator
– e.g., 4%2=0, 5%2=1
– Typically used to convert times and distances,
and to detect odd or even numbers
32
Example I
33
Example II
You want to deposit a certain amount of money into a savings account and leave it alone to draw interest
for the next 10 years. At the end of 10 years, you would like to have $10,000 in the account. How much
do you need to deposit today to make that happen?
1.Get the desired future value
2.Get the annual interest rate
3.Get the number of years that the money will sit in the account
4.Calculate the amount that will have to be deposited
5.Display the result of the calculation in step 4
34
Mixed-Type Expressions and
Data Type Conversion
• Data type resulting from math operation depends
on data types of operands
– Two int values: result is an int
– Two float values: result is a float
– int and float: int temporarily converted to float,
result of the operation is a float
• Mixed-type expression
– Type conversion of float to int causes truncation of
fractional part
35
Breaking Long Statements
into Multiple Lines
• Long statements cannot be viewed on screen
without scrolling and cannot be printed without
cutting off
• Multiline continuation character (\): Allows to break
a statement into multiple lines
result = var1 * 2 + var2 * 3 + \
var3 * 4 + var4 * 5
36
Breaking Long Statements
into Multiple Lines
• Any part of a statement that is enclosed in
parentheses can be broken without the line
continuation character.
print("Monday's sales are", monday,
"and Tuesday's sales are", tuesday,
"and Wednesday's sales are", Wednesday)
total = (value1 + value2 +
value3 + value4 +
value5 + value6)
37
More About Data Output
• Print function displays line of output
– Newline character at end of printed data
– Special argument end='delimiter' causes print to
place delimiter at end of data instead of newline
character
38
More About Data Output
• print function uses space as item separator
– Special argument sep='delimiter' causes print to
use delimiter as item separator
39
More About Data Output
• Special characters appearing in string literal
– Preceded by backslash (\)
• Examples: newline (\n), horizontal tab (\t)
– Treated as commands embedded in string
• When + operator used on two strings in performs
string concatenation
– Useful for breaking up a long string literal
40
Examples
41
Examples
42
Formatting Numbers
• Can format display of numbers on screen using
built-in format function
– Two arguments:
• Numeric value to be formatted
• Format specifier
– Returns string containing formatted number
– Format specifier typically includes precision and data
type
• Can be used to indicate scientific notation, comma separators,
and the minimum field width used to display the value
43
Examples
44
Displaying Formatted Output
with F-strings
• An f-string is a special type of string literal
that is prefixed with the letter f
• F-strings support placeholders for variables
45
Displaying Formatted Output
with F-strings
• Placeholders can also be expressions that
are evaluated
46
Displaying Formatted Output
with F-strings
• Format specifiers can be used with
placeholders
• .2f means:
– round the value to 2 decimal places
– display the value as a floating-point number
47
Displaying Formatted Output
with F-strings
• Other examples:
48
Displaying Formatted Output
with F-strings
• Specifying a minimum field width:
Field width = 12
The number is 12,345.68
Field width = 12
49
Displaying Formatted Output
with F-strings
• Aligning values within a field
– Use < for left alignment print(f'{num:<20.2f}')
– Use > for right alignment print(f'{num:>20.2f}')
– Use ^ for center alignment print(f'{num:^20.2f}')
• The order of designators in a format specifier
– When using multiple designators in a format specifier, write them in
this order:
[alignment][width][,][.precision][type]
– Example:
• print(f'{number:^10,.2f}')
50
Displaying Formatted Output
with F-strings – Examples
51
Displaying Formatted Output
with F-strings – Examples
52
Displaying Formatted Output
with F-strings – Examples
• print(f"{variable:5.2f}")
53
Displaying Formatted Output
with F-strings – Examples
• print(f"{variable:5.2f}")
left-aligns center-aligns
right-aligns
54
Magic Numbers
• A magic number is an unexplained numeric
value that appears in a program’s code.
Example:
amount = balance * 0.069
• What is the value 0.069? An interest rate? A
fee percentage? Only the person who wrote
the code knows for sure.
55
The Problem with Magic
Numbers
• It can be difficult to determine the purpose of the number.
• If the magic number is used in multiple places in the
program, it can take a lot of effort to change the number in
each location, should the need arise.
• You take the risk of making a mistake each time you type
the magic number in the program’s code.
– For example, suppose you intend to type 0.069, but you accidentally
type .0069. This mistake will cause mathematical errors that can be
difficult to find.
56
Named Constants
• You should use named constants instead of magic numbers.
• A named constant is a name that represents a value that
does not change during the program's execution.
• Example:
INTEREST_RATE = 0.069
• This creates a named constant named INTEREST_RATE,
assigned the value 0.069. It can be used instead of the
magic number:
amount = balance * INTEREST_RATE
57
Example
58
Advantages of Using Named
Constants
• Named constants make code self-
explanatory (self-documenting)
• Named constants make code easier to
maintain (change the value assigned to the
constant, and the new value takes effect
everywhere the constant is used)
• Named constants help prevent typographical
errors that are common when using magic
numbers
59
Exercise I
• A company has determined that its annual
profit is typically 23 percent of total sales.
Write a program that asks the user to enter
the projected amount of total sales, then
displays the profit that will be made from that
amount.
60
Exercise II
• A customer in a store is purchasing five
items. Write a program that asks for the price
of each item, then displays the subtotal of
the sale, the amount of sales tax, and the
total. Assume the sales tax is 7 percent.
61