0% found this document useful (0 votes)
27 views67 pages

Pthyon CHP 2

Uploaded by

Xue Ni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views67 pages

Pthyon CHP 2

Uploaded by

Xue Ni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

CHAPTER 2

VARIABLES, DATA
TYPES, Kuru Ratnavelu &Assistant
COMMENTS , Prof Ts Chit Su Mon

ERROR MESSAGES
Constants
• Fixed values such as numbers, letters, and
strings are called “constants” - because
their value does not change
• Numeric constants are as you expect
• String constants use single-quotes (') 123
>>> print
or double-quotes (") 123
>>> print 98.6
98.6
>>> print 'Hello world'
Hello world
Variables
• A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later
statement

x = 12.2 x 12.2100
y = 14
x = 100 y 14
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

and del for is raise


assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Sentences or Lines

x=2 Assignment Statement


x=x+2 Assignment with expression
print x Print statement

Variable Operator Constant Reserved Word


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
Right side is an expression.
Once expression is 0.93
evaluated, the result is
placed in (assigned to) x.
A variable is a memory
location used to store a
value. The value stored in a x 0.6 0.93
variable can be updated by
replacing the old value (0.6)
with a new value (0.93).

x = 3.9 * x * ( 1 - x )

Right side is an expression.


Once expression is 0.93
evaluated, the result is
placed in (assigned to) the
variable on the left side (i.e.
x).
Numeric Expressions
• Because of the lack of Operator Operation
mathematical symbols on + Addition
computer keyboards - we Subtractio
use “computer-speak” to -
n
express the classic math Multiplicati
operations *
on
• Asterisk is multiplication / Division
• Exponentiation (raise to a ** Power
power) looks different from
in math. % Remainder
Numeric Expressions

>>> xx = 2 >>> jj = 23 Operator Operation

>>> xx = xx + 2 >>> kk = jj % 5 + Addition

>>> print xx >>> print kk -


Subtractio

4 3 n
Multiplicati
>>> yy = 440 * 12 >>> print 4 ** 3 *
on

>>> print yy 64 / Division

5280 4R3 ** Power

>>> zz = yy / 1000 5 23 % Remainder


>>> print zz 20
5
3
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)
Parenthesis
• Multiplication, Division, and Remainder
Power
• Addition and Subtraction Multiplication
• Left to right 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 Parenthesis
Power
•Remember the rules top to bottom Multiplication
Addition
•When writing code - use parenthesis Left to Right
•When writing code - keep 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
Python Built-in Core Data
Types
Python offers following built-in core data types :
i) Numbers ii) String iii) List iv) Tuple v) Dictionary

Built-in Core Data Types

Numbers String List Tuple Dictionary

Floating-Point Complex
Integers
Numbers Numbers

Integers(Signed)

Boolean
Intege
rs
Integers are whole numbers. They have no fractional parts.
Integers can be positive or negative.
There are two types of integers in Python:
i) Integers(Signed) : It is the normal integer representation of
whole numbers using the digits 0 to 9. Python provides
single int data type to store any integer whether big or
small. It is signed representation i.e. it can be positive or
negative.
ii)Boolean : These represent the truth values True and False. It
is a subtype of integers and Boolean values True and False
corresponds to values 1 and 0 respectively
Demonstration of Integer Data
Type
#Demonstration of Integer-Addition of two integer
number a=int(input("Enter the value of a:"))
b=int(input("Enter the value of
b:")) sum=a+b
print("The sum of two
integers=",sum)

Output:
Enter the value of a: 45
Enter the value of b:
67
The sum of two
integers= 112
Floating Point
Numbers
A number having fractional part is a floating point
number. It has a decimal point. It is written in two forms :
i) Fractional Form : Normal decimal notation e.g. 675.456
ii) Exponent Notation: It has mantissa and
exponent. e.g. 6.75456E2
Advantage of Floating point numbers:
They can represent values between the integers.
They can represent a much greater range of values.
Disadvantage of Floating point numbers:
Floating-point operations are usually slower than
integer operations.
Demonstration of Floating Point Data
Type
#Demonstration of Float Number- Calculate Simple
Interest princ=float(input("Enter the Principal Amount:"))
rate=float(input("Enter the Rate of
interest:")) time=float(input("Enter the Time
period:")) si=(princ*rate*time)/100
print("The Simple Interest=",si)

Output:
Enter the Principal
Amount:5000 Enter the Rate of
interest:8.5 Enter the Time
period:5.5 Simple Interest=
2337.5
Complex Number
Python represents complex numbers in the form a+bj.

#Demonstration of Complex Number- Sum of two


Complex Numbers
a=7+8j
b=3.1+6
j
c=a+b
print("Sum of two Complex
Numbers") print(a,"+",b,"=",c)
Output:
(7+8j) + (3.1+6j) = (10.1+14j)
String
s characters enclosed in Single or
A String is a group of valid
Double quotation marks. A string can group any type of
known characters i.e. letters ,numbers and special characters.
A Python string is a sequence of characters and each
character can be accessed by its index either by forward
indexing or by backward indexing.
e.g. subj=“Computer”

Forward indexing 0 1 2 3 4 5 6 7
Subj C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1 B
ackward indexing
#Demonstration of String- To input string & print
it my_name=input("What is your Name? :")
print("Greetings!!!")
print("Hello!",my_name)
print("How do you
do?")

Output :
What is your Name? :Ananya
Inkane Greetings!!!
Hello! Ananya
Inkane How do you
do?
List
The List is Python’s compound data type. A List in Python
represents a list of comma separated values of any data type
between square brackets. Lists are Mutable.
#Demonstration of List- Program to input 2 list & join
it List1=eval(input("Enter Elements for List 1:"))
List2=eval(input("Enter Elements for List 2:"))
List=List1+List2
print("List 1 :",List1)
print("List 2 :",List2)
print("Joined List :",List)
Output:
Enter Elements for List 1:[12,78,45,30]
Enter Elements for List 2:[80,50,56,77,95]
List 1 : [12, 78, 45, 30]
List 2 : [80, 50, 56, 77, 95]
Joined List : [12, 78, 45, 30, 80, 50, 56,
77, 95]
Tupl
e
The Tuple is Python’s compound data type. A Tuple in Python
represents a list of comma separated values of any data type
Within parentheses. Tuples are Immutable.
#Demonstration of Tuple- Program to input 2 tuple &
join it
tuple1=eval(input("Enter Elements for Tuple 1:"))
tuple2=eval(input("Enter Elements for Tuple
2:"))
Tuple=tuple1+tuple2
print(“Tuple 1 :“,tuple1)
print(“Tuple 2 :“,tuple2)
print("Joined Tuple :“,Tuple)
Output:
Enter Elements for Tuple 1:(12,78,45,30)
Enter Elements for Tuple 2:(80,50,56,77,95)
List 1 : (12, 78, 45, 30)
List 2 : (80, 50, 56, 77, 95)
Dictionary
Dictionaries are unordered collection of elements in curly braces in the form
of a key:value pairs that associate keys to values. Dictionaries are Mutable.
As dictionary elements does not have index value ,the elements are accessed
through the keys defined in key:value pairs.
#Demonstration of Dictionary- Program to save Phone nos. in dictionary
& print it
Phonedict={“Madhav”:9876567843,”Dilpreet”:7650983457,”Murugan”:9067
2 08769,”Abhinav”:9870987067}
print(Phonedict)
Output:
{'Madhav': 9876567843, 'Dilpreet': 7650983457, 'Murugan': 9067208769,
'Abhinav': 9870987067}
What does “Type” Mean?
• In Python variables,
literals, and constants
have a “type” >>> ddd = 1 + 4
• Python knows the >>> print ddd
difference between an 5
integer number and a >>> eee = 'hello ' + 'there'
string >>> print eee
• For example “+” means hello there
“addition” if something is a
number and “concatenate”
if something is a string concatenate = put together
>>> eee = 'hello ' + 'there'
Type Matters >>> eee = eee + 1
Traceback (most recent call
last):
• Python knows what File "<stdin>", line 1, in
“type” everything is <module>
• Some operations are TypeError: cannot
prohibited concatenate 'str' and 'int'
objects
• You cannot “add 1” to a >>> type(eee)
string <type 'str'>
• We can ask Python what >>> type('hello')
type something is by <type 'str'>
using the type() function. >>> type(1)
<type 'int'>
>>>
Several Types of Numbers
•Numbers have two main >>> xx = 1
>>> type (xx)
types <type 'int'>
• Integers are whole numbers: >>> temp = 98.6
-14, -2, 0, 1, 100, 401233
>>> type(temp)
• Floating Point Numbers have <type 'float'>
decimal parts: -2.5 , 0.0, >>> type(1)
98.6, 14.0
<type 'int'>
•There are other number >>> type(1.0)
types - they are variations <type 'float'>
on float and integer >>>
Number
s
• Numbers are referred to as numeric literals
• Two Types of numbers: ints and floats
– Whole number written without a decimal point
called an int
– Number written with a decimal point
called a
float

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Number
s
• Arithmetic Operators
– Addition, subtraction, multiplication, division, and
exponentiation.
• Result of a division is always a float
• Result of the other operations is a float if …
– Either of the numbers is a float
– Otherwise is an int.

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Type Conversions >>> print float(99) / 100
0.99
>>> i = 42
•When you put an >>> type(i)
integer and floating <type 'int'>
point in an >>> f = float(i)
expression the >>> print f
integer is implicitly 42.0
converted to a float >>> type(f)
•You can control this <type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
with the built in -2.5
functions int() and >>>
float()
The print Function
• Used to display numbers on the monitor
– If n is a number, print(n) displays number n.
– The print function can display the result of
evaluated expressions
– A single print function can display several
values
Example 1: Program
demonstrates
operations
© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS
RESERVED.
The abs Function

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
The int
Function

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
The round
Function

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
abs, int, and round
Example
• Example 3: Program evaluates
functions, prints results

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Mixing Integer and Floating
•When you perform an >>> print 99 / 100
operation where one 0
operand is an integer
>>> print 99 / 100.0
and the other operand
is a floating point the 0.99
result is a floating >>> print 99.0 / 100
point 0.99
•The integer is >>> print 1 + 2 * 3 / 4.0 - 5
converted to a floating -2.5
point before the >>>
operation
Augmented Assignments
• Remember: expression on right side of
assignment statement evaluated before
assignment is made
var = var + 1
• Python has special operator to accomplish
same thing
var += 1

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Augmented Assignments
• Example 4:
Program illustrates
different
augmented
assignment
operators.

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Two Other Integer
Operators
• Integer division operator
– Written //
• Modulus operator
– Written %

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Python Integer Division is Weird!
•Integer division >>> print 10 / 2
truncates 5
>>> print 9 / 2
•Floating point division 4
produces floating point >>> print 99 / 100
numbers 0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
This changes in Python 3.0
String >>> sval = '123'
>>> type(sval)

Conversions <type 'str'>


>>> print sval + 1
Traceback (most recent call last):
•You can also use File "<stdin>", line 1, in <module>
int() and float() to TypeError: cannot concatenate 'str'
and 'int'
convert between >>> ival = int(sval)
strings and >>> type(ival)
integers <type 'int'>
>>> print ival + 1
•You will get an 124
error if the string >>> nsv = 'hello bob'
does not contain >>> niv = int(nsv)
Traceback (most recent call last):
numeric File "<stdin>", line 1, in <module>
characters ValueError: invalid literal for int()
User Input
•We can instruct
Python to pause
and read data
from the user nam = raw_input(‘Who are you?’
using the print 'Welcome', nam
raw_input
function
•The raw_input Who are you? Chuck
function returns a Welcome Chuck
string
Converting User Input
•If we want to read
a number from
the user, we must inp = raw_input(‘Europe floor?’)
convert it from a usf = int(inp) + 1
string to a print 'US floor', usf
number using a
type conversion
function Europe floor? 0
•Later we will deal US floor 1
with bad input
data
String Operations
• Some operators apply to
strings
>>> print 'abc' + '123’
• + implies “concatenation”
Abc123
• * implies “multiple
>>> print 'Hi' * 5
concatenation”
HiHiHiHiHi
• Python knows when it is >>>
dealing with a string or a
number and behaves
appropriately
Mnemonic Variable Names
• Since we programmers are given a choice in
how we choose our variable names, there is a
bit of “best practice”
• We name variables to help us remember what
we intend to store in them (“mnemonic” =
“memory aid”)
• This can confuse beginning students because
well named variables often “sound” so good
that they must be keywords
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c=a*b
print x1q3p9afd print c

hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print pay
Optional print Argument
sep
• Consider statement
print(value0, value1, …, valueN)
• Print function uses string consisting of one
space character as separator
• Optionally change the separator to any string
we like with the sep argument

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Optional print Argument
end
• Print statement ends by executing a newline
operation.
• Optionally change the ending operation with
the end argument

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
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
# Get the name of the file and open it
name = raw_input('Enter file:')
handle = open(name, 'r')
text = handle.read()
words = text.split()

# Count word frequency


counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1

# Find the most common word


bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

# All done
print bigword, bigcount
Escape Sequences
• Short sequences placed in strings
– Instruct cursor or permit some special characters
to be printed.
– First character is always a backslash (\).
• \t induces a horizontal tab
• \n induces a newline operation

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Escape Sequences
• Example 1: Program demonstrates the use of
the escape sequences \t and \n.

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Escape Sequences
• Backslash also used to treat quotation marks
as ordinary characters.
• \”causes print function to display double
quotation mark
• \\ causes print function to display single
backslash

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justifying Output in a
Field
• Example 2: Program demonstrates methods
ljust(n), rjust(n), and center(n)

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justify Output with
format

• Given: str1 is a string and w is a field width

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justify Output with
format

• Given: num is a number and w is a field width

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justify Output with
format
• Example 3: Program illustrates formatting

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justify Output with
format
• Table 2.4 Demonstrate number formatting.

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Justify Output with
format

• Example 4: Program formatting with


curly brackets

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Syntax
Errors
• Grammatical and punctuation errors are called
syntax errors.

Table 2.1 Three Syntax Errors

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Syntax
Errors

FIGURE 2.1 Syntax error message boxes.

© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS


RESERVED.
Runtime
Errors
• Errors discovered while program is running
called runtime errors or exceptions

Table 2.2 Three Runtime Errors


© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS
RESERVED.
Runtime
Errors
• When Python encounters exception
– Terminates execution of program,
displays message

FIGURE 2.2 An Error Message for an Exception Error


© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS
RESERVED.
Logic Error
• Occurs when a program does not perform the
way it was intended
• Example
average = firstNum + secondNum / 2
• Syntax correct, logic wrong: should be
average = (firstNum + secondNum) /
2
• Logic errors are most difficult type of error to
locate
© 2016 PEARSON EDUCATION, LTD. ALL RIGHTS
RESERVED.

You might also like