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

Chapter-2 Data and Expressions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Chapter-2 Data and Expressions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

Data and Expressions

By
G. Lavanya
Contents
• Literals
• Variables and Identifiers
• Operators
• Expressions and Data Types
Literals
• A literal is a sequence of one or more characters that stands for itself.
• Used to completely express a fixed value of a specific data type.
• Literals are constants that are self- explanatory and don’t need to be
computed or evaluated.
• They are used to provide variable values or to directly utilize them in
expressions.
Types of literals
1.String literals
2.Character literal
3.Numeric literals
4.Boolean literals
5.Literal Collections
6.Special literals
Numeric Literals
• Contains only the digits (0-9), an optional sign character(+ or -) and a
possible decimal point.
• Three types
• Integer
• Float
• Complex
• Contains decimal point→ floating point value(float)
• Otherwise integer values
• Commas are never used in numeric literals.
Numeric literals in python
Integer
• Both positive and negative numbers including 0.
• There should not be any fractional part.
• Example: 0b10100,50,0x12b,0o320
• 1st→ binary literal
• 2nd →decimal literal
• 3rd→hexa decimal literal
• 4th→ octa decimal literal
Examples

But on using the print function to display


a value or to get the output they were
converted into decimal.
Float
• Real numbers having both integer and fractional parts.
Complex

• The numerals will be in the form of a+bj where a→ real part


b→ complex part

Real part is 0
Limits of Range in Floating-Point
Representation
• There is no limit to the size of an integer than can be represented in
Python.
• Floating point values have both a limited range and a limited
precision.
• Python uses a double precision standard format(IEEE 754) providing a
range of 10-308 to 10 308 with 16 to 17 digits of precision.
Limitations of Floating-point
representation

• Arithmetic overflow: Multiplication of two values


result is too large in magnitude
Result:Inf—Infinity

Arithmetic Correct Result:


3.0e410
Indicates ARITHMETIC
OVERFLOW
• Arithmetic Underflow- A condition that occurs when a calculated
result is too small in magnitude to be represented.

Result:0.0
Arithmetically correct
result:3.0e410
Indicates: Arithmetic
overflow has occurred
Limits of precision in Floating- Point
Representation
• Arithmetic overflow and arithmetic underflow are relatively easily
detected.
• The loss of precision that can result in a calculated result, however, is
a much more subtle issue.
• For example, 1/3 is equal to the infinitely repeating decimal
.33333333 . . ., which also has repeating digits in base two,
.010101010. . . .
• Floating point representation→ finite number of digits
• For floating point values , approximation of true value is stored
Decimal ends after 16 digits(Range)

Multiplication result rounded off

Approximation

Result Rounded value


Limitations of floating point number
representation
format function(Built-in)
• The format() function formats a specified value into a
specified format.
• Syntax: format(value, format)
• Example:
Examples:
String Literals
• Represents sequence of characters.
• Delimited by matching pair of single quote (‘) or double quote(“)
sometimes triple.
Partial listing of ASCII-compatible
UTF-8 encoding scheme
• The default encoding in Python uses UTF-8 , an 8-bit encoding
compatible with ASCII, an older, still widely used encoding scheme.

Capital Letters

Digits (0-9) Small Letters


Numeric Vs String Representation
of digits
Expecting String but here we have
given int type • Python has means for converting
between a character and its
encoding.
• Ord function gives UTF-8( ASCII)
encoding value for a given
character or string.
• Chr gives character for a given
encoding value.
• Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format()
• x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
o/p:The value of x is 5 and y is 10
print('I love {0} and {1}'.format('bread','butter'))
Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
Output: I love butter and bread
Character Literal
• It is also a type of Python string literal where a single character
is surrounded by single or double quotes.
Boolean Literal
• In Python, boolean literals are used to represent the two Boolean
values: ‘True’ and ‘False’.
• These literals are case-sensitive, which means you must use
uppercase "True" and "False" to represent them exactly as Boolean
literals. Here's how they are used:
• ‘True’: Represents the Boolean value for "true" or "1."
• ‘False’: Represents the Boolean value for "false" or "0.“
• These boolean literals are fundamental for making decisions and
controlling the logic of your Python programs.
• You can use these Boolean literals in various programming constructs, such as
conditional statements (if, else, elif), loops, and more, to control the flow of your Python
code. For example:

• # Using boolean literals in conditional statements


is_sunny = True
if is_sunny:
print("It's sunny today.")
else:
print("It's not sunny today.")

• # Using boolean literals in expressions


• result = True and False # result will be False
• result = True or False # result will be True
• result = not True # result will be False
Literal Collections
• Python provides four different types of literal collections:
1.List literals
2.Tuple literals
3.Dictionary literals
4.Set literals
• Literal collections are used to create data structures that store
multiple values.
List
• List is a ordered collection of items.
• The list contains items of different data types.
• The values stored in the List are separated by a comma (,) and
enclosed within square brackets([]).
• We can store different types of data in a List. Lists are
mutable(means you can CHANGE their contents).
Tuple
• A tuple is a collection of different data-type. It is enclosed by
the parentheses ‘()‘ and each element is separated by the
comma(,). It is immutable.
Difference between List and Tuple
Dictionary Literal
• The dictionary stores the data in the key-value pair.
• It is enclosed by curly braces ‘{}‘ and each pair is separated by the
commas(,).
• We can store different types of data in a dictionary. Dictionaries are
mutable.
Set Literal
• Set is the collection of the unordered data set.
• It is enclosed by the {} and each element is separated by the
comma(,).
Special Literal
• Python contains one special literal (None). ‘None’ is used to define a
null variable. If ‘None’ is compared with anything else other than a
‘None’, it will return false.
2.1.4 Control Characters
• These are the special characters that are not displayed on the screen.
• It controls the display of output.
• Do not have any corresponding keyboard character.
• Represented by combination of characters called escape sequence.
• Escape sequence begins with an escape character(escape the normal
meaning)
• \(backslash)→escape character
• Example:
Escape sequence ‘\n’ → newline control character
2.1.5 String Formatting
• format( value, format_specifier)
• Value→ value to be displayed
• format_specifier→ combination of formatting options
• Left Justification: Hello justified in a field width of 20 characters
• Right Justification:

• Center Justification:

• Blank Spaces:
• By Default: Left Justification
• Question: Print Hello World ……………………….. Have a nice day!
2.1.6 Implicit and Explicit Line joining
• Sometimes a program line may be too long to fit in the Python-
recommended maximum length of 79 characters.
• There are two ways in Python to do deal with such situations—
implicit and explicit line joining.
Implicit Line Joining
• In Python implicit line joining we uses parentheses, square
brackets or curly braces to split the expression in multiple
lines. For instance consider the code below.
Some points to be note
• i)There can be comment after the line.
2.Blank Lines are allowed to continue

3. Triple-quoted strings are also allowed to have continued


lines but here there cannot be comment in each line.
Explicit Line Joining
• When we want to join many logical lines we can use
the backslash characters (\).
• This character (\) will join the logical lines together as if they
are declared in one single line.
• Such method of joining the lines using the backslash(\) is
known as explicit line joining.
Exercise
• QUESTION:
Display the Unicode encoding value for each character in the string
“Hello World!”.
OUTPUT:

The program utilizes the following features:


1. String Literals
2. Print
3. Ord Function
Variables and Identifiers
2.2 Variables
• A variable is a name(identifier) that is associated with a value.

• A variable can be assigned different values during a program’s


execution. Hence, the name “variable”.
• Wherever a variable appears in a program (except on the left-hand
side of an assignment statement), it is the value associated with the
variable that is used , and not the variable’s name.
• num + 1 ➝ 10 + 1 ➝ 11
• Notes:
• The value stored in a variable can be changed during program
execution.
• A Variables in Python is only a name given to a memory
location, all the operations done on the variable effects that
memory location.
• Rules for Python variables
• A Python variable name must start with a letter or the
underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and
NAME are three different variables).
• The reserved words(keywords) in Python cannot be used to
name the variable in Python.
# valid variable name
geeks = 1
Geeks = 2
Ge_e_ks = 5
_geeks = 6
geeks_ = 7
_GEEKS_ = 8

print(geeks, Geeks, Ge_e_ks)


print(_geeks, geeks_, _GEEKS_)
Variables Assignment
• Variables are assigned values by use of the assignment operator , =

(Think = symbol as arrow symbol)


The right side of an
assignment is evaluated
first, then the result is
assigned to the variable
on the left

Variable Updation
• Variables may also be assigned to the value of another variable

• Variables num and k are both associated with the same literal value
10 in memory
Declaration and Initialization
of Variables
Redeclaring variables in Python

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)


Python Assign Values to Multiple
Variables

a = b = c = 10

print(a)
print(b)
print(c)
Assigning different values to
multiple variables
• Python allows adding different values in a single line with “,”
operators.
• Can we use the same name for different types?
• If we use the same name, the variable starts referring to a new
value and type.
+ Operator
• The Python plus operator + provides a convenient way to add a value
if it is a number and concatenate if it is a string.
• If a variable is already created it assigns the new value back to the
same variable.
• Can we use + for different Datatypes also?
• No, use for different types would produce an error.
• a="Lavanya“
• b=2
• print(a+b)
id function
• The id function produces a unique number identifying a specific value
(object) in memory.
• Since variables are meant to be distinct, it would appear that this
sharing of values would cause problems.
• Specifically, if the value of num changed,
would variable k change along with it?
• This cannot happen in this case because the
variables refer to integer values, and integer
values are immutable
• An immutable value is a value that cannot be
changed. Thus, both will continue to refer to
the same value until one (or both) of them is
reassigned

If no other variable references the memory location of the original value, the memo
ry location is deallocated (that is, it is made available for reuse).
2.2.2 Variables assignment
through keyboard Input
• The value that is assigned to a given variable does not have to be
specified in the program.
• The value can come from the user by use of the input function .
• input() function is used to read the input from the user.
variable=input(“prompt ”)
• Variable name is assigned to
string type
• If the user hits enter without
entering any value, name would
be assigned to the empty string
(‘ ‘)
• All input is returned by the input function as a string type.
• For the input of numeric values, the response must be converted to the
appropriate type.
• Python provides built-in type conversion functions int() and float()
• line = input('How many credits do you have?’)
num_credits =int(line)
line = input('What is your grade point average?’)
gpa =float(line)
Here, the entered number of credits, say '24', is converted to the equivalent
integer value, 24, before being assigned to variable num_credits. For input of the
gpa, the entered value, say '3.2', is converted to the equivalent floating-point
value, 3.2
• The sep separator is used between the values.
• It defaults into a space character.
• After all values are printed, end is printed. It defaults into a new line.
• Ex:
print(1,2,3,4) Output: 1 2 3 4
print(1,2,3,4,sep='*‘) Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&') Output: 1#2#3#4&
2.2.3 Identifiers
• Identifier is a user-defined name given to a variable, function,
class, module, etc.
• The identifier is a combination of character digits and an
underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and
‘NUM’ are three different identifiers in python.
• It is a good programming practice to give meaningful names to
identifiers to make the code understandable.
• Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an
underscore ( _ ).
2.2.4 Keywords
• A keyword is an identifier that has predefined meaning in a
programming language and therefore cannot be used as a “regular”
identifier. Doing so will result in a syntax error.
2.3 Operators
• An operator is a symbol that represents an operation that may be
performed on one or more operands.
• Operators that take one operand are called unary operators.
• Operators that take two operands are called binary operators.
• +,- can be used as for both unary and binary operator.
Operators
Arithmetic Operators
• Python provides two types of division:
❑ True division
❑Truncating Division
• True Division:
✓ denoted by a single slash,/
✓25/10 evaluates to 2.5
• Truncating Division:
✓Denoted by double slash,//
✓Result is based on type of operands applied to.
• When both operands are integer values, the result is a truncated integer referred
to as integer division .
• When as least one of the operands is a float type, the result is a truncated
floating point.
• 25 // 10 evaluates to 2,
• 25.0 // 10 becomes 2.0
Also called Relational Operators
• == → determines two values are equal
• = →Assignment operator

• These operators not only for numericals , we can also use for
strings.→ Follows Lexographical (Dictionary ) Ordering.
• “Alen” is less than “Brenda”→ Unicode
A→65 B→66 (65<66)
• ‘alen’ is greater than ‘Brenda’(a→97 B→66) (97>66)
• How to get Unicode encoding value for any character → ord function
Also called as Boolean Operators
Boolean Logic Truth Table
Mathematical Vs Programming
Representation
• In Mathematics range is written as: 1<= num <=10(1to10)
• Programming Languages: the above representation does not make sense.
• Let’s see how the above representation works( Assume num=15)
1<=num <=10➔1<=15<=10
=> True <= 10 (∵1<=15 evaluates to 15)
=> True <=10(Non-Sense) Wrong Representation
in programming
languages

mixed type expression error


Correct Representation in Programming
languages

• In Python, True =1 , False=0.


• 1 <= num <= 10➔True<=10➔1<=10 ➔ Result True. (Assume
num=15)
• But actual result→ False.
• Python Shell:

Correct Result
• Python automatically rewrites
Membership operators

•in and not in are the membership operators in Python.


•They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
•In a dictionary we can only test for presence of key, not the
value.
Bitwise operators
In the table below: Let x = 10 (0000 1010 in binary)
and y = 4 (0000 0100 in binary)

A simple rule to remember the bitwise NOT operation on integers is -(x+1).


Identity operators
•is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located
on the same part of the memory.

Ex:
a1 = 3
b1 = 3
a2 = 'CS2’
b2 = 'CSE’
'print(a1 is not
b1)
print(a2 is b2)
2.4 Expressions and Data types
2.4.1 Expression
• An expression is a combination of symbols that evaluates to a value.
Expressions, most commonly, consist of a combination of operators
and operands.
• 4 + (3 * k)
• An expression can also consist of a single literal or variable.
• 4, 3, and k are each expressions.
• This expression has two subexpressions, 4 and (3 * k). Subexpression
(3 * k) itself has two subexpressions, 3 and k.
• Expressions that evaluate to a numeric type are called arithmetic
expressions .
• A subexpression is any expression that is part of a larger expression.
• Subexpressions may be denoted by the use of parentheses, as shown
above.
• Thus, for the expression 4 + (3 * 2), the two operands of the addition
operator are 4 and (3 * 2), and thus the result it equal to 10.
• If the expression were instead written as (4 + 3) * 2, then it would
evaluate to 14. Since a subexpression is an expression, any
subexpression may contain subexpressions of its own.
• If no parentheses are used, then an expression is evaluated according
to the rules of operator precedence in Python.
2.4.2 Operator Precedence
• Generally while we are writing expression we are following infix
notation
• 4+3 (Operator is in between two operands)
• There are another two types
• Prefix(operator before operands +ab)
• Postfix( operator after operands ab+)
• Consider an expression using infix notation
• 4+(3*5)
It contains two operators +,*.
Result:19
If we omit parenthesis:
Two possibilities:
Operator Precedence Table

Operator Precedence of Arithmetic Operators in


Python
Examples:

Operator precedence guarantees a consistent interpretation of expressions.


However, it is good programming practice to use parentheses even when
not needed if it adds clarity and enhances readability, without overdoing it.
Thus, the previous expression would be better written as, 4 +(2 ** 5) // 10
2.4.3 Operator Associativity
• What happens when two operators have same precedence?
• Ambiguity
• Order of Evaluation does matters.
• Associativity
• To add clarity and enhance readability, better to use
parenthesis.(Good programming practice)
Short – Circuit (Lazy) Evaluation
• Short-circuiting is a programming concept in which the compiler skips the
execution or evaluation of some sub-expressions in a logical expression.
The compiler stops evaluating the further sub-expressions as soon as the
value of the expression is determined.
• For example: x or y If x is truthy, then the or operator returns x. Otherwise, it
returns y.
• In other words, if x is truthy, then the or operator doesn’t need to evaluate y. It
just returns x immediately. This is why the evaluation is called lazy or short-
circuiting evaluation.
• For logical and, if the first operand evaluates to false, then regardless of the value
of the second operand, the expression is false. Similarly, for logical or, if the first
operand evaluates to true, regardless of the value of the second operand, the
expression is true.
• For example, the expression
• if n ! =0 and 1/n < tolerance:
would evaluate without error for all values of n when short-circuit
evaluation is used.
• If programming in a language not using short-circuit evaluation,
however, a “divide by zero” error would result when n is equal to 0. In
such cases, the proper construction would be,
if n ! = 0:
if 1/n <tolerance:
• In the Python programming language, short-circuit evaluation is used.
Logically Equivalent Boolean Expressions
• In numerical algebra, there are arithmetically equivalent expressions
of different form.
• For example, x(y + z) and xy +xz are equivalent for any numerical
values x, y, and z.
• Similarly, there are logically equivalent Boolean expressions of
different form.
The last two equivalences above are referred to as De Morgan’s Laws.
2.4.4 Data Types
• A data type is a set of values, and a set of operators that may be applied to
those values.
• Built in Data types: Integers, float, strings
• Two approaches to data typing:
• 1) Static
• If a variable is declared as certain type before it is used, that
type of values only can be assigned to the variable
• 2)Dynamic:
• The data type of the variable depends upon the value that the
variable is holding.
• Thus, the same variable may be assigned values of different type during the
execution of a program.
• Since everything is an object in Python programming, data types are
actually classes and variables are instance (object) of these classes.
1.Numbers
2.Strings
3.Boolean
Numbers:
• Integers, floating point numbers and complex numbers falls under Python
numbers category.
• They are defined as int, float and complex class in Python.
• Integers can be of any length, it is only limited by the memory available.
• A floating point number is accurate up to 15 decimal places.
• Complex numbers are written in the form, x + yj, where x is the real part
and y is the imaginary part.
• We can use the type() function to know type a variable.
• Ex:
2.4.5 Mixed-Type Expression
• Automatic
• A mixed-type expression is an expression containing operands of
different type.
• Operands of mixed-type expressions therefore must be converted to
a common type.
• Values can be converted in one of two ways—by implicit (automatic)
conversion, called coercion ,
- or by explicit type conversion .
Coercion(Implicit)
• Coercion is automatically performed on mixed-type expressions only
if the operands can be safely converted, that is, if no loss of
information will result.
Explicit Type Conversion
• Explicit
• is the explicit conversion of operands to a specific type.
• Type conversion can be applied even if loss of information results.
• Python provides built-in type conversion functions int() and float()
k Yo u
Th a n

You might also like