Week 1
Week 1
CS115
INTRODUCTION TO PROGRAMMING IN
PYTHON
WEEK 1
1
About CS 115 - Expectations
1. Course Management System (Moodle)
1. Weekly Course Outline
2. Course Information
3. Lecture Notes and Code Examples
4. Lecture Videos
2. Course Information
1. Assessments and their weights
2
Lab sessions
You will have 10 lab assignments which you are required to
solve individually.
There is 1 lab session per week, a TA and tutors will be
present for the entire lab session.
You should attend the lab hours to complete your labs.
The teaching assistants will check and grade the assignment.
They may ask questions about your code.
3
Programs and Tools
It is assumed for this online course you have access to:
◦ A computer with Python 3.x, Numpy, Matplotlib and the development
environment of your choice installed and working.
◦ A web cam (either laptop or removable)
◦ A mobile device with a camera and video/audio capabilities.
◦ An active internet connection.
4
Python Language and
Modules
In class the exercises and examples will use Python 3.8.
We will cover additional packages not included with standard Python,
which are:
◦ Numpy: package for scientific computing in Python.
◦ Matplotlib: comprehensive library for creating static, animated, and
interactive visualizations in Python.
5
Software
For the course, we will be using the Anaconda Python 3.8 distribution.
Anaconda contains:
Python: a programming language in which we write computer programs.
Python packages: For scientific computing and computational modelling, we
need additional libraries (packages) that are not part of the Python standard
library. These allow us to create plots, operate on matrices, and use specialized
numerical methods. Eg. numpy, pyplot, etc.
Spyder: The name SPyDER derives from "Scientific Python Development
EnviRonment" (SPYDER). It is an integrated development environment (IDE) for
the Python language with advanced editing, interactive testing, debugging
features.
Jupyter Notebook: an altenative tool to develop open-source software, open-
standards, and services for interactive computing across many programming
languages.
6
How to Download Anaconda
Anaconda 2019.10 with Python 3.7 is available in all BCC labs.
7
Outline
Problem Solving
8
Problem Solving
The purpose of writing a program is to solve a problem
Solving a problem consists of multiple activities:
◦ Understand the problem
◦ Design a solution
◦ Consider alternatives and refine the solution
◦ Implement the solution
◦ Test the solution
These activities are not purely linear – they overlap and interact
9
Algorithms
Steps used to solve a problem.
The steps in an algorithm should be precisely defined and the
ordering of the steps is very important.
An algorithm defines:
o sequence of simple steps.
o flow of control process that specifies when each step is executed.
o a means of determining when to stop.
10
Flowcharts and Pseudocode
Example: A program that asks the user their name then says ‘Hello [Name]’:
1. Input name
2. Output ‘hello [name]’
11
Outline
Problem Solving
12
Computer Programs
The mechanics of developing a program include several
activities:
o writing the program in a specific programming language (such as Python)
o translating the program into a form that the computer can execute
o investigating and fixing various types of errors that can occur
Software tools can be used to help with all parts of this process.
Spyder/Jupyter provide tools for all steps in program development.
13
Programming Languages
There are hundreds of programming languages, no best or
worst language.
Some languages are better or worse for different applications.
Each programming language has:
o Set of primitive constructs (‘words’ that make up language)
o A syntax (describes the order of the words)
o Semantics (defines the meaning of the sentences)
14
Programming Languages
Python includes the following:
o Primitive constructs: numbers, strings, operators (+,-,…)
o Syntax: order in which the constructs must be added to be well
formed, ‘syntactically correct’
o Semantics: the meaning of the syntactically correct statements.
15
Syntax and Semantics
The syntax rules of a language define how we can put together
symbols, reserved words, and identifiers to make a valid program
The semantics of a program statement define what that statement
means (its purpose or role in a program)
A program that is syntactically correct is not necessarily logically
(semantically) correct
A program will always do what we tell it to do, not what we meant
to tell it to do
16
Errors in Programs
Syntactic errors
◦ common and easily caught
Semantic errors
◦ can cause unpredictable behavior
◦ some languages like Java check for these before running program, some
such as Python do less checking.
◦ code has different meaning than what programmer intended
◦ program crashes, stops running
◦ program runs forever
◦ program gives an answer but different than expected
17
Outline
Problem Solving
18
Introduction to Python
General purpose programming language.
Can be used effectively to build almost any type of program.
Advantages:
o Relatively simple language.
o Easy to learn.
o Large number of freely available libraries.
o Easy to download and install.
o Runs under all operating systems.
Disadvantages:
o Because of minimal static semantic checking, not optimal for:
programs that have high reliability constraints (air traffic control systems, medical device).
large team projects, or extended length projects. ( “too many cooks spoil the soup”)
19
Introduction to Python
Python is an interpreted language versus a compiled language.
In interpreted languages, the sequence of instructions (source code) is
executed directly whereas in compiled languages the source code is
first converted into a sequence of machine code.
Both have advantages and disadvantages.
20
Python Programs
A program (script) is a sequence of definitions and commands
o definitions evaluated
o commands executed by Python interpreter
21
Shell vs. Script
We can print ‘Hello World’ in two different ways, using the shell
(command line) or using a script(python file).
The print() command prints text to the screen, so the command
print(‘Hello World’) will print the given text to the console.
22
Built-In Functions
The Python interpreter has a number of functions and types built into it that are always
available.
24
Scalar Objects
int – represent integers, ex. 5
float – represent real numbers, ex. 3.27
bool – represent Boolean values True and False
NoneType – special and has one value, None
Can use type() to see the type of an object:
◦ type("hello world")
str
◦ type(5)
int
◦ type(3.5)
float
◦ type( True )
bool
25
Type Conversion
Sometimes we need to convert data from one type to another. For
example, we may want to find the integer value of 3.2.
We can use built in functions to convert object of one type to
another (type casting)
◦ float(3) converts integer 3 to float 3.0
◦ int(3.9) truncates float 3.9 to integer 3
◦ bool(5) converts non zero values to boolean True
◦ bool(0) converts zero value to boolean False
26
Variables
A variable is a name for a location in memory that holds an
object, and allows us to associate labels with objects.
A variable has three things:
◦ a label : that is how we refer to it
27
Naming Variables
Programming have rules for naming variables.
Variables names must start with a letter or an underscore, such as:
_vname, vname_
The remainder of your variable name may consist of letters, numbers
and underscores. Eg: password_1, n00b
Names are case sensitive. case_sensitive, CASE_SENSITIVE, and
Case_Sensitive are each a different variable.
Variable should be given meaningful names in our programs.
For example, variables with names a and p are not meaningful, but
names such as area and perimeter are immediately understood.
28
Reserved Words
Reserved words are the keywords that have built-in meanings and
cannot be used as variable names.
Each version of Python may have a different keyword list.
To see the list of reserved words in Python you can type the commands:
import keyword
keyword.kwlist
Example list:
29
Comments
Comments explain the purpose and process.
Docstrings provide documentation for functions, modules and classes which we will
discuss later.
30
Binding Variables and Values
(Assignment)
An assignment statement changes the value of a variable
The assignment operator is the = sign.
Syntax of assignment statement:
value
variableName = variableName
expression
Example: total = 55
31
CHANGING BINDINGS
In python you can re-bind variable names using new assignment
statements.
The previous value may still be stored in memory but the
reference to the value no longer exists.
Value for area does not change until you tell the computer to do
the calculation again
Example:
pi = 3.14
radius = 2.2
area = pi*(radius**2)
radius = radius+1
32
Multiple Assignment
All of the expressions on the right-hand side of an assignment are
evaluated before any bindings are changed.
Example:
x, y = 2, 3
x, y = y, x
print(‘x=‘, x)
print(‘y=‘, y)
will print:
x = 3
y = 2
33
Expressions
Combine objects and operators to form expressions.
34
OPERATORS ON ints and floats
i+j -> the sum
i-j -> the difference
i*j -> the product
i/j -> floating point division
i//j -> integer division (value is truncated)
i%j -> the remainder when i is divided by j
i**j -> i to the power of j
35
Python Arithmetic Operator
Precedence
The order of evaluation can be changed by using parentheses to group
sub-expressions.
For example: (x + y) * 2, first adds x and y then multiplies the product by 2.
The table below shows the arithmetic operator precedence.
36
Quick Check
What are the results of the following expressions?
12 / 5
12 // 5
10 / 4.0
10 // 4.0
4 / 10
4 // 10
12 % 3
10 % 3
3 % 10
37
Quick Check
What are the results of the following expressions?
12 / 5 = 2.4
12 // 5 = 2
10 / 4.0 = 2.5
10 // 4.0 = 2.0
4 / 10 = 0.4
4 // 10 = 0
12 % 3 = 0
10 % 3 = 1
3 % 10 = 3
38
Assignment Operators
• See: week1_exp.py
39
Quick Check
In what order are the operators evaluated in
the following expressions?
a + b + c + d + e a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
40
Quick Check
In what order are the operators evaluated in the
following expressions?
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1
41
Writing Good Code
Coding conventions are used to improve the readability of code
and make it consistent across the wide spectrum of Python
code.
They provide guidelines about the code layout and style.
In this course, we will follow the PEP8 coding conventions.
Important conventions:
◦ Indentations should be 4 spaces.
◦ Spaces are the preferred indentation method.
◦ Use blank lines to indicate logical sections.
◦ Although there may be exceptions, generally use a single space before
and after operators.
See the PEP8 documentation for the complete list of rules.
42
Printing to Console
To show output from code to a user, use the built-in print
command.
In [1]: 3 + 2
“Out” tells us it is an
Out[1]: 5 interaction in the shell only
In [2]: print(3 + 2)
No “Out” means that it is
5 shown to the user when the
program runs.
43
Formatting print() values
To format numeric or string values, use the format() built-in
function.
Usage:
‘format_string’.format(values)
44
Formatting print() values
salary = 7512.32165
print( ‘Your salary is’, salary )
Output:
Your salary is 7512.32165
vs
salary = 7512.32165
print(‘Your salary is {0:.2f}’.format(salary ))
Output:
Your salary is 7512.32
45
Format Field { variable_index:format_type }
46
Formatting Example
salary = 7510.2685
age = 32
name = 'Jane'
Output:
Name: Jane Age: 00032 Salary: 7510.27
Output:
Salary and age of Jane are 7510.269 32
47
Exercises
1. Write a program that converts 400oK to Celsius, and displays the result
in a proper format.
2. Write a program that finds the area and perimeter of a circle with the
radius 1.5 cm and display the result. You can assume pi is the constant
value 3.14.
3. Write a program that finds the sum of the first and last digit of some 4
digit number.
4. Write a program to calculate the number of hours and minutes needed
for a car to travel 500 kilometers at the velocity 110 km/h.
See: week1_example.py or week1_example.ipynb
48
Terms of Use
This presentation was adapted from lecture materials provided in MIT
Introduction to Computer Science and Programming in Python.
Licenced under terms of Creative Commons License.