Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Programming with Python

Lecture 4: Data & Expressions


Instructor: John Eric Steephen
Today’s lecture

Topics
– Literals
– Expressions and data types
– Number formatting
– Variables and identifiers
– Keywords
– Operators
– Type conversion

Pre-requisites
– Sessions 2, 3
Running Python – Interactive mode
• Shell mode
• Commands are processed one line at a time
– In IDLE, Run → Python Shell
– Type print("Hello World!") into the Python shell & press <Enter>




• print("Hello World!") → Calls ‘print()’ module with argument “Hello


World!”
– ‘print()’ is a built-in module
• Prints, i.e., outputs the value of the passed parameter to the screen
• Python already contains the code for it
– Python contains many such built-in modules
• In Python, a module is referred to as a function
Running Python – Non-interactive mode
• Script mode
• Commands are in a file & are processed together
– Type into the IDLE window: print("Hello World!")
– Save the file with a .py extension (e.g. Test.py)
– In IDLE, Run → Run Module






– In Python, a module is used to refer to a file containing Python code
• Usually given the extension .py
• Test.py is a Python module
• We choose Run Module in IDLE to execute the code contained in a
Python file
Literals

Piece of code that exactly represents a value

String literal or string (str)
– A character sequence enclosed in single/double/3 single/3 double
quotes
• e.g. 'Hello', "Hello World", '''Hi World''', """K"""
– Characters include letters, digits, special characters, blanks
• e.g. "007", 'MH01-AB2388', '''78''', '6', 'some1@somewhere.in', " "
– A string with 0 characters is an empty string
• '', "", '''''', """"""
– Strings can contain quote characters as long as it is enclosed using a
different quote character
• "Ajay is Rupa's friend", 'Type "Hello" now'
• 'Type 'Hello' now' → error
– If enclosed in 3 quotes (single/double), the string can span multiple
lines
print('''Hello World!
How are you?''')
Literals

Numeric literal
– A number containing
• Only the digits 0-9
• Optional sign character (+ or -)
• A possible decimal point
– If there is no decimal point, it denotes an integer (int) value
• e.g. 5, 2500, +768, -23
– If there is a decimal point, it denotes a floating-point (float) value
• e.g. 7.23, +8.2, -0.003, 12.0, 6.
Literals

Control characters
– Special characters not displayed on screen
– Used to control display of output
– Do not have a corresponding keyboard character
– Denoted by escape sequences
• A string starting with the escape character ‘\’
• The characters following ‘\’ escapes their normal meaning
– Examples
• '\n' represents the newline control character used to begin a new line
• The print function ends the output with a newline by default

print('Hello')

print('World!')

• To introduce a newline within an argument of print()


print('Hello\nWorld!')
Data type

A set of values & a set of operators that may be applied to
those values
– e.g. Integer data type consists of the set of integers & the operators for
addition, multiplication etc.

Built-in types
– Pre-defined data types in Python
• e.g. Integer, float, string

Same internal representation of data can be interpreted in
different ways depending on data type
– The bit string 01000001 represents the number 65 if it is considered as
an integer or as the letter ‘A’ if considered as a string

Static typing
– Variable’s data type declared before it is used
• Can only be assigned values of that type
Data type

Dynamic typing
– Variable’s data type depends only on the data type of value it is
currently holding
– Same variable may be assigned values of different types during
program execution
– Python uses dynamic typing

The type() built-in function
– Returns the data type of its argument
• type(5.0) returns <class 'float'>
• type('Hello') returns <class 'str'>
The print() function

Each call prints the output in a new line
print('Hello')
print('World!')


To avoid printing ‘World’ in a new line & to put a space
between the words
print("Hello", end=" ")
print("World!")
– end is an optional parameter that specifies what Python should do at
the end of a print statement

Permits an arbitrary no. of arguments
– Each argument can be of any data type
• e.g. one argument can be string while another can be float
– A single space is automatically put between arguments
• print('I', 'am', 9, 'years', 'old') → I am 9 years old
– If we need another character in place of space
• print('I', 'am', 'fine', sep = '-') → I-am-fine
• print('I', 'am', 'fine', sep = '') → Iamfine
Number formatting

Float values have arbitrary number of decimal places
– e.g. 1.1, 3.0000000005, 6.785767299

The built-in format() function
– Has the form
• format(value, format_specifier)
• format_specifier can contain a combination of formatting options
– Returns a numeric string version of the value containing a specified no.
of decimal places
• Actual value is unaffected
• format(3.0000000005, '.0f') → '3'
• format(6.785767299, '.3f') → '6.786'
• format(9**99, '.4e') → '2.9513e+94'
• format(9**-9, '.2e') → '2.58e-09'
• format(13402, ',.1f') → '13,402.0'
– Usage
• x = format(1.1, '.2f')
• print(x)
Obtaining input

The built-in input() function
– Takes a string argument
• The string is used as a prompt
– On calling the function,
• The prompt is printed
• Waits for input from user
– The user enters the input and presses <Enter>
• The function returns user input as a string

name = input("Enter your name: ")


print(name)
Identifier

Identifier just means name

A character sequence used to provide a name for a given
program element
• e.g. Variable names, function names

Identifier is case sensitive
• e.g. Num & num are different identifiers

Identifiers can contain letters, digits and ‘_’,
• e.g. Train18, First_Name

Identifiers cannot begin with a digit
• e.g. 12thWeek → Error

Identifiers should not begin with ‘_’
– Used by Python for some internal identifiers
• e.g. _Name → Not recommended

Identifiers should not have spaces or quotes
• e.g. Last Name, ‘totalSales’ → Error
Identifier

The identifier ‘_’
– In the shell, equal to value of most recently evaluated expression
– Type into the shell the following:
• >>> 4 + 5
• >>> _ + 1
– What do you see?

Variable
– A name (identifier) associated with a value
• Can be assigned different values during program execution
• Can be used in place of its value

Named constant
– A variable whose value is a constant
– Common practice to use only upper case letters
• PI = 3.14
• MINS_PER_HOUR = 60
Identifier

Keyword
– An identifier that has a predefined meaning
• e.g. and, del, global, not, with, as, elif, if, or, yield, assert, else
– Cannot be used as an identifier by the programmer

Other predefined identifiers
• e.g. float, int, print, exit, quit
– Should not be used as an identifier by the programmer
• print = 7
• print(‘Hi’)
Operations

Operator
– A symbol that represents an operation
• e.g. +, -

Operand
– A value that a given operator is applied to
• In 3 + 2, 3 and 2 are the operands
• in x – y, x and y are the operands
– A function that returns a value can also be an operand
• The function is called & its return value is used
• In int(‘31’) + 4, return value of int(‘31’) and 4 are the operands

Unary operator
– Operator that takes one operand
• e.g. negation operator, -12

Binary operator
– Operators that take two operands
• e.g. 3 - 2
Assignment operator

Assignment operator (=)
– Used for name binding
• In algorithm, varA ← 5
• In Python, varA = 5
– First, the right side of an assignment is Loc 1 10 x
evaluated Loc 2
– Then the result is assigned to the variable
on the left
Loc 1 10
• varA = 2 + 7
• varB = ‘DUK’ Loc 2 34.78 x
– What happens in memory
• x = 10 Loc 1 10
• x = 34.78
Loc 2 34.78 x
• k=x k
• k = "Hello"
Loc 1 Hello k

Loc 2 34.78 x
Assignment operator
– Cascaded assignment
• y=x=8
– Simultaneous assignment
• x, y = 5, 7 + 4
– Augmented assignment
• x += 1 → x=x+1
• x /= 2 + 5 → x = x / (2 + 5)
• x //= 7 → x = x // 7
• x **= 2 → x = x ** 2

Variable swapping
• tmp = x
• x=y
• y = tmp
– Alternatively
• x, y = y, x
Arithmetic operators

Addition (+), subtraction (–), multiplication (*)
• 7 + 2.0
• 9–3
• 4.5 * 0.5

Negation (–)
• e.g. –10, –22, –5

Exponentiation (**)
• e.g. 10 ** 2 is 100

Division, True division or Float division (/)
– The result of a division is always a float
• 7.9 / 2
• 7 / 34.23
• 4.3 / 8.8
• 8/4
Arithmetic operators

Truncating division or Floor division (//)
– Result is the greatest integer ≤ quotient
– If the operands are integers, result is an integer quotient
– If even 1 operand is a float, result is a float holding an integer value
• 25 // 10 is 2
• 25.0 //10 is 2.0
• 10.5 // 5.0 is 2
• 11 // 2.5 is 4.0

Modulus, Modulo or Remainder (%)
• 25 % 10 is 5
• 10.5 % 5 is 0.5
• 11 % 2.5 is 1.0

The divmod(x, y) built-in function
– Returns the results of both floor division and modulo
• Hours = 130 // 60
• Minutes = 130 % 60
• Hours, Minutes = divmod(130, 60)
Expressions

Combination of operators & operands that evaluate to a value
• e.g. 4 * (3 + k), 3 + k, 4, k
– When entered in shell mode, its value is displayed
• e.g. if 7 + 2 is entered into Python shell, it displays 9

Arithmetic expression
– An expression that evaluates to a number

Mixed-type expression
– An expression having operands of different data types
• e.g. 2 + 4.5
– A binary operator can perform its operation only if its operands are of
the same data type
• If they are not, they need to be first converted into the same type
– The operands can be converted in 2 ways
• Implicit or automatic type conversion (coercion)
• Explicit type conversion
Coercion

Performed automatically by Python
– Only if the conversion is safe
• A conversion is safe when there is no information loss
– Integer to float conversion is always safe
• e.g. 2 → 2.0
– Float to integer conversion is not always safe
• 3.0 → 3 (Safe)
• 4.5 → 4 (Unsafe)
– If one operand is a float, the other operand is converted to float
• The result is a float
• 2 + 4.5 → 2.0 + 4.5 → 6.5
Explicit type conversion

Performed by the programmer
– Done using built-in type conversion functions
• e.g. int(), float(), str(), bool()
– Can be done even if it is unsafe
• float(2) + 4.4 → 6.4 (safe)
• 2 + int(4.4) → 6 (unsafe)
– int() extracts the integer part of its argument
• Doesn’t round off to the nearest integer
• int(4.9) → 4, not 5
– Numeric strings can be converted to numeric type
• "10" → int("10") → 10
• "10" → float('10') → 10.0
• "10.8" → int('10.8') → Error
• "10.8" → float('10.8') → 10.8 → int(10.8) → 10
• "Hello" → float("Hello") → Error
– Numeric type can be converted to numeric strings
• str(-4.5) → '-4.5'
• str(1 + 10 + 100) → '111'
Explicit type conversion

The eval() built-in function
– Takes a string as argument
– Evaluates it like a Python expression
– Returns the result of the expression
• eval('7 + 3') → 10
• height = 5.6
• ht = eval(height)
• print(ht) → '5.6'
• Age = input("Enter your age: ")
• age = eval(Age)
• x, y = eval("10, 20 + 12") → x, y = 10, 20 + 12 → x is 10, y is 32
• Ip = input("Enter name and age (separated by comma): ")
• x, y = eval(Ip)
Statements

A single complete command
• e.g. print(‘Hi’)

Usually a statement is completely contained in a line

A statement can span multiple lines if we put ‘\’ at the end of
the line or by using parenthesis
X = •3 + \ is same as X = (3 + is same as X=3+4
4 4)


To have multiple statements on a single line
– Separate them with ‘;’
• print("Hello World!"); print('Hi World!')

You might also like