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

Year 1 Computer Programming - Lecture 2

The document discusses program design and the Python programming language. It covers topics like program design specification using pseudo code and flowcharts. It also discusses Python variables, data types, input/output functions, and defining functions. The document provides examples and explanations of these programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Year 1 Computer Programming - Lecture 2

The document discusses program design and the Python programming language. It covers topics like program design specification using pseudo code and flowcharts. It also discusses Python variables, data types, input/output functions, and defining functions. The document provides examples and explanations of these programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

CMP 4266

Software Development UG1


Lecture – 2

(Based on Gaddis, T., Starting out with Python 3e, Pearson Education)

CMP4266, School of CS & DT, Birmingham City University.


Outline
 Program Design Specification
 Python Programing Language
– Variables.

– Reading Input from the keyboard.

– Data type conversion

– Output formatting

– Defining functions with input and output

– Decision structures

CMP 4266, School of CS & DT, Birmingham City University.


Design Specification (Pseudo code)

 Programs must be designed before they are written


 Understand the task(s) that the program is to perform
 Determine the steps that must be taken to perform the task
– Create an algorithm, listing logical steps that must be taken
– Logical steps can be specified in Pseudo code or flowchart

 Pseudo code: fake code


– Informal language that has no syntax rule
– Not meant to be compiled or executed
– Used to create model program
- No need to worry about syntax errors, can focus on program’s
design
- Can be translated directly into actual code in any programming
language

CMP 4266, School of CS & DT, Birmingham City University.


Pseudo-Code: ATM Example

 output welcome message


 input service option
– if option = deposit then
– output “Enter amount to deposit”
– input amount
– balance  balance + amount

 if option = withdraw then


– output “Enter amount to withdraw”
– input amount
– balance  balance – amount

 output balance

CMP 4266, School of CS & DT, Birmingham City University.


Design Specification (Flow Chart)

 Flowchart: diagram that graphically depicts the steps in a


program
Symbol Function

Ovals are terminal symbols i.e. start or end

arrows represent the flow of the program and


connect the other symbol

Rectangles are processing symbols

Parallelograms are input and output symbols

A diamond indicates decision

CMP 4266, School of CS & DT, Birmingham City University.


Design Specification (Example)

 We are writing a program to calculate and display the gross pay for an
hourly paid employee.

1. Input the hours worked


2. Input the hourly pay rate
3. Calculate gross pay as
hours worked multiplied by pay
rate
4. Display the gross pay

CMP 4266, School of CS & DT, Birmingham City University.


Design Specification (Flow Chart)
2.1 Exercise (15 minutes)
In-class
 Draw a flowchart to log in to facebook account? Exercise

 To log in to facebook account we first enter the facbook URL


www.facebook.com in our browser like Chrome or Explorer etc. This
request is sent to the facebook server and it responds by sending us the
home page of facebook.
 Next, we enter our registered Email ID and Password and click the Login
button.
 Then our login credential is checked. If it is correct, we are shown our
profile. On the other hand, if the login credential is wrong then an error
occurs and we are prompted to re-enter our Email ID and Password.

CMP4266 , School of CS & DT, Birmingham City University.


Python Programming Language

CMP4266, School of CS & DT, Birmingham City University.


Variables

 Variable: name that represents a value stored in the computer


memory
– A variable references the value it represents
– Used to access and manipulate data stored in memory

 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 (=)

 In assignment statement, variable receiving value must be on


left side
 You can only use a variable if a value is assigned to it

CMP 4266, School of CS & DT, Birmingham City University.


Use of Variables

 Variables are names for different values i.e. numbers or


strings. You can use the variables to access these values later
in your code.
 Variables make your code re-usable with different cases.
 For example: Body mass index (BMI) is a measure of body fat
based on your weight in relation to your height
– The formula to calculate human BMI is:

No variables – hardcoded Code with variables


values weight = 75
height = 163

75 / (163 * 163) BMI = weight / (height * height)


CMP 4266, School of CS & DT, Birmingham City University.
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
– Python does not allow punctuation characters such @, $, % in Variables.
 Python Keywords

CMP 4266, School of CS & DT, Birmingham City University.


Variable Examples

Variable Declaration Valid?


and = 2

And = 2

and12 = “And”

val 1 = 5

Val_1 = 5

1num = 12

_num = 7

CMP 4266, School of CS & DT, Birmingham City University.


Standard Built-In Types

 Principal built-in types are


– Numerics
- Integers : used to represent whole numbers, e.g. 10, 32 etc.

- Floating point numbers: used to represent number with fractions, i.e.


decimal numbers, e.g. 4.56, 2.33 etc.

– Sequences
- String : used to represent textual data, e.g. “Hello”, “welcome” etc.

CMP 4266, School of CS & DT, Birmingham City University.


Comments and Reading Input from the Keyboard

 Comments: notes of explanation within a program


– Ignored by Python interpreter
- Intended for a person reading the program’s code
– Begin with a # character
 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

– Example

s = input("Enter your name : ")


Enter your name :
CMP 4266, School of CS & DT, Birmingham City University.
Data Type Conversion

 Built-in functions convert between data types


– int(item) converts item to an int
– float(item) converts item to a float
– str(item) converts item to a string

 Example

num_str = input("Enter a number > ")


num = int(num_str)

CMP 4266, School of CS & DT, Birmingham City University.


Data Type Conversion

 Nested function call: general format:


function1(function2(argument))
- value returned by function2 is passed to function1

– Example
a=int(input("Enter your age "))

– Type conversion only works if item is valid numeric/string value,


otherwise, throws exception

name = "Alex"
int(name)

ValueError: invalid literal for int() with base 10: 'Alex'

CMP 4266, School of CS & DT, Birmingham City University.


Formatted Output

 print function displays line of output


– Allows multiple comma separated items to print in one line
– uses space as item separator
– Special argument sep=‘delimiter’ causes print to use
delimiter as item separator
– prints a new line at the end. you can pass the special argument
end=' ‘ to suppress newline
 Example
print('One', 'Two', 'Three') print("One") print("One", end = ' ')
One Two Three print("Two") print("Two", end = ' ')
print("Three") print("Three", end = ' ')
print('One', 'Two', 'Three', sep='*')
One*Two*Three One
Two One Two Three
Three

CMP 4266, School of CS & DT, Birmingham City University.


Formatted Output

 Python allows to interpolate numbers into printed strings.


 %d, %f and %s are used to interpolate integer, float and string values
respectively.

 Example
age=10
print(“He is %d years old" %age)
He is 10 years old

 The % symbol can be used to define field width and decimal precisions as
well.
_float = 11.56542
 Example, print ("a float %14.2f" % _float )
a float 11.57

CMP 4266, School of CS & DT, Birmingham City University.


Exercise 2.2 – Implementation of BMI
calculation (15 minutes)
In-class
 The program calculates a person's BMI from the weight and Exercise
height supplied using the user's input.
 The system should ask for user’s name, weigh and height.
 Each input value should be converted into the correct data
format.
 The name and results from the BMI calculation should be printed
on the screen using the formatted output.
– The formula to calculate human BMI is:

 The software output will look the following

CMP4266 , School of CS & DT, Birmingham City University.


Introduction to Functions

 Function: group of statements within a program that perform as specific


task. Usually one task of a large program

 Instead of writing a large program as one long sequence of statements, it


can be written as several small functions, each one performing a specific
part of the task.

 These small functions can then be executed in the desired order to perform
the overall task.

 There are many benefits of using functions, including


 A program’s code tends to be simpler and easier to understand
 Functions also reduce the duplication of code within a program. If a specific
operation is performed in several places in a program, a function can be written
once to perform that operation, and then be executed any time it is needed.
CMP 4266, School of CS & DT, Birmingham City University.
Function in Python

 Function definition: specifies what function does


def function_name(parameter1, parameter2..):
statement
statement
.. .. ..
return..
 Function header: first line of function
– Includes keyword def and function name, followed by parentheses and
colon. Inside the parentheses you can specify list of arguments.
 Block: set of statements that belong together as a group
 Each block must be indented, i.e. Lines in block must begin with the same
number of spaces. IDLE automatically indents the lines in a block

CMP 4266, School of CS & DT, Birmingham City University.


Function Example

Valid Function Declaration Invalid Function Declaration

def area(width, height): def area(width, height):


a = width * height a = width * height
return a return a

CMP 4266, School of CS & DT, Birmingham City University.


Exercise 2.3 – BMI calculation function -
(10 minutes)
In-class
Exercise

 Define a function to implement the BMI software completed in


Exercise 2.2
 The function header should be called bmi_cal
 Use input parameters to allow the function to print the person
name and his/her BMI calculation.
 When the function is defined, execute the function with the
needed input parameters.

CMP4266 , School of CS & DT, Birmingham City University.


Library Functions and Modules

 Standard library: library of pre-written functions that comes with Python


– Library functions perform tasks that programmers commonly need
- Example: print, input

 Some library functions built into Python interpreter. To use, just call the
function
 Modules: files that stores functions of the standard library
– Help organize library functions not built into the interpreter
– Copied to computer when you install Python
 To call a function stored in a module, need to write an import statement
– Written at the top of the program
– Format: import module_name
– Example
import math
math.pow(2, 2)
4.0

CMP 4266, School of CS & DT, Birmingham City University.


Control Structure

 Control Structure: logical design that controls order in which


set of statements execute
– Sequence structure: set of statements that execute in the order they
appear

def area(width, height):


a = width * height
return a

– Decision structure: specific action(s) performed only if a condition exists

CMP 4266, School of CS & DT, Birmingham City University.


Decision Structure

 Actions can be conditionally executed


– Performed only when a condition is true

 Single alternative decision structure:


provides only one alternative path of
execution
– If condition is not true, exit the structure

CMP 4266, School of CS & DT, Birmingham City University.


Decision Structure - The if Statement

 Python syntax:
if condition:
Statement
Statement

 First line known as the if clause


– Includes the keyword if followed by condition
- The condition can be true or false
- When the if statement executes, the condition is tested, and if it is
true the block statements are executed. otherwise, block statements
are skipped

CMP 4266, School of CS & DT, Birmingham City University.


Boolean Expressions and Relational Operators

 Boolean expression: expression tested by if statement to determine if it is


true or false
– Example: a > b
- true if a is greater than b; false otherwise
 Boolean variable: references one of two values, True or False.
Represented by bool data type
 Relational operator: determines whether a specific relationship exists
between two values
– Example: greater than (>)

CMP 4266, School of CS & DT, Birmingham City University.


Boolean Expressions and Relational Operators

 Any relational operator can be used in a decision block


– Example: if balance == 0
– Example: if payment != balance

 It is possible to have a block inside another block


– Example: if statement inside a function
– Statements in inner block must be indented with respect to the outer
block
– Example

def find_grade():
score = int(input("Enter Score : "))
if score >= 40:
print("Your grade is Pass")
CMP 4266, School of CS & DT, Birmingham City University.
Decision Structure - The if-else Statement

 Dual alternative decision structure: two possible paths of execution


– One is taken if the condition is true, and the other if the condition is false

– Syntax: if condition:
statements
else:
other statements
– if clause and else clause must be aligned
– Statements must be consistently indented
CMP 4266, School of CS & DT, Birmingham City University.
Decision Structure - The if-elif-else Statement

 if-elif-else statement: special version of a decision


structure
– Makes logic of nested decision structures simpler to write
- Can include multiple elif statements
– Syntax: if condition1:
statements
elif condition2:
statements
elif condition3:
statements
elif .. .. .. ..
else:
statements

CMP 4266, School of CS & DT, Birmingham City University.


Decision Structure - The if-elif-else Statement

CMP 4266, School of CS & DT, Birmingham City University.


Example Using Decision Structure

def find_grade():
score = int(input("Enter Score : "))
if score >= 90:
print("Your grade is A")
elif score >= 80:
print("Your grade is B")
elif score >= 70:
print("Your grade is C")
elif score >= 60:
print("Your grade is D")
else:
print("Your grade is F")

CMP 4266, School of CS & DT, Birmingham City University.


Logical Operators

 Logical operators: operators that can be used to create complex Boolean


expressions
– and operator and or operator: binary operators, connect two Boolean
expressions into a compound Boolean expression
– not operator: reverses the truth of its Boolean operand
 The and Operator Takes two Boolean expressions as operands and the
compound Boolean expression is true only when both sub expressions are
true
– Example: x >= 10 and x <= 20

 The or Operator Takes two Boolean expressions as operands and the


compound Boolean expression is true when either of the sub expressions is
true
– Example: x < 10 or x > 20

CMP 4266, School of CS & DT, Birmingham City University.


Logical Operators (Examples)

 a > b and c < a or b > c : what is the truth value if a=10, b=13 and
c=8.

Truth value is True


a > b is False
c < a is True
b > c is True

So we have

False and True or True


False or True
True

CMP 4266, School of CS & DT, Birmingham City University.


Logical Operators (Examples)

 a > b and (c < a or b > c) : what is the truth value if a=10, b=13
and c=8.

Truth value is False


a > b is False
c < a is True
b > c is True

So we have

False and (True or True)


False and True
False

CMP 4266, School of CS & DT, Birmingham City University.


Logical Operators (Examples)

 not (a == b or c < a and b < c): what is the truth value if a=10,
b=13 and c=8.

Truth value is True


a == b is False
c < a is True
b < c is False

So we have

not (False or True and False)


not (False or False)
not (False)
True
CMP 4266, School of CS & DT, Birmingham City University.
Exercise 2.4 - Include the weight categories in
the bmi_cal function - (15 minutes)
In-class
Exercise
 Enhance the bmi_cal function to
provide meaningful feedback. E.g.
use is Underweight or Obese.
 For example, if the calculated BMI
value is 25.5, the programme should
print out a name and a message
suggesting the user is “Overweight”.
 See Figure for the weight categories.
 Use the decision structure, boolean
expressions and logical operators to
complete this exercise.

CMP4266 , School of CS & DT, Birmingham City University.

You might also like