0% found this document useful (0 votes)
11 views

Chapter 1 - CPIT110

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Chapter 1 - CPIT110

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Chapter 1

Introduction to Computers,
Programs, and Python
CPIT 110 (Problem-Solving and Programming)

Introduction to Programming Using Python, By: Y. Daniel Liang


Version 2.0
Sections
• 1.2. What is a Computer?
• 1.3. Programming Languages
• 1.4. Operating Systems
• 1.5. The History of Python
• 1.6. Getting Started with Python
• A Simple Python Program
• Simple Examples
• Anatomy of a Python Program
• 1.7. Programming Style and Documentation
• 1.8. Programming Errors
Programs Check Points Labs 2
Python Online IDE

Programs
• Program 1: Welcome with Two Messages
• Program 2: Welcome With Three Messages
• Program 3: Compute an Expression

3
Check Points
• Simple Examples
◦ #1
◦ #2
• Section 1.8
◦ #3

4
Objectives
• To understand computer basics, programs, and operating systems
(1.2-1.4).
• To write and run a simple Python program (1.5).
• To explain the basic syntax of a Python program (1.5).
• To describe the history of Python (1.6).
• To explain the importance of, and provide examples of, proper
programming style and documentation (1.7).
• To explain the differences between syntax errors, runtime errors,
and logic errors (1.8).

5
Textbook
Introduction to Programming Using Python, By: Y. Daniel Liang

6
1.2. What is a Computer?
§ CPU
§ Memory
§ Storage Devices
§ Output Devices
§ Input Devices

7
What is a Computer?
• A computer is an electronic device that stores and processes data.
• A computer includes both hardware and software.
• In general, hardware comprises the visible, physical elements of the
computer, and software provides the invisible instructions that
control the hardware and make it perform specific tasks.
• A computer consists of: CPU, memory, storage devices (such as disks
and CDs), input devices (such as the mouse and keyboard), output
devices (such as monitors and printers), and communication devices
(such as modems and network interface cards).

1.2 8
What is a Computer?
• A computer’s components are interconnected by a subsystem called
a bus.
• You can think of a bus as a sort of system of roads running among
the computer’s components; data and power travel along the bus
from one part of the computer to another.
• In personal computers, the bus is built into the computer’s
motherboard, which is a circuit case that connects all of the parts of
a computer together.
Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 9
A computer consists of

1.2 10
CPU
• The central processing unit (CPU) is the brain of a computer.
• It retrieves instructions from memory and executes them.
• The CPU speed is measured in megahertz (MHz).
• 1 megahertz equaling 1 million pulses per second.
Bus

Storage Communication Input Output


Memory CPU
Devices Devices Devices Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 11
CPU

1.2 12
Memory
• Memory is to store data and program instructions for CPU to
execute.
• A memory unit is an ordered sequence of bytes, each holds eight
bits. (a bit = 0 or 1)
• A program and its data must be brought to memory before they can
be executed.
• The current content of a memory byte is lost whenever new
information is placed in it.
Bus

Storage Communication Input Output


Memory CPU Devices
Devices Devices Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 13
Memory

1.2 14
Storage Devices
• Memory is volatile, because information is lost when the power is
off.
• Programs and data are permanently stored on storage devices and
are moved to memory when the computer actually uses them.
• There are three main types of storage devices: Disk drives (hard
disks and floppy disks), CD drives (CD-R and CD-RW), and Tape drives
(magnetic tape).

Bus

Storage Communication Input Output


Devices Memory CPU Devices Devices Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 15
Storage Devices

1.2 16
Output Devices
• An output device is any device used to send data from a computer
to another device or user.
• Most computer data output that is meant for humans is in the form
of audio or video such as monitors.
• The monitor displays information (text and graphics).
• The resolution and dot pitch determine the quality of the display.

Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 17
Output Devices

1.2 18
Input Devices
• An input device is any hardware device that sends data to a
computer.
• Input and output devices let the user communicate with the
computer.
• The most common input devices are keyboards and mice.

Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices

e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,


and Tape and NIC Mouse Printer

1.2 19
Input Devices

1.2 20
1.3. Programming Languages
§ Programs
§ Machine Language
§ Assembly Language
§ High-Level Language
§ Popular High-Level Languages
§ Interpreting/Compiling Source Code
§ Interpreting Source Code
§ Compiling Source Code
21
Programs
• Computer programs, known as software, are instructions to the
computer.
• You tell a computer what to do through programs.
• Without programs, a computer is an empty machine.
• Computers do not understand human languages, so you need to use
computer languages to communicate with them.
• Programs are written using programming languages.

1.3 22
Programming Languages
Machine Language Assembly Language High-Level Language
• Machine language is a set of primitive instructions built into every
computer.
• The instructions are in the form of binary code, so you have to enter
binary codes for various instructions.
• Program with native machine language is a tedious process.
• Moreover the programs are highly difficult to read and modify.
• For example, to add two numbers, you might write an instruction in
binary like this:
1101101010011010

1.3 23
Programming Languages
Machine Language Assembly Language High-Level Language
• Assembly languages were developed to make programming easy.
• Since the computer cannot understand assembly language,
however, a program called assembler is used to convert assembly
language programs into machine code.
• Writing code in assembly language is easier than in machine
language. However, it is still tedious to write code in assembly
language.
• For example, to add two numbers, you might write an instruction in
assembly code like this:
ADD 2, 3, result

1.3 24
Programming Languages
Machine Language Assembly Language High-Level Language
• The high-level languages are English-like and easy to learn and
program.
• Since the computer cannot understand high-level languages,
however, a program called interpreter or compiler is used to convert
high-level language programs into machine code.
• For example, the following is a high-level language statement
(instruction) that computes the area of a circle with radius 5:
area = 5 * 5 * 3.1415

1.3 25
Popular High-Level Languages

1.3 26
Interpreting/Compiling Source Code
• The instructions in a high-level programming language are
called statements.
• A program written in a high-level language is called a source
program or source code.
• Because a computer cannot understand a source program, a
source program must be translated into machine code for
execution.
• The translation can be done using another programming tool
called an interpreter or a compiler.

1.3 27
Interpreting Source Code
• An interpreter reads one statement from the source code,
translates it to the machine code or virtual machine code, and
then executes it right away.
• Note that a statement from the source code may be translated
into several machine instructions.

1.3 28
Compiling Source Code
• A compiler translates the entire source code into a machine-
code file, and the machine-code file is then executed.

1.3 29
1.4. Operating Systems

30
Operating Systems
• The operating system (OS) is a
program that manages and
controls a computer’s activities.
• You are probably using Windows
10, Linux, or macOS.
• Windows is currently the most
popular PC operating system.
• Application programs - such as
an Internet browser and a word
processor - cannot run without
an operating system.

1.4 31
1.5. The History of Python
§ What is Python?
§ Python’s History
§ Python 2 vs Python 3

32
What is Python?
General Purpose Interpreted Object-Oriented
• Python is a general-purpose programming language.
• That means you can use Python to write code for any
programming tasks.
• Python are now used in Google search engine, in mission critical
projects in NASA, in processing financial transactions at New York
Stock Exchange.

1.5 33
What is Python?
General Purpose Interpreted Object-Oriented
• Python is interpreted.
• Which means that python code is translated and executed one
statement at a time by an interpreter.
• In a compiled language, the entire source code is compiled and
then executed altogether.

1.5 34
What is Python?
General Purpose Interpreted Object-Oriented
• Python is an object-oriented programming language.
• Data in Python are objects created from classes.
• A class is essentially a type that defines the objects of the same
kind with properties and methods for manipulating objects.
• Object-oriented programming is a powerful tool for developing
reusable software.

1.5 35
Python’s History
• Python is created by Guido van Rossum in Netherlands in 1990.
• Python is open source.
• Open-source software is a type of computer software in which
source code is released under a license in which the copyright
holder grants users the rights to study, change, and distribute the
software to anyone and for any purpose.

1.5 36
Python 2 vs Python 3
• Python 3 is a newer version, but it is not backward compatible with
Python 2.
• That means if you write a program using Python 2, it may not work
on Python 3.
• For example, the following command works on Python 2, but it
doesn't work on Python 3: print "Hello World".
• To get the previous command working on Python 3, you can write it as
the following: print("Hello World").
• We will learn and use Python 3 in this book.

1.5 37
1.6. Getting Started with Python
§ Install Python
§ PyCharm IDE
§ Install PyCharm
§ Modes of Python Interpreter
§ Interactive vs Script Mode

38
Install Python
• Go to www.python.org/downloads and then download and install
the last version of Python 3.x.x for your operating system.
• See Lab 1 for more details.

1.6 39
PyCharm IDE
• An integrated development environment (IDE) is an application that
provides comprehensive facilities to programmers for software
development.
• IDEs are large size programs, and many of them are not free.
• For Python programmers, PyCharm is one of the best IDE for Python.
• Also, it has a free version called “Community Edition”.
• In general, using IDEs are the best way to develop programs
especially mid-large programs.

1.6 40
Install PyCharm
• Go to https://www.jetbrains.com/pycharm/download/ and then
download and install “Community” version.
• See Lab 1 for more details.

1.6 41
Modes of Python Interpreter
Interactive Mode Script Mode
• Interactive mode provides us with a quick way of running blocks
or a single line of Python code.
• The code executes via the Python Shell (also known as Python
Interactive Shell), which comes with Python installation.

Python Shell on CMD

1.6 42
Modes of Python Interpreter
Interactive Mode Script Mode
• The >>> indicates that the Python shell is ready to execute and
send your commands to the Python interpreter.
• The result is immediately displayed on the Python shell as soon as
the Python interpreter interprets the command.

Python Shell on PyCharm IDE

1.6 43
Modes of Python Interpreter
Interactive Mode Script Mode
• This is the normal mode where a python code is written in a text
file with a ‘.py’ extension, and Python interpreter executes the
file.
• The result of the code will be displayed after the Python
interpreter runs the file.

PyCharm IDE Notepad

1.6 44
Interactive vs Script Mode
The key differences between programming in interactive mode and
programming in script mode:
1. In script mode, a file must be created and saved before executing
the code to get results. In interactive mode, the result is
returned immediately after pressing the <enter> key from the
keyboard.
2. In script mode, you are provided with a direct way of editing your
code. This is not possible in interactive mode.

1.6 45
A Simple Python Program
§ Program 1: Welcome with Two Messages
§ Creating and Editing Using PyCharm
§ Tracing The Program Execution
§ Code Tracing

46
Welcome with Two Messages
Program 1
Write a program that displays Welcome to Python and Programming is
fun. The output should be as the following:

Welcome to Python
Python is fun

Ø The Solution:
LISTING 1.1 Welcome.py

1 # Display two messages Run

2 print("Welcome to Python")
3 print("Python is fun")

A Simple Python Program Program 1 47


Step
1 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Open PyCharm.

A Simple Python Program Program 1 48


Step
2 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Click on “New Project”.

A Simple Python Program Program 1 49


Step
3 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Then, change the default name of the project “pythonProject”. For
example, name it as “My First Project”, and then click on “Create”.

A Simple Python Program Program 1 50


Step
4 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Then, the new project is created and opened. After that, you have to
create a new Python file inside the project to write the code on it.

A Simple Python Program Program 1 51


Step
5 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Select the project name on the left menu, right click on it and select
“New” → “Python File”.

A Simple Python Program Program 1 52


Step
6 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Then, name the new file “Welcome”.

A Simple Python Program Program 1 53


Step
7 of 7
Welcome with Two Messages
Creating and Editing Using PyCharm
• Now, the new file is created and opened. Write the code in it:

A Simple Python Program Program 1 54


Step
1 of 2
Welcome with Two Messages
Running The Code Using PyCharm
• To run the file, right click on any area of the editor and click on (Run
‘Welcome’), which is the name of the file.

A Simple Python Program Program 1 55


Step
2 of 2
Welcome with Two Messages
Running The Code Using PyCharm
• After that, PyCharm is going to run the file using the Python
interpreter, and then display the output of the file for you.

A Simple Python Program Program 1 56


Welcome with Two Messages
Tracing The Program Execution
LISTING 1.1 Welcome.py

1 # Display two messages


2 print("Welcome to Python") It is a comment, so do
nothing.
3 print("Python is fun")

A Simple Python Program 1 of 3 Program 1 57


Welcome with Two Messages
Tracing The Program Execution
LISTING 1.1 Welcome.py

1 # Display two messages


2 print("Welcome to Python") Execute a statement
3 print("Python is fun")

The output of the


Welcome to Python statement

A Simple Python Program 2 of 3 Program 1 58


Welcome with Two Messages
Tracing The Program Execution
LISTING 1.1 Welcome.py

1 # Display two messages


2 print("Welcome to Python") Execute a statement
3 print("Python is fun")

Welcome to Python The output of the


statement
Python is fun

A Simple Python Program 3 of 3 Program 1 59


Code Tracing
• Code tracing is when the programmer interprets the
results of each line of code and keeps track of the effect of
each statement.

A Simple Python Program 60


Simple Examples
§ Program 2: Welcome With Three Messages
§ Program 3: Compute an Expression
§ Check Point #1 - #2

61
Welcome With Three Messages
Program 2
Write a program that displays Welcome to Python , Programming is
fun , and Problem Driven . The output should be as the following:

Welcome to Python
Python is fun
Problem Driven

Ø The Solution:
LISTING 1.2 WelcomeWithThreeMessages.py

1 # Display three messages Run

2 print("Welcome to Python")
3 print("Python is fun")
4 print("Problem Driven")
Simple Examples Program 2 62
Compute an Expression
Program 3
!".$ % & × (
Write a program that evaluates and print its result.
)$ * (.$
Ø The Solution:
LISTING 1.3 ComputeExpression.py

1 # Compute expression Run

2 print((10.5 + 2 * 3) / (45 - 3.5))

Ø The output:
0.39759036144578314

Simple Examples Program 3 63


Check Point
#1
Identify and fix the errors in the following code:
1 # Display two messages
2 print("Welcome to Python")
3 print("Python is fun").

Ø Solution:
The errors are the incorrect indentation in line 2 and the
punctuation (.) in line 3.
1 # Display two messages
2 print("Welcome to Python")
3 print("Python is fun")

Simple Examples 64
Check Point
#2
Show the output of the following code:
1 print("3.5 * 4 / 2 - 2.5 is")
2 print(3.5 * 4 / 2 - 2.5)

Ø Solution:
3.5 * 4 / 2 - 2.5 is
4.5

Simple Examples 65
Anatomy of a Python Program
§ Statement
§ Indentation
§ Comment
§ Special Symbols

66
Statement
• A statement represents an action or a sequence of actions.
• The statement print("Welcome to Python") in the program
in Listing 1.1 is a statement to display the greeting
"Welcome to Python“.

LISTING 1.1 Welcome.py

1 # Display two messages It is a statement


(action)
2 print("Welcome to Python")
3 print("Python is fun") It is a statement
(action)

Anatomy of a Python Program 67


Indentation
• The indentation matters in Block 1
Python. Block 2

• The following figure is a Block 3

block structure visualizing Block 2, Continuation

indentation. Block 1, Continuation

• Note that the statements are entered from the first column in
the new line. It would cause an error if the program is typed as
follows:
1 # Display two messages It would cause an error
2 print("Welcome to Python") because this statement
has a wrong
3 print("Python is fun") indentation.

Anatomy of a Python Program 68


Caution
• Don’t put any punctuation at the end of a statement.
• For example, the Python interpreter will report errors for the
following code:

1 # Display two messages


2 print("Welcome to Python").
3 print("Python is fun").

Anatomy of a Python Program 69


Note
• Python programs are case sensitive.
• It would be wrong, for example, to replace print in the program
with Print.

1 # Display two messages


2 print("Welcome to Python")
3 Print("Python is fun")

Anatomy of a Python Program 70


Comment
• A comment is a programmer-readable explanation or
annotation in the source code of a computer program.
• In Listing 1.1, line 1 is a comment that documents what the
program is and how it is constructed.

LISTING 1.1 Welcome.py

1 # Display two messages It is a comment, so the


2 print("Welcome to Python") Python interpreter will
3 print("Python is fun“) ignore it when
executing the
program.

Anatomy of a Python Program 71


Comment
• Comments help programmers communicate and understand a
program.
• They are not programming statements and thus are ignored by
the interpreter.
• In Python, comments are preceded by a pound sign (#) on a
line, called a line comment, or enclosed between three
consecutive single quotation marks (''') on one or several lines,
called a paragraph comment.

Anatomy of a Python Program 72


Comment
• When the Python interpreter sees #, it ignores all text after #
on the same line.
• When it sees ''', it scans for the next ''' and ignores any text
between the triple quotation marks.
• Here are examples of comments:
1 # This program displays Welcome to Python (a line comment)
2 ''' This program displays Welcome to Python and
3 Python is fun (a paragraph comment)
4 '''
5 print("Welcome to Python")
6 print("Python is fun")

Anatomy of a Python Program 73


Special Symbols

Anatomy of a Python Program 74


1.7. Programming Style and
Documentation
§ Programming Style
§ Documentation
§ Appropriate Comments and Comment Styles
§ Proper Indentation and Spacing

75
Programming Style
• Programming style deals with what programs look like.
• When you create programs with a professional programming style,
they not only execute properly but are easy for people to read and
understand.
• This is very important if other programmers will access or modify
your programs.

1.7 76
Documentation
• Documentation is the body of explanatory remarks and comments
pertaining to a program.
• These remarks and comments explain various parts of the program
and help others understand its structure and function.
• As you saw earlier in the chapter, remarks and comments are
embedded within the program itself; Python’s interpreter simply
ignores them when the program is executed.
• Good programming style and proper documentation make a
program easy to read and prevents errors.
• Programming style and documentation are as important as coding.
In the following slides, there are a few guidelines.

1.7 77
Appropriate Comments and Comment
Styles
• Include a summary comment at the beginning of the program to
explain what the program does, its key features, and any unique
techniques it uses.
• In a long program, you should also include comments that introduce
each major step and explain anything that is difficult to read.
• It is important to make comments concise so that they do not crowd
the program or make it difficult to read.
• In homework and exams, Include your name, class section,
instructor, date, and a brief description at the beginning of the
program.

1.7 78
Proper Indentation and Spacing
• Indentation
◦ Indent four spaces.

• Spacing
◦ A consistent spacing style makes programs clear and easy to read,
debug, and maintain.
◦ Use blank line to separate segments of the code.

print(20+50) print(20 + 50)


print(20- 10) print(20 - 10)
print(60*5+30) print(60 * 5 + 30)
print("A","B") print("A" ,"B")

1.7 79
1.8. Programming Errors
§ Types of Programming Errors
§ Syntax Errors
§ Runtime Errors
§ Logic Errors
§ Notes
§ Check Point #3

80
Types of Programming Errors
• Programming errors can be categorized into three types:
◦ Syntax Errors
§ Error in code construction.
◦ Runtime Errors
§ Causes the program to abort.
◦ Logic Errors
§ Produces incorrect result.

1.8 81
Syntax Errors
• Syntax errors result from errors in code construction, such as
mistyping a statement, incorrect indentation, omitting some
necessary punctuation, or using an opening parenthesis without a
corresponding closing parenthesis.
• Python has its own syntax, and you need to write code that obeys
the syntax rules. If your program violates the rules Python will report
syntax errors.

1.8 82
Runtime Errors
• Runtime errors are errors that cause a program to terminate
abnormally.
• They occur while a program is running if the Python interpreter
detects an operation that is impossible to carry out.
• Input mistakes typically cause runtime errors.

1.8 83
Runtime Errors
• An input error occurs when the user enters a value that the program
cannot handle.
• For instance, if the program expects to read in a number, but instead
the user enters a string of text, this causes data-type errors to occur
in the program.

1.8 84
Logic Errors
• Logic errors occur when a program does not perform the way it was
intended to.
• Logic errors produce unintended, incorrect or undesired output or
other behavior, although it may not immediately be recognized as
such.
• In fact, they do not cause the program to terminate abnormally.

1.8 85
Logic Errors
Example
The following is a program that converts a temperature (35 degrees)
$
from Fahrenheit to Celsius. T(°C) = ×(T(°F) − 32)
+
LISTING 1.4 ShowLogicErrors.py

1 # Convert Fahrenheit to Celsius Run


2 print("Fahrenheit 35 is Celsius degree ")
3 print(5 / 9 * 35 - 32)

The produced result (-12.55)


Fahrenheit 35 is Celsius degree
is not correct. The correct
-12.555555555555554 result is (1.66).

• Replace the expression 5 / 9 * 35 – 32 with 5 / 9 * (35 – 32) to get the correct


result.
• That is, you need to add parentheses around (35 – 32) so Python will calculate
that expression first before doing the division.

1.8 86
Notes
• In Python, syntax errors are actually treated like runtime errors
because they are detected by the interpreter when the program is
executed.
• In general, syntax and runtime errors are easy to find and easy to
correct, because Python gives indications as to where the errors
came from and why they are wrong.
• Finding logic errors, on the other hand, can be very challenging.

1.8 87
Check Point
#3
If you forget to put a closing quotation mark on a string, what kind of
error will be raised?
Ø Answer: Syntax Error

If your program needs to read data from a file, but the file does not
exist, an error would occur when running this program. What kind of
error is this?
Ø Answer: Runtime Error
Suppose you write a program for computing the perimeter of a
rectangle and you mistakenly write your program so that it computes
the area of a rectangle. What kind of error is this?
Ø Answer: Logic Error

1.8 88
End
§ Test Questions
§ Programming Exercises

89
Test Questions
• Do the test questions for this chapter online at
https://liveexample-ppe.pearsoncmg.com/selftest/selftestpy?chapter=1

90
Programming Exercises
• Page 27 – 29:
◦ 1.1 – 1.11
• Lab #1
• Lab #2

91

You might also like