You are on page 1of 35

CS1010E Programming Methodology 1

CS1010E
Programming Methodology

Lecture 1: Introduction to programming

Dr. Zhou Lifeng (zhoulifeng@nus.edu.sg)


CS1010E Programming Methodology 2

GETTING STARTED WITH


PROGRAMMING
CS1010E Programming Methodology 3

What is a Program?
• (Computer) Program
• A sequence of instructions telling a computer what to
do.

• Execution of a program
• Computer performs the instruction sequence.

• Programming language
• Language for writing instructions to a computer.
CS1010E Programming Methodology 4

Why Python?
• Clear and readable syntax
• Intuitive
• Natural expression
• Powerful
• Popular and Relevant

* We use Python 3.x


CS1010E Programming Methodology 5

Example Python Program


a = 1
b = 2
c = a + b
if c < 0:
print('Yes')
else: Q: What is the output?

print('No')
CS1010E Programming Methodology 6

ELEMENTS OF A PYTHON
PROGRAM
CS1010E Programming Methodology 7

Variables
• A variable is a name you create in your program to
represent something, e.g. a value, a collection of value.
• In IDLE console, we can try the following example:

>>> my_int = 27
>>> my_int
27

>>> a_float = 3.14159


>>> a_float
3.14159
CS1010E Programming Methodology 8

Python Types

int 8 45 1234
float 2.3 3.14159
bool True False
str "cs1010s"
'cs1010s'
None Doesn’t matter if it’s
quote or double quote
CS1010E Programming Methodology 9

type() Function
>>> type(123)
<class 'int'>

>>> type('123')
<class 'str'>

>>> type(None)
<class 'NoneType'>
CS1010E Programming Methodology 10

Type conversion
>>> str(123)
'123'

>>> float('45.2')
45.2

>>> int(23.8)
23

>>> int('cs1010s')
ValueError!
CS1010E Programming Methodology 11

Variable Naming Rules


1. Contain only 'a'-'z', 'A'-'Z', digits, or '_' (and
cannot start with digits)
2. Case sensitive
e.g. aBc != abc
3. Avoid reserved keywords e.g. int

4. Python convention: lower case letters


separated by '_'
e.g. count_change
CS1010E Programming Methodology 12

input() Function
>>> var = input('Please enter an integer: ')
>>> var
'65'
Suppose user enter 65
>>> var = int(var) through keyboard
>>> var
65

• The input() function reads data as a string.


CS1010E Programming Methodology 13

print() Function
>>> var = 65
>>> print(var)
65
>>> print('My variable has value:', var)
My variable has value: 65

• The print() function takes a list of elements in parentheses


separated by commas.
• if the element is a string, prints it as is

• if the element is a variable, prints the value associated with the


variable
CS1010E Programming Methodology 14

Assignment
• An assignment statement stores a value or a
computational result in a variable.
SYNTAX

<variable> = <expression>

= is not equality,
but assignment

• If the variable already has a value, after assignment, old


value will be replaced by the new value.
CS1010E Programming Methodology 15

Example
>>> abc = 18 + 2
>>> my_string = 'This is my string'
>>> x, y = 1, 2
>>> x
1
>>> y
2
>>> y = y + 3
>>> y
5
CS1010E Programming Methodology 16

Arithmetic Operators
+ - * / ** // %

>>> a = 2 * 3 >>> 11 / 3
>>> a 3.6666666666666665
6
>>> 11 // 3
>>> 2 ** 3 3 Known as floor
8 division

>>> 11 % 3
23 Return
2 remainder
CS1010E Programming Methodology 17

Example
>>> 45/15/3 >>> 4 + 3**2
1 13

>>> 19%7%3 >>> (6-3)//2


2 1

>>> 4 + 3*5 >>> 6-3//2


19 5

• Arithmetic operations are usually executed from left to


right, respecting parentheses rule and precedence rule.
CS1010E Programming Methodology 18

Relational Operators Check equality

> >= < <= == !=


>>> 1 <= 10 >>> 2 != 3
True True

>>> 5 > 15 >>> '1' == 1


False False

>>> 5 <= 5 >>> False == False


True True

True and False are known as Boolean values


CS1010E Programming Methodology 19

Logical Operators
or and not
A A
A or B A and B
True False True False

True True True True True False


B B
False True False False False False

A not A
True False
False True
CS1010E Programming Methodology 20

Example
>>> 3>5 and 1<2
False

>>> 3>5 or 1<2


True

>>> a = True
>>> not a
False
CS1010E Programming Methodology 21

Strings
• A string is a sequence of characters enclosed in
single (or double) quotes, e.g. 'abcd'
• String operations:
1. We can index a string, e.g.

>>> s = 'abcd'
>>> s[0]
'a'
>>> s[1]
'b'
CS1010E Programming Methodology 22

Strings
• A string is a sequence of characters enclosed in
single (or double) quotes, e.g. 'abcd'
• String operations:
2. We can concatenate two strings, e.g.

>>> s = 'abcd'
>>> t = 'efg'
>>> s + t
'abcdefg'
CS1010E Programming Methodology 23

Strings
• A string is a sequence of characters enclosed in
single (or double) quotes, e.g. 'abcd'
• String operations:
3. We can compare two strings, e.g.

>>> s = 'abcd'
>>> t = 'efg'
>>> s < t
True

* Compare the 1st pair of characters first. If equal, compares the 2nd
pair of characters, … until a difference is found.
CS1010E Programming Methodology 24

More String Operations


>>> s = 'ba'
>>> t = s * 2 # create 2 copies of s
>>> t
baba
>>> 'ab' in s # is 'ab' part of s?
False
>>> 'ab' in t
True
>>> w = (s+'@')*2 # what is w?

A comment starts with # and will


be ignored by Python interpreter
CS1010E Programming Methodology 25

String Slicing (generates a substring)


s[start:stop:step] Default:
start = 0
stop = #letters
step = 1
non-inclusive
s = 'abcdef'
>>> s[0:2] >>> s[1:5:3]
'ab' 'be'
>>> s[1:2] >>> s[::2]
'b' 'ace'
>>> s[:2]
'ab'
CS1010E Programming Methodology 26

Import Python Packages


• Python has defined a lots of packages for
programmers to use.
• We can import them into our program.

>>> import math


>>> math.pi
3.141592653589793
CS1010E Programming Methodology 27

Import Python Packages


• The other way to import a package:

>>> import math as m


>>> m.pi
3.141592653589793
CS1010E Programming Methodology 28

PROBLEM SOLVING BY
PROGRAMMING
CS1010E Programming Methodology 29

Programming Demo: Problem Statement


• Given a square inscribed in a circle with all the four
corners of the square touching the circumference of the
circle, write a program to read the length of the inscribed
square and print out the area of the circle.

Think about algorithm first


 Algorithm is the outline of your
program where your focus is on
the major logic of problem
2a
solving, ignoring tiny details
CS1010E Programming Methodology 30

Programming Demo: Problem Statement


• Given a square inscribed in a circle with all the four
corners of the square touching the circumference of the
circle, write a program to read the length of the inscribed
square and print out the area of the circle.

Algorithm design:
 What is known to you?
 What is to calculate?
2a  What do you need to know?
CS1010E Programming Methodology 31

Programming Demo: Problem Statement


• Given a square inscribed in a circle with all the four
corners of the square touching the circumference of the
circle, write a program to read the length of the inscribed
square and print out the area of the circle.

Algorithm design:
r  Pythagoras’ theorem:
r2 = a 2 + a 2 = 2 * a 2
2a  Area of circle:
c = π * r2
= π * 2 * a2
CS1010E Programming Methodology 32

Programming Demo: Problem Statement


• Given a square inscribed in a circle with all the four
corners of the square touching the circumference of the
circle, write a program to read the length of the inscribed
square and print out the area of the circle.

Algorithm:
r 1. Read length of square from user
2. Compute radius r: r2 = 2 * a2
2a
3. Compute area c = π * r2
4. Print out area of the circle
CS1010E Programming Methodology 33

Sample Python Implementation


import math

# 1. Read length of square from user


length_str = input('Enter length of square: ')
length_int = int(length_str)

# 2. Compute radius square


radius_square = 2 * (length_int/2)**2

# 3. Compute area
area = math.pi * radius_square

# 4. Print out area of the circle


print('Area =', area)
CS1010E Programming Methodology 34

Moral of the Story


• Programming is more than learning syntax.

• Programming is about problem solving with


computer.
• Program is the implementation of your problem solving idea
(algorithm).

• We shall think out the ideas (algorithms) before


typing the programs
See you
next week.

You might also like