UNIT II BASICS OF PYTHON PROGRAMMING
UNIT II BASICS OF PYTHON PROGRAMMING
PROGRAMMING
UNIT II
Introduction-Python Interpreter-Interactive and
script mode -Values and types, variables, operators,
expressions, statements, precedence of operators,
Multiple assignments, comments, input function,
print function, Formatting numbers and strings,
implicit/explicit type conversion.
Introduction
Introduction
• Python is a general-purpose interpreted,
interactive, object-oriented, and high-level
programming language.
• It was created by Guido van Rossum during 1985-
1990.
• Python got its name from “Monty Python’s flying
circus”. Python was released in the year 1991.
Features of Python
• Integers(int) • Tuple
• Floating point numbers(float) • Dictionary
• Boolean
• None Type
• Complex type
• String
• List
Integers
>>> print(str[::-1])
gnimmargorP nohtyP
>>> print(str[18:20])
Arithmetic OverFlow:
• OverflowError occurs when any operations like
arithmetic operations or any other variable storing
any value above its limit then there occurs an
overflow of values that will exceed it’s specified or
already defined limit.
Arithmetic UnderFlow
• Underflow occurs while doing division of two
floating numbers, when a calculated result is too
small in magnitude to be represented.
Loss of Precision Problem:
• When you divide 1/3, the result is .33333333.....
where 3 is repeated infinitely. Python will limit the
range to an approximation value
Quotient and Remainder
• When dividing two numbers, if you want to know
the quotient and remainder, use the floor
division(//) and modulo operator(%) respectively.
Exponent
• The ** operator is used for Exponent. ie., Raising of
one number to the power of another.
Built-in format()
• The format() function produces a numeric string of
a floating point value rounded to a specific number
of decimal places.
Implicit Conversion
• Indirect conversion method. E.g. Int to float.
Explicit Conversion
• Direct conversion method. E.g. Float to int
Escape Sequence
>>> Print(list[1:3])
[python,1]
>>> print([2:])
[1]
>>> alist=[‘kite’]
>>> Print(list+alist)
[‘psp’,’python’,1,’kite’]
Tuple
• Tuple contains items separated by commas
and enclosed with parenthesis().
• Values cannot be edit or update or insert a
new value in Tuple.
• The values in tuples can be stored of any
type.
• Tuples are immutable.
• As tuples are immutable, they are faster
than the list because they are static.
>>>tuple=(10,20,30,’dhoni’,’K’,)
>>>print(tuple)
(10,20,30,’dhoni’,’K’,)
Dictionaries
• Dictionaries are used to store data values in
key:value pairs.
• A dictionary is a collection which is ordered,
changeable and do not allow duplicates.
None type
• None is a special data type.
• Basically not known or empty
• Eg:
>>> x=None
>>>x
Print(x)
None
Input function
• The input() prompts the user to provide some
information on which the program can work and give
the result.
• All the user input are consider as string.
0&0=0 0|0=0
0&1=0 0|1=1
1&0=0 1 |0=1
1&1=1 1|1=1
0^0=0 ~0 = 1
0^1=1 ~1 = 0
1^0=1
1^1=0
Expressions
Expressions
• An expression is a combination of
operators and operands that is
interpreted to produce some other value.
• So that if there is more than one operator
in an expression, then precedence
decides which operation will be
performed first.
1. Constant Expressions
2. Arithmetic Expressions - +, - ,
*, /, //, ….
3. Integral Expressions
4. Floating Expressions
5. Relational Expressions - > , < , >= ,
<=
6. Logical Expressions – and, or, not
7. Bitwise Expressions
8. Combinational Expressions
E.G
a = 16
b = 12
c = a + (b > 1)
print(c)
????
Operator Precedence
Precedence Name Operator
1 Parenthesis ()[]{}
2 Exponentiation **
Unary plus or minus,
3 -a , +a , ~a
complement
Multiply, Divide,
4 / * // %
Modulo
Addition &
5 + –
Subtraction
6 Shift Operators >> <<
7 Bitwise AND &
Operator Precedence
Precedence Name Operator
8 Bitwise XOR ^
9 Bitwise OR |
Comparison
10 >= <= > <
Operators
11 Equality Operators == !=
Assignment
12 = += -= /= *=
Operators
Identity and
13 membership is, is not, in, not in
operators
14 Logical Operators and, or, not
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d);
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Statements
Statements
• A statement is an instruction that a Python
interpreter can execute. So, in simple words, we
can say anything written in Python is a
statement.
• Types:
1. Multiple statement
We can add multiple statements on a
single line separated by semicolons, as
follows:
2. Multi-Line Statements
• Python statement ends with the token NEWLINE
character.
• But we can extend the statement over multiple
lines using line continuation character (\). This is
known as an explicit continuation.
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
‘’’ex-02 Number formatting with padding for int and
floats’’’
print("{:5d}".format(12))
print("{:2,d}".format(1234))
print("{:8.3f}".format(12.2346))
print("{:05d}".format(12))
print("{:-5d}".format(12))
Number formatting with alignment
Type Meaning
Left aligned to the
< remaining space
Center aligned to the
^ remaining space
Right aligned to the
> remaining space
Forces the signed (+) (-) to
= the leftmost position
‘’’ex-03 Number formatting with alignment’’’
print("{:^10.3f}".format(12.2346))
print("{:<05d}".format(12))
print("{:=8.3f}".format(-12.2346))
‘’’homework: Number formatting with fill, align, sign,
width, precision and type’’’
# integer
print(format(1234, "*>+10,d"))
# float number
print(format(123.4567, "^-09.3f"))
String format() Parameters
• format() method takes any number of parameters.
But, is divided into two types of parameters:
# positional arguments
print("Hello {0}, your balance is {1} ".format("Adam",
230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc} “ .format
(name="Adam", blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc} “ .format("Adam",
blc=230.2346))
# homework
print('{2} {1} {0}'.format('directions',
'the', 'Read'))
print('The first {p} was alright, but the {p} {p} was
tough.'.format(p = 'second'))
Implicit/explicit
type conversion
Implicit type conversion
• In Python, when the data type conversion takes place
during compilation or during the run time, then it’s
called an implicit data type conversion.
• E.g
a=5
b = 5.5
sum = a + b
print (sum)
print (type (sum))
10.5
<class 'float'>
Explicit type conversion
• Explicit type conversion is also known as
typecasting. Explicit type conversion takes place
when the programmer clearly and explicitly defines
the same in the program.
• Syntax:
Datatype (parameter)
Explicit type conversion
Inbuilt functions Description
Int(y) It converts y to an integer
Float(y) It converts y to a floating-point number.
Str(y) It converts y to a string.
Tuple(y) It converts y to a tuple.
List(y) It converts y to a list.
Dict(y) It creates a dictionary and y should be a
sequence of (key, value) tuples.
Complex(y, z) It creates a complex number.
• E.g
# adding string and integer data types using explicit
type conversion
a = 100
b = “200”
result1 = a + b
print(“The sum is:”, result1)
print(“The complex is:”, ????)