Programming Lecture 2
Programming Lecture 2
PROGRAMMING LANGUAGE-I
1
4 Major Versions of Python
• “Python” or “CPython” is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
4
Trace a Program Execution
Assign 20 to
# Assign a radius radius
radius = 20 # radius is now 20
radius 20
# Compute area
area = radius * radius * 3.14159
# Display results
print("The area for the circle of radius " +
str(radius) + " is " + str(area))
5
Trace a Program Execution
Assign result to
# Assign a radius area
radius = 20 # radius is now 20
radius 20
# Compute area
area = radius * radius * 3.14159 area 1256.636
# Display results
print("The area for the circle of radius“,
radius, " is "area)
6
Trace a Program Execution
print a message to
# Assign a radius the console
# Display results
print("The area for the circle of radius",
radius, "is", area)
7
Reading Input from the Console
var = eval(stringVariable)
8
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary information
• Turn off a line of code - perhaps temporarily
Identifiers/Variable Names
• An identifier is a sequence of characters that consists of
letters, digits, underscores (_), and asterisk (*).
• An identifier must start with a letter or an underscore. It
cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix
A, "Python Keywords," for a list of reserved words.)
Reserved words have special meanings in Python, which
we will later.
• An identifier can be of any length.
10
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words
• You can not use reserved words as variable names
/ identifiers
x = 12.2 x 12.2100
y = 14
x = 100 y 14
Variables
# Compute the first area
radius = 1.0
area = radius * radius * 3.14159
print("The area is ", area,
" for radius ", radius)
# Compute the second area
radius = 2.0
area = radius * radius * 3.14159
print("The area is ", area,
" for radius ", radius)
14
Expression
x = 1 # Assign 1 to variable x
radius = 1.0 # Assign 1.0 to variable radius
15
Assignment Statements
• We assign a value to a variable using the assignment
statement (=)
• An assignment statement consists of an expression on
the right hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
A variable is a memory
location used to store a x 0.6
value (0.6).
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
x = 3.9 * x * ( 1 - x )
19
Simultaneous Assignment
x, y = y, x # Swap x with y
ComputeAverageWithSimultaneousAssignment
20
Named Constants
The value of a variable may change during the execution
of a program, but a named constant or simply constant
represents permanent data that never changes. Python
does not have a special syntax for naming constants.
You can simply create a variable to denote a constant.
To distinguish a constant from a variable, use all
uppercase letters to name a constant.
21
Several Types of Numbers
• Numbers have two main
types
• Integers are whole numbers: - >>> xx = 1
>>> type (xx)
14, -2, 0, 1, 100, 401233
<class 'int'>
• Floating Point Numbers have >>> temp =
decimal parts: -2.5 , 0.0, 98.6, 98.6
14.0 >>> type(temp)
< class 'float'>
• There are other number >>> type(1)
types - they are variations < class 'int'>
on float and integer >>> type(1.0)
< class 'float'>
>>>
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
// Integer Division 1 // 2 0
% Remainder 20 % 3 2
The % Operator
2 3 3 1 Quotient
3 7 4 12 8 26 Divisor 13 20 Dividend
6 12 24 13
1 0 2 7 Remainder
24
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is always
1. So you can use this property to determine whether a
number is even or odd. Suppose today is Saturday and you
and your friends are going to meet in 10 days. What day is
in 10 days? You can find that day is Tuesday using the
following expression:
25
Variable Names Legal and
Illegal
• You've already learned three rules about naming a variable:
• 1. You can't enclose it in quotation marks.
• 2. You can't have any spaces in it.
• 3. It can't be a number or begin with a number.
• In addition, a variable can't be any of Python's reserved words, also
known as keywords—the special words that act as programming
instructions, like print
Concatenating text strings
In Chapter 1 you learned to display a string on the screen, coding it this You tell Python to combine the two strings this way:
way.
In Chapter 2, you learned that you could use a variable to do the same It's called concatenation. All it takes is a plus sign. Now, if you
thing.
code…
1 greeting = "Hello, World!"
2 print(greeting) print(whole_greeting)
But suppose you wanted to break the greeting into two parts, and
assign each part to a separate variable, like this: …Python displays HelloWorld
1 greeting = "Hello"
2 addressee = "World"
Python Literals
literals: Eg:
I. String literals: 1. >>> text1='hello'
String literals can be formed by enclosing a text b).Multi line String- A piece of text that is spread along multiple
in the quotes. We can use both single as well as lines is known as Multiple line String.
double quotes for a String.
There are two ways to create Multiline Strings:
Eg:
"Aman" , '12345'
1). Adding black slash at the end of 2).Using triple quotation marks:-
each line.
Eg:
Eg:
1. >>> str2='''''welcome
1. >>> text1='hello\
2. to
2. user'
3. SSSIT'''
3. >>> text1
4. >>> print str2
4. 'hellouser'
5. welcome
5. >>>
6. to
7. SSSIT
8. >>>
Numeric Literals are immutable. Numeric literals can belong to
following four different numerical types.
DisplayTime
32
Overflow
When a variable is assigned a value that is too
large (in size) to be stored, it causes overflow.
For example, executing the following
statement causes overflow.
>>>245.0 ** 1000
OverflowError: 'Result too large'
33
Underflow
When a floating-point number is too small (i.e., too close to
zero) to be stored, it causes underflow. Python
approximates it to zero. So normally you should not be
concerned with underflow.
34
Scientific Notation
• - Floating-point literals can also be specified in
scientific notation, for example,
• - 1.23456e+2, same as 1.23456e2, is equivalent
to 123.456, and
• - 1.23456e-2 is equivalent to 0.0123456.
• E (or e) represents an exponent and it can be
either in lowercase or uppercase.
35
Arithmetic Expressions
is translated to
36
Order of Evaluation
• When we string operators together - Python must
know which one to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to
lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and
Remainder
Parenthesis
• Addition and Subtraction Power
• Left to right Multiplication
Addition
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print(x)
11 1+8/4*5
>>>
1+2*5
Parenthesis
Power 1 + 10
Multiplication
Addition
Left to Right
11
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print x
11 1+8/4*5
>>> Note 8/4 goes before 1+2*5
4*5 because of the
left-right rule.
Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right
Operator
Precedence
• Remember the rules top to bottom Parenthesis
• When writing code - use parenthesis Power
Multiplication
• When writing code - keep Addition
Left to Right
mathematical expressions simple
enough that they are easy to
understand
• Break long series of mathematical
operations up to make them more
clear
Exam Question: x = 1 + 2 * 3 - 4 / 5
How to Evaluate an
Expression
Though Python has its own way to evaluate an
expression behind the scene, the result of a Python
expression and its corresponding arithmetic expression
are the same. Therefore, you can safely apply the
arithmetic rule for evaluating a Python expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
42
Mixing Integer and Floating
• When you perform
an operation where
one operand is an
integer and the other
operand is a floating
point the result is a >>> print (1 + 2 * 3 / 4.0 – 5)
floating point -2.5
>>>
• The integer is
converted to a
floating point before
the operation
Augmented Assignment
Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
44
Type Conversion and
Rounding
datatype(value)
round(4.6) => 5
round(4.5) => 4
45
Problem: Keeping Two Digits
After Decimal Points
Write a program that displays the sales tax with two digits
after the decimal point.
SalesTax
46
Problem: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The time.time() function returns the current time in seconds
with millisecond precision since the midnight, January 1,
1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.) You can use this function
to obtain the current time, and then compute the current
second, minute, and hour as follows.
Elapsed
time ShowCurrentTime
Time
Unix epoch Current time
01-01-1970 time.time()
00:00:00 GMT
47
Software Development Process
Requirement
Specification
System
Analysis
System
Design
Implementation
Testing
Deployment
Maintenance
48
Requirement Specification
A formal process that seeks to understand
Requirement the problem and document in detail what
Specification
the software system needs to do. This
System phase involves close interaction between
Analysis
users and designers.
System
Design
Implementation
Testing
Implementation
Testing
Part of the analysis entails modeling
the system’s behavior. The model is Deployment
intended to capture the essential
elements of the system and to define Maintenance
services to the system.
50
System Design
Requirement
Specification
The process of designing the
system’s components.
System
Analysis
System
Design
Implementation
Testing
System
Analysis Input, Process, Output
System
Design
Implementation
Testing
Maintenance
52
Implementation
Requirement
Specification The process of translating the
System system design into programs.
Analysis Separate programs are written for
System each component and put to work
Design
together.
Implementation
Testing
53
Testing
Requirement
Specification
Ensures that the code meets the
System requirements specification and
Analysis
weeds out bugs.
System
Design
Implementation
Testing
54
Deployment
Requirement
Specification
Deployment makes the project
System available for use.
Analysis
System
Design
Implementation
Testing
Deployment
Maintenance
55
Maintenance
Requirement
Specification
Maintenance is concerned with
System changing and improving the
Analysis
product.
System
Design
Implementation
Testing
ComputeLoan
57
Case Study: Computing Distances
ComputeDistance Run
58
Case Study: Computing Distances
ComputeDistanceGraphics
59