Chapter 5 - Elementary Programming
Chapter 5 - Elementary Programming
CHAPTER 5
ELEMENTARY PROGRAMMING
CONTENTS
Assignment
Constants Expressions Operators
Statement
Data Type
Statements Indentation Comments
Conversion
Introduction to CSE 2
Writing a Simple Program
• Problem: Calculating the area of a circle.
• Algorithm:
1. Get the circle’s radius from the user.
2. Compute the area by applying the following formula:
area = radius * radius * PI
3. Display the result.
• Important issues:
• How to read the radius?
• How to store the radius, area in the program?
• Values for the radius and area are stored in the computer’s
memory
• How to display result?
Introduction to CSE 3
Writing a Simple Program
• Program
Introduction to CSE 4
Keywords
• Keywords that are reserved words, have special meanings.
They cannot be used as variable names, function names, or
any other identifiers.
Introduction to CSE 5
Identifier
• Identifier is the name that identify the element in a program
such as variable, function, array….
• All identifiers must obey the following rules:
• Consists of letters, digits, and underscores (_)
• Must start with a letter or an underscore, cannot start with a
digit
• Cannot be a keyword
• Can be of any length
• Example:
• Legal identifiers: area, radius, top_of_page, temp1…
• Not legal identifiers: 2A, for, search elem
Introduction to CSE 6
Identifier
• Note:
• Python is case sensitive → area, Area, and AREA are all
different identifiers
• Tip:
• Descriptive identifiers → easy to read, understand, maintain
• Use lowercase letters for variable names
• Two major ways to paste words together:
• Underscore: radius_of_circle
• Camel Case: radiusOfCircle
• Quiz:
• Which of the following identifiers are valid?
miles, Test , a+b, b–a, 4#R, $4, #44, if
Introduction to CSE 7
Data Types
• A data type consists of two things:
• A set of values it can have
• A set of operations that can be performed on those values
• Basic data types:
• Integer
• Floating-Point Number
• Complex Number
• String
• Boolean
Introduction to CSE 8
Data Types
1. Integer
• Contains values: -3, 3, 0, -1, 1234,…
• Type: int
• An integer value in other bases
Prefix Base
0b (zero + 'b') 2
0B (zero + 'B')
0o (zero + 'o') 8
0O (zero + 'O')
0x (zero + 'x') 16
0X (zero + X')
Introduction to CSE 9
Data Types
2. Floating-Point Number
• Contains real values with a decimal point: -3.5, 3.1419, 4.2e-
4…
• Type: float
• Precision: float values are only approximations to real
numbers.
Introduction to CSE 10
Data Types
3. Complex Number
• Complex numbers are specified as <real part> + <imaginary
part>j
• Type: complex
Introduction to CSE 11
Data Types
4. String
• String is sequence of character
data.
• Type: str
• String literals may be delimited
using either single or double
quotes
• ‘Hello’
• “Hello”
• A string can also be empty: ‘’
• To include special character in a
string → using a backslash (\)
Introduction to CSE 12
Data Types
4. String
Special Character
Escape Example
Sequence
\'
\"
\newline
\\
Introduction to CSE 13
Data Types
4. String
Applying Special Meaning to Characters
Escape Interpretation
Sequence
\t Horizontal Tab (TAB) character
\n New line
\a Bell (BEL) character
\b Backspace character
\r Carriage Return (CR) character
Introduction to CSE 14
Data Types
4. String
Example:
Introduction to CSE 15
Data Types
5. Boolean
• Boolean type may have one of two values, True (1) or False
(0)
• Type: bool
• Expressions are often evaluated in Boolean context.
Introduction to CSE 16
Variables
• Variables are the names that refers to different values stored in memory.
Every value has a data type.
• Naming variables must follow the rules of identifiers.
• Variable Creation
• Assign values to a variable
variable = expression
• ‘=’ : gets, not equals
• We can reassign the value of a variable
Introduction to CSE 17
Variables
A variable must be
• NOTE: created before it can
be used.
Introduction to CSE 18
Variables
• NOTE: radius 1.5
Python is a dynamically typed language
2
Dynamic Typing
• Interpreter does type checking
only as code runs
• Type of a variable is allowed to
change over its lifetime
Static Typing
• Type checking is performed as
your program is compiled
• A variable generally is not
allowed to change type.
Introduction to CSE 19
Variables
Object References
• Python is a highly object-oriented language → every item of
data in a Python program is called an object.
• Objects can be very small (the number 3) or very large (a
digital photograph)
• Every object stored in memory location.
radius PyFloatObject {
value = 1.5
}
PyIntObject {
value = 2
}
Introduction to CSE 20
Variables
Object References
x PyIntObject {
value = 7
}
y PyIntObject {
value = 3
}
PyStrObject {
value = “abc”
}
Introduction to CSE 21
Variables
• NOTE:
Lifetime of an object
• An object’s life begins when it is created, at which time at
least one reference to it is created.
• When there is no reference to object:
→ lifetime is over
→ it is inaccessible
→ reclaim the allocated memory (garbage collection)
Introduction to CSE 22
Assignment Statement
• The general syntax:
variable = expression
• This is executed as follows:
1. Evaluate the expression to produce a value.
2. Assign value of expression to variable.
• An expression represents a computation involving values, variables,
and operators that, taken together, evaluate to a value.
Introduction to CSE 23
Assignment Statement
• Syntax to assgin a value to multiple variables :
var1 = var2 =…varn = expression
• Example:
i=j=k=1
equivalent to
k=1
j=k
i=j
Introduction to CSE 24
Assignment Statement
• Syntax of Simultaneous Assignment:
var1, var2, ..., varn = exp1, exp2, ..., expn
• Evaluate all the expressions on the right and assign them to the
corresponding variable on the left simultaneously.
Using temporary variable Using simultaneous assignment
Introduction to CSE 25
Assignment Statement
• Simultaneous Assignment
Example: Input three numbers and obtains their average.
Constants
• A constant is an identifier that represents a permanent value
(never change).
• Python does not have a special syntax for constants
→Create a variable to denote a constant.
→To distinguish a constant from a variable, use all uppercase
letters to name a constant
• Example: PI = 3.14159
• Benefits of using constants:
1. Don’t have to repeatedly type the same value if it is used
multiple times.
2. If you have to change the constant’s value, only need to
change it once.
3. Descriptive names make the program easy to read.
Introduction to CSE 27
Expressions
• An expression is a combination of zero or more operators
and one or more operands.
• Operands: constants, variables, function calls.
• Operators: are special tokens that represent computations.
• The interpreter evaluates expression → produces a value.
• Example:
• 42, n, print(“hello”)
• 3*((i % 4)*(5 +(j – 2)/(k+3)))
• x >= y
• x >= 0 and y >= 0
Introduction to CSE 28
Operators
• Operators are used to perform operations on variables and
values.
• Python divides the operators in the following groups:
• Arithmetic operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
• Assignment operators
Introduction to CSE 29
Arithmetic operators
Arithmetic operators are used to perform common mathematical operations:
Introduction to CSE 31
Comparison Operators
• Comparison operators are used to compare two values.
• It either returns True or False
Types of
Operator Syntax Meaning Example
Operands
1 == 2 → False
int, float,
== a == b Equal "he" == "He" → False
complex, str
1.1 + 2.2 == 3.3 →False
int, float, 3 != 3.0 → False
!= a != b Not equal
complex, str (1+2j) != (4+2j) → True
> a>b Greater than int, float, str 7 > 5 → True
< a<b Less than int, float, str 'he' < 'an‘ → False
>= a >= b Greater than or equal to int, float, str 100 >= 100 → True
<= a <= b Less than or equal to int, float, str 100 <= 50 → False
Introduction to CSE 32
Logical Operators
• Logical operators are used to combine comparison
expression.
• Type of Operands is bool.
• It either returns True or False
Operator Syntax Meaning Example
((9/3 == 3) and (2*3 ==6))
True if both a and b are True → True
and a and b
False otherwise (('A'== 'a') and (3==3))
→ False
True if either a or b is True ((2==3) or ('A'=='A'))
or a or b
False otherwise → True
True if x is False
not not a not(3 == 3) → False
False if x is True
Introduction to CSE 33
Logical Operators
NOTE: Evaluation of Non-Boolean Operands
• Numeric Value
• A zero value is False.
A non-zero value is True.
• String
• An empty string is False.
A non-empty string is True.
• Composite Object: list, tuple, dict, and set
• False if it is empty and True if it is non-empty
• “None” Keyword
Introduction to CSE 34
Logical Operators
NOTE: Evaluation of Non-Boolean Operands
a b a and b a or b not a
True True/False b a False
Introduction to CSE 35
Identity Operators
• Identity operators are used to compare the objects
• not if they are equal, but if they are actually the same object,
with the same memory location
Introduction to CSE 36
Membership Operators
• Membership operators are used to test whether a value or
variable is in a sequence.
Introduction to CSE 37
Bitwise Operators
• Bitwise operators are used to compare (binary) numbers.
Introduction to CSE 38
Assignment operators
Assignment operators are used to assign values to variables:
Introduction to CSE 39
Operator Precedence
Order Operator Order Operator
1 or 9 +, -
2 and 10 *, /, //, %
3 not x 11 +x, -x, ~x
in, not in, is, is not, <, <=,
4 12 **
>, >=, !=, ==
x[index], x[index:index], x(arg
5 | 13
uments...), x.attribute
6 ^ (expressions...),
14 [expressions...], {key: value...}
7 & , {expressions...}
8 <<, >>
Introduction to CSE 41
Statements
• Programs are made up of statements, or instructions
• Statements are divided into 2 types:
• Simple statements
• Function calls
• Assignment statements
• Statements: break, continue, return
• …
• Compound statements
• Contain other statements
• Affect or control the execution of those other statements
• Such as: if , for, while, try, with,…
Introduction to CSE 42
Indentation
• Block of statements:
• Grouping of statements for a specific purpose
• Most of the programming languages like C/C++, Java use braces { } to
define a block of statements
• Python uses indentation to highlight the block
• Whitespace is used for indentation
• A block starts with indentation and ends with the first unindented line
• All statements with the same distance to the right belong to the same
block
Introduction to CSE 43
Comments
• Comments can be used to:
• Explain Python code that may not be easy to understand
• Make the code more readable
• Prevent execution when testing code.
• Comments are not compiled and executed
• Creating a Comment:
• Using # for single line
• Using triple quotes (multiline string) for multi-line
Introduction to CSE 44
Comments
Introduction to CSE 45