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

Unit 1 - Lecture Notes

Uploaded by

Ashterite
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 1 - Lecture Notes

Uploaded by

Ashterite
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT

1 University of the Philippines Visayas


Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

COPYRIGHT NOTICE

This material has been reproduced and communicated to you by or on behalf of University of the Philippines
pursuant to PART IV: The Law on Copyright of Republic Act (RA) 8293 or the “Intellectual Property Code of
the Philippines”.

The University does not authorize you to reproduce or communicate this material. The Material may contain
works that are subject to copyright protection under RA 8293. Any reproduction and/or communication of the
material by you may be subject to copyright infringement and the copyright owners have the right to take
legal action against such infringement.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

UNIT

1
Learning Outcomes:
The way of the Program, Variables, expressions,
and statements

1. Describe why there is a need of the course


2. Differentiate the different parts of a program
3. Implement debugging a program
4. Describe the basic concepts in Python Programming Language
5. Determine the correct usage of data types
6. Differentiate the different types of literals and different ways to declare a
constant
7. Implement the basic ways to accept user input and display an output
8. Differentiate the different types of operators and their application

Learning Activities: Graded Assignment


Duration: 2 hours

Think like a Computer Scientist

Think like:
 Mathematicians
- Computer Scientist use formal languages to denote
ideas (specifically computations)
 Engineers
- they design things, assembling components into
systems and evaluating tradeoffs among alternatives Source:https://rposervices.com/wp-content/uploads/2019/02/AI-RPO.j
pg
 Scientists
- they observe the behavior of complex systems, form hypotheses and test predictions.

The most important skill of Computer Scientist is PROBLEM SOLVING!!!

Problem Solving is the ability of to formulate problems, think creatively about solutions, and express a
solution clearly and accurately. When you do programming, the process of learning to program is an
excellent opportunity to practice problem-solving skills.

Therefore, Computer Science is NOT the study of computers. According to a famous Computer Scientist
Edsger Disjktra, “Computers are to Computer Science what telescope are to astronomy”.

Computer Scientists use numerous techniques if investigation to answer the fundamental question of
computer science - “What can be computed?”. The three main techniques are design, analysis, and
experimentation.

A. One way to demonstrate that a particular problem can be solved is to actually design a solution. You
will develop a step-by-step process for achieving the desired result. And in Computer Science this is called
an algorithm.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

B. Analysis is the process of examining algorithms and problems mathematically. Computer scientist
have shown that some seemingly simple problems are not solvable by any algorithm.Other problems are

intractable. The algorithms that solve these problems take too long or require too much memory to be of
practical value. Analysis of algorithm is an important part of computer science.
C. Since some problems are too complex or ill-defined to lend themselves to analysis, in such cases,
compute scientists rely on experimentation; they actually implement systems and then study the resulting
behaviour. Even when theoretical analysis is done, experimentation is needed in order to verify and refine
the analysis.

Apart from designing, analyzing, and evaluating algorithms, compute scientists are involved in the
activities which fall under the general umbrella of computing. Some examples include mobile computing,
networking, human-computer interaction, artificial intelligence, computational science (using powerful
computes to model scientific processes), databases and data mining, software engineering, web and
multimedia design, management information systems, and computer security. Wherever computing is done,
the skills and knowledge of computer science is being applied

Python Programming Language

Python is an example of a high-level programming language. It is much easier to


program in a high level language. High-level language are portable - they can run on
different kinds of computers with few or no modifications.

There are two (2) programs that are used to process high-level language into
low-level languages: interpreter and compilers.

Interpreter reads a high-level program and executes it. Meaning that it does what
https://www.seaq.co/wp-content/uploads/2019/
07/Python.jpg
the program says, It processes the program a little at a time ,alternately reading
lines and performing computations.

Compiler reads the program and translates it completely before the program starts running.

The high-level called the source code, and the translated program is called the object code or the
executable. Once a program is compiled, you can execute it repeatedly without further translation.

Python is considered as an interpreted language because Python programs are executed by an interpreter.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

What is a program?
A program is a sequence of instructions that specified how to perform a computation. The computation
might be something mathematical, such as solving a system equations or finding the roots of a polynomial,
but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely
enough) compiling a program.

Source:https://i.pinimg.com/originals/ec/81/b4/ec81b4a50b712e3341d
160da848742f6.gifpg

When your write down directions to your house for a friend, you are writing a program. Your friend
“executes” that program by following each instructions in turn.

Every program is written in terms of a few basic operations that its reader already understand. For
example, the set of operations that your friend can understand might include the following: “Turn left at
Darwin Street”, “Go forward three blocks”, and “if you go get to the gas station, turn around - you’ve gone
too far.”

Computers are similar but have a different set of operations.

The details look different in different languages, but a few instructions appear in just about every
language:

Input: get the data from the keyboard, a file, or some other device
Output: display data on the screen or send data to a file or other device
Conventional Execution: check for certain conditions and execute the appropriate sequence of
statements
Repetition: perform some action repeatedly, usually with some variation

Debugging
Programming is error-prone. Programming errors are called bugs and the process of tracking them
down is called debugging.

Source : https://i.pinimg.com/600x315/fd/75/21/fd752102a8fce6454d832f492e51fd23.jpg
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

There are three (3) kinds of errors that can occur in a program: syntax errors, runtime errors, and
semantic errors.

1. Syntax Errors

Syntax is the structure of a program and the rules about the structure. Syntax errors are produced by
Python when it is translating the source code into byte code. They usually indicate that there is something
wrong with the syntax of the program. For example 8) will cause a syntax error because in programming, the
parenthesis should come in a matching pair (). Having an incorrect indention, leaving out a symbol (such as
a colon, command or brackets) and misspelling a keyword can cause a syntax error and yields to a message
SyntaxError: invalid syntax. The example (1+2) is legal in programming and will not cause a syntax error.

In programming, if there is a single syntax error anywhere in the program, an error message will be
displayed and the program will not be able to run. During the first few weeks of programming, you will
probably spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer
errors and find them faster.

Try it on Your Own:

Find all the syntax errors in the code snippet below and explain why they are errors.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Answer:
There are five syntax errors:

Missing def keyword in function


definition
else clause without an if

Missing colon (:) after if


condition

:
The if block is empty because
the print statement is not Spelling mistake (“esle”)
indented correctly

2. Runtime Errors

Runtime errors are errors that does not appear until after the program has started running. These errors
are called exceptions because they usually indicate that something exceptional (and bad) has happened.
Most runtime error messages include information about where the error occurred and what functions were
executing. Example: An infinite recursion eventually causes the runtime error “maximum recursion depth
exceeded”

Runtime errors are rare in the simple programs.

Some examples of runtime errors are:


 Division by zero
 Performing an operation on incompatible types
 Using identifier which has not been defined
 Accessing a list element or dictionary value which doesn’t exist
 Trying to access a file which doesn’t exist

To prevent runtime errors, you must consider all possible values that a variable could contain, especially
when you are processing user input.

Try it on Your Own:

Find the potential sources of runtime errors in this code snippet:


UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Answer:

1. The values entered by the user may not be valid integers or floating point numbers
2. The user may enter zero for the divisor
3. If the math library hasn’t been imported, math.round is undefined

3. Semantic Errors

If there is a semantic error in the program, it will run successfully in the sense that the computer will not
generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will
do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the
program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work
backward by looking at the output of the program and trying to figure out what it is doing.

Example: An expression may not be evaluated in order you expect, yielding an incorrect result.

Try it on Your Own:

Will the expression y = x / 2 * math.pi produce the expected output?

Answer:

No. In programming multiplication and division have the same precedence and are evaluated from
left to right. So this expression computes x / 2 π . A good way to debug expressions is to add
parentheses to make the order of evaluation explicit:

y = x / (2 * math.pi)

Whenever you are not sure of the order of evaluation , use parentheses. Not only will the program be
correct, it will also be more readable for other people who haven't memorized the rules of precedence.

Running Python

If you have not yet installed Python 3 please do so before you proceed with the examples. There are two
versions of Python , Python 2 and Python 3. There are few differences between the two, however, for our
course, we will be using Python 3.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

I would recommend that you open the Python shell in your computer so that you can also try the
examples in the next pages of this module(lecture note). We will be running the interactive mode in the
Python.

Click the Python IDLE


2

Type “Python” in the Search


box of your Computer 1

The Python shell should appear like this below (in the Python Shell below, the Python version is Python 2 as
it begins with 2, but you should have Python 3 in your computer) :
3

The most important part is the >>> which is a Python prompt indicating that the Python interpreter is
waiting for you to give it a command.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Alternative option to run Python Interpreter:

Click the Command Prompt


icon 2

Type “cmd”or “command 1


Prompt” in the Search box of
your Computer

Type “python” and


press ENTER
3

4
Just like your Python Shell, the Python version will also displayed as well as
the Python prompt

NOW WE ARE ALL SET


WITH OUR PYTHON
INTERPRETER!!! WE ARE
NOW READY TO TRY OUR
EXAMPLES AND RUN OUR
OWN PROGRAM!!!!
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Type print (‘Hello, World!’) in the prompt and press ENTER. It should look like this:

This is an example of a print statement. It displays a result on the screen. In this case, the result is
the words Hello, World!

The quotation marks in the program mark the beginning and end of the text to be displayed; they
don’t appear in the result.

The parentheses indicate that print is a function. We’ll discuss about functions in the next topics.

Other examples:

Try it on Your Own:

1. With the prompt open, print the sum of 2 and 3.

Answer:

2. Now, try to print 2 + 3 = 5.

Answer:
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Variables, expressions, and statements

Source: https://s-media-cache-ak0.pinimg.com/736x/89/f3/7b/89f37b3be33c34681686d8515aa91c0f--programming-humor-computer-programming.jpg

Values and Types:

Value is one of the basic units of data, like a number or a string, that a program manipulates.
Example of values are 2, 42.0, and ‘Hello World!’. These values belongs to different types: 2 is an
integer (int), 42.0 is a floating-point number (float), and ‘Hello World!’ is a string (str) so-called
because the letters it contains are strung together.

Type is a category of values, examples int, float, str. If you are not sure what type a value has, the
interpreter can tell you:

1,000,000 is not legal in Python.

If you try to print 1,000,000 - it will output 1 0 0


The reason is that Python interprets as comma separated sequence sequence of integers. That’s why
it prints with spaces between.

Try to find the types of other values. Go ahead and try them in the interpreter. It is better to
experiment so that you will know more beyond the examples we have.
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

One of the most powerful features of a programming language is the ability to manipulate variables.
A variable is a name that refers to a value.

A. Assignment statements

An assignment statement creates a new variable and gives it a value.

Example:

In the example above, there are three assignments. The first assigns a string to anew variable
named message; the second gives the integer 17 to n; and the third assigns the (approximate)
value of π to pi.

If you type an integer with a leading zero, you will get a confusing error.

Example:

In other times, it might work but you will get a semantic error. This is because programming
languages use token. Token is one of the basic elements of the syntactic structure of a program, a
word in a natural language, programming languages are using formal languages - any one of the
languages that people have designed for specific purposes.

You can also reassign to a variable, and doing so doe not change any other variable.

Example:

In the example above, this is what happened:

1. The value 20 was assigned to the variable difference, thus the initial value of difference is
20
2. Difference then is multiplied to 2, their product is assigned to the variable difference
3. If you print the variable double to know its value, its value is 40 as the product of the
difference value (20) and 2
4. The variable difference is being used again to store another value which is now 5.
5. Now, if you print the variable double to know it value, its value is still 40. Why? Because
although we assigned a different value (5) to the variable difference, we didn’t use that
new value to compute for the variable double, then, the initial value of double still remains
which is 40.

If you want to use the new value of difference for computation and assign it to double, it will
look like this:
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Notice that the value of variable double changed to 10 because we reused the value of
difference. And because difference was assigned a new value of 5, then the new value of double is
the product of 2 and the new value of difference(2). The resulting output then is 10.

Another example:

1. Initially, 3 was assigned as a value to the variable number


2. If you type number in your shell, it will output you its value which is 3
3. The variable number was assigned a value of the product of number which is 3 and 2
4. Therefore, the new value of number now is 6. Because that is the product of number(3) and
2.
5. Again, the variable number is being used where it was assigned the product of number and
number.
6. So, the new value of number now is 36 because the last value of the variable number is 6,
and multiply it by the variable number (which is the same variable that has the value of
(6)).

Augmented Assignment

An augmented assignment combines an assignment statement with an operator to make


the statement more concise.

Examples:
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Augmented Assignment Operators

B. Variable names

Programmers generally choose names for their variables that are meaningful - they document
what the variable is used for.

General rule for variable names:


 Variable names can be as long as you like
 They can contain both letters and numbers
 They should not begin with a number
 It is legal to use uppercase letters, but it is conventional to use only lower case for
variable names
 The underscore character, _, can appear in a name; often used in names with multiple
words such as your_name or airspeed_of_unladen_swallow
 Do not use reserved keywords as variable names

Examples:

1. 77tombraider = ‘big parade’


SyntaxError: invalid syntax

77tombraider is an illegal variable name as it starts with a number

2. more@ = 10000000000
SyntaxError: invalid syntax

more@ is an illegal variable name as it has special character @; the only special character
accepted is undescore _

3. class = ‘Welcome to CMSC 11’

class is an illegal variable name because it is Python’s reserved keyword


UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

IMPORTANT: Python 3 keywords

You don’t have to memorize the list above. In most development environments (such as Sublime or
Notepad++), keywords are displayed in a different color, if you try to use one as a variable name, you’ll
know.

C. Expressions and statements

An expression is a combination of values, variables, and operators. A value all by itself is


considered as an expression, and so is a variable.

Examples of LEGAL expressions: 17 x x + 17

A statement is a unit of code that the Python interpreter can execute. A script contains a
sequence of statements. If there is more than one statement, the results appear one at a time as
the statements executes.

Example:

The print and assignment are examples of statements.

D. Operators and Operands

Operators are special symbols that represent computations.

Operator Example Output


15 - 3 12
17.0 - 10.0 7.0
Subtraction ( -)
17.0 - 10 7.0
Float and int produces a float
17 - 10.0 7.0
Addition (+) 4 + 13 17
Multiplication (*) 4*7 28
Division (/) 5/2 2.5
53 // 24 2 Uses floor division, which
17 // 10 1 means it rounds down to
the nearest integer
-17//10 -2
3.3 //1 3.0
Integer Division (//) Result is rounded down
3 // 1.0 3.0
to the nearest whole
3 // 1.1 2.0 number, although the
3.5 // 1.1 3.0 types is a floating
3.5 //1.3 2.0
Exponent (**) 3 ** 6 729
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or
-5 -5
Negation (-)
--5 5
(unary operator)
--- 5 -5
Sign of the result matches
Modulo (%) -17 % 10 3 the sign of the divisor
(Remainder) 17 % -10 -3 (second operand)

E. Order of Operations: Rules of Precedence

Order of Operations from highest to Lowest


Operation Example(s) Output
2 * (3-1) 4
Parentheses
( 1+1 ) ** (5-2) 8
2 ** 1 + 1 3
Exponentiation 3 * 1 ** 3 3
2 ** 3 9
Negation
Multiplication,
Division, Integer
Division, A. 2 * 3 - 1 A. 5
Modulo(remainder) B. 6 + 4 // 2 B. 8
Addition and
Subtraction

Operators with the same precedence are evaluated from left to right (except exponentiation).
Python follows the mathematical convention of PEMDAS. For example, in the expression degrees
/2 * pi, the division happens first and the result is multiplied by pi.

F. String Operations

You CANNOT perform mathematical operations on strings even if the string looks like
numbers. Note that ‘2’ is not equal to 2. The first value is a string 2, and the second value is an
integer 2.

Examples of ILLEGAL operations:

‘2’-’1’ ‘eggs’/’easy’ ‘third’*’a charm’

Addition(+) and Multiplication(*) operators work with strings which performs concatenation
and repetition respectively. You can use comma(,) to concatenate int(integer) and str (string)
UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

Examples:

the multiplication(*) operator was used to


reproduce three (3) copies of the string
first is a variable that stores the string value ‘computer’
“Computer”
second is a variable that stores the string
value “Science”

The addition(+) operator was used to


concatenate the two string variables having
an output of ComputerScience

G. Comments

Comments are information in a program that is meant for another programmers (or anyone
reading the source code). It has no effect on the execution of the program. It is used for
documenting your source code.

Comments start with the # symbol to comment a single line of your code. A pair of three (3)
single quotes are used to comment a block.

Example:

Notice that the comments are in gray font. This is to inform the programmer that it is
comment and the colored fonts are the ones that will be displayed in the screen after execution.

The output of the code above is:


UNIT
1 University of the Philippines Visayas
Division of Physical Sciences and Mathematics
CMSC 11: Introduction to Computer Science
Prepared by: Christi Florence C. Cala-or

ACTIVITIES:

Refer to Unit 1 Activity Guide.

LABORATORYACTIVITIES:

Refer to Unit 1 Assignment Guide.

References:
Campbell, et al. Practical Programming: An Introduction to Computer Science Using Python 3.6. The
Pragmatic Bookshelf, 2017.
Downey, A. Think Python: How to Think Like a Computer Scientist, 2nd Edition. Green Tea Press, 2015.

University of Cape Town and individual contributors (2013, 2014). Errors and exceptions. Retrieved from
https://python-textbok.readthedocs.io/en/1.0/Errors_and_Exceptions.html#:~:text=is%20set!%22)-,Runtime
%20errors,run%20by%20the%20Python%20interpreter.&text=Some%20examples%20of%20Python%20ru
ntime,an%20operation%20on%20incompatible%20types

You might also like