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

UNIT II BASICS OF PYTHON PROGRAMMING

Uploaded by

swarna
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)
54 views

UNIT II BASICS OF PYTHON PROGRAMMING

Uploaded by

swarna
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/ 102

BASICS OF PYTHON

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

• Simple and Easy to learn • Embedded


• Free and Open Source • GUI Programming
Software and Database
• High level language
• Portable
• Object Oriented
• Interpreted and Interactive
• Extendable
Applications of Python
• 3D Software
• Web development
• Image processing and graphic design application
• Science and computational application
• Games
• Operating System
• Enterprise and business application
Installing Python
• Go to www.python.org
• Latest version “Python 3.11”
Python IDLE
• Integrated Development Environment
or
• Integrated Development and Learning Environment
Features of IDLE
• Multi-window text editor with syntax highlighting.
• Auto completion with smart indentation.
• Python shell to display output with syntax
highlighting.
PYTHON INTERPRETER
• Python Interpreter is a program that reads
and executes Python code. It uses 2 modes
of Execution.
1. Interactive mode
2. Script mode
1. Interactive mode
• When we type Python statement, interpreter
displays the result(s) immediately.
2. Script mode
• In script mode, we type python program in a file
and then use interpreter to execute the content of
the file.
• Save the code with filename.py and run the
interpreter in script mode to execute the script.
Execution Methods
• Interpreter: To execute a program in a high-level
language by translating it one line at a time.
• Compiler: To translate a program written in a high-
level language into a low-level language all at once,
in preparation for later execution.
Differences between
Compiler and Interpreter
Keywords

Keywords are the reserved words in Python. We


cannot use a keyword as a variable name, function
name or any other identifier.
Identifiers
• Identifier is the name given to entities like class,
functions, variables etc. in Python.
• It helps differentiating one entity from another.
Rules for identifiers
• Identifiers can be a combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore (_).
• Variable names like myClass, var_1 and
print_this_to_screen, all are valid example.
• An identifier cannot start with a digit. 1variable is
invalid, but variable1 is perfectly fine.
• Keywords cannot be used as identifiers.
Eg.
>>> global = 1 File "<interactive input>", line 1 global
= 1 ^ SyntaxError: invalid syntax
Literals
• A literal is something that the compiler recognizes
as syntax for writing an object directly.
• They are two types of literals
• Numeric literals
• String literals
Numeric literals
• A numeric literals is a literals containing only the
digits 0-9, an optional sign character(+ or -) and a
possible decimal point.
Eg: 3
Eg:12.35
String literals
• String literals or string represent a sequence of
characters
Eg: ‘Hello’
>>>print(‘Hello’)
Hello
VALUES AND TYPES
• A value is one of the basic things a program works
with like a letter or a number.
1,2 – integer
‘Hello, world!’ - string
Data types

• Integers(int) • Tuple
• Floating point numbers(float) • Dictionary
• Boolean
• None Type
• Complex type
• String
• List
Integers

• Integers are whole numbers without decimal


point
• They can be positive or negative
• Integers have unlimited in python
Eg.
a=0 upto a=99999999999999999999(both + and -)
2^-31 to 2^31
Floating point

• Floating point numbers are signified real numbers


• Float are written in decimal point
• Scientific notation ‘e’ is used represent 10th power
Eg.
2.e1=20.0
2.e2=200.0
2.e3=2000.0
a=7.0
b=23.6
Complex type
• The complex data type is an immutable type that
holds a pair of floats, one representing the real
part and the other representing the imaginary
part of complex number.
eg: 5+14j
>>>z=5+14j
Boolean
• Boolean data type is a data type, having two
values usually denoted True and False
• Truth values of logic
• The Boolean data types is the primary result of
conditional statements, which allow different
actions and change control flow.
Eg. Print(2==2)
True
Print(2==3)
False
String

• Strings in python are identified as a contiguous set


of characters represented in the quotation
marks(‘kumar’, ”mani”, ’’’logo‘’’)
• Python flows for either single quotation, double
quotation or triple quotation
• The plus(+) sign is string concatenation operator
• Asterisk(*) sign is multiple operator
Cont..

• Subsets of strings can be taken using slice operator


([],[:],[::]) with indexing started at 0 in the
beginning of the string
• Working their way from -1 at the end
Eg: >>>Str=‘windows’
>>>Print(str)
windows
>>>Str=‘hello’
>>>Print(str[0:3])
hel
>>>Print(str[4:])
o
>>>Print(str*2)
hellohello
>>> str='krishna'
>>> print(str[-1])
a
>>> print(str[1])
r
>>> print(str[1:])
rishna
>>> print(str+'hi')
krishnahi
>>> str = "Python Programming"
>>> print(str[2 : 10 : 2])
to r
>>> print(str[-10:-1])
rogrammin
>>> print(str[-1:-10])

>>> 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

• Some characters can be included using ( \ )


backslash before them.
Multiple Assignment
• Python used to assign a single value to more than
one variables simultaneously.
• E.g

• Python also allows to assign multiple values to


multiple variable simultaneously.
• E.g.
Multiple statements on a Single Line
• There are two types of in a program code.
• 1. The physical line is what we see while writing a
program.
• 2. The logical line is what python see in a single
statement separated by semicolon (;)
• E.g.
Lists
• Lists are the most versatile of python’s
compound data types
• A list contains items separated by commas and
enclosed within square brackets([])
• Lists are mutable
Eg: list=[‘psp’,’python’,1]
>>>Print(list[0])
psp
Cont..

>>> 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.

• type() is used check datatype of a variable.


E.G >>> type(name)
<class 'str'>
• # - used for single line comment.
Indentation
• Whitespace at the beginning of the line is called
indentation.
• Use a single tab for each indentation level.
Operators
Operators
• Python divides the operators in the following
groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Unary operators
8. Bitwise operators
1. Arithmetic operators
• Arithmetic operators are used with
numeric values to perform common
mathematical operations:
2. Assignment operators
• Assignment operators are used to assign
values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
3. Comparison operators
• Comparison operators are used to
compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or x >= y
equal to
<= Less than or equal to x <= y
4. Logical operators
• Logical operators are used to combine
conditional statements:
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of x < 5 or x < 4
the statements is true
not Reverse the result, not(x < 5 and x < 10)
returns False if the
result is true
5. Identity operators
• Identity operators are used to compare the
objects, not if they are equal, but if they are
actually the same object, with the same
memory location:

Operator Description Example


is Returns True if both x is y
variables are the
same object
is not Returns True if both x is not y
variables are not the
same object
6. Membership operators
• Membership operators are used to test if
a sequence is presented in an object:

Operator Description Example


in Returns True if a x in y
sequence with the
specified value is
present in the object
not in Returns True if a x not in y
sequence with the
specified value is not
present in the object
7. Unary operators
• Unary operators act on single operands.
• Python supports unary minus operator, it is
strikingly different from the arithmetic operator
that operates on single operands and also subtracts
the second operand from the first operand.
8. Bitwise operators
• As the name suggests, bitwise operators perform
operations at the bit level.
• These operators include bitwise AND, bitwise OR,
bitwise XOR, and not operators.
• Bitwise operators expect their operands to be of
integers and treat them as a sequence of bits.
Bitwise AND (&) Bitwise inclusive OR ( |)

0&0=0 0|0=0
0&1=0 0|1=1
1&0=0 1 |0=1
1&1=1 1|1=1

Bitwise exclusive OR (^) Bitwise 1's complement (~)

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.

• We can use parentheses (), [], {} to write a multi-


line statement. This is known as an Implicit
continuation.
3. Compound Statements
• Compound statements contain (groups of)
other statements;
• The compound statement includes the conditional and
loop statement.
1. if statement: Also known as a conditional statement.
2. while statements: Also known as a looping statement.
3. for statement: Using for loop statement, we can iterate
any sequence or iterable variable. Also known as a
looping statement.
4. try statement: specifies exception handlers.
4. Simple Statements
4. 1. Expression statements – x + 20
4. 2. The pass statement
• The pass statement is used as a placeholder for
future code.
• Nothing happens when the pass statement is
executed, but you avoid getting an error when
empty code is not allowed.
4.3 The del statement
The Python del statement is used to delete
objects/variables.

4.4 The return statement


Using a return statement, we can return a value from
a function when called.
4.5 import statement
The import statement is used to import modules. We
can also import individual classes from a module.
4.6 The continue and break statement
• break Statement: The break statement is used
inside the loop to exit out of the loop.
• continue Statement: The continue statement skip
the current iteration and move to the next
iteration.
Multiple
assignments
Multiple Assignment
• Python used to assign a single value to more than
one variables simultaneously.
• E.g

• Python also allows to assign multiple values to


multiple variable simultaneously.
• E.g.
Multiple Assignment from
user
• split():
• The split() method splits a string
into a list.
• Syntax
string.split(separator, maxsplit)
Multiple Assignment from
user
• map():
• map() function returns a map object
(which is an iterator) of the
results after applying the given
function to each item of a given
iterable (list, tuple etc.)
• Syntax :
map(fun, iter)
Formatting
numbers and
strings
Built-in format()
• The format() function produces a numeric string of
a floating point value rounded to a specific number
of decimal places.
Format()
• The format() method returns a formatted
representation of the given value controlled by the
format specifier.
• It's syntax is:
format(value[, format_spec])
• value - value that needs to be formatted
• format_spec - The specification on how
the value should be formatted.
[[fill]align][sign][#][0][width][,][.precision][type]

where, the options are


fill ::= any character
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g"
| "G" | "n" | "o" | "s" | "x" | "X" | "%"
Formatting numbers()
Number Formatting Types
Type Meaning
d Decimal integer
Corresponding Unicode
c character
b Binary format
o Octal format
Hexadecimal format (lower
x case)
Hexadecimal format (upper
X case)
# ex-01 number formatting

# 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 parameters - list of parameters that can


be accessed with index of parameter inside curly
braces {index}
• Keyword parameters - list of parameters of type
key=value, that can be accessed with key of
parameter inside curly braces {key}
• For positional arguments
• For keyword arguments
# default arguments
print("Hello {}, your balance is {} ".format("Adam",
230.2346))

# 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 value is : {:.2f}".format(40))

print('a: {a}, b: {b}, c: {c}'.format(a = 1,


b = 'Two',
c = 12.3))

print("The value {:^10} is positive value".format(40))

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:”, ????)

You might also like