0% found this document useful (0 votes)
5 views89 pages

Chap 1

The document provides an overview of programming languages, focusing on Python as a general-purpose language. It discusses Python's features, advantages, limitations, and its various data types, as well as identifiers, keywords, and type casting. Additionally, it compares Python with Java and outlines the installation process and different versions of Python.

Uploaded by

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

Chap 1

The document provides an overview of programming languages, focusing on Python as a general-purpose language. It discusses Python's features, advantages, limitations, and its various data types, as well as identifiers, keywords, and type casting. Additionally, it compares Python with Java and outlines the installation process and different versions of Python.

Uploaded by

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

Anand Komiripalem

What is a Programming Language

A programming language is a set of commands, instructions,


and other syntax used to create a software program.

Examples of Programming Languages: C, C++, Java, Python etc.


Anand Komiripalem

Python

Python is a widely used general-purpose, high level


programming language.

It was initially designed by Guido van Rossum in


1991(While working with national Research
Institute - Netherlands) and developed by
Python Software Foundation
Anand Komiripalem

There are two types of application Languages


1. General Purpose Application Language
2. Purpose based Application Language

Purpose based application Language: Language used for the development


of specific Applications
Ex:
pascal: used developing scientific applications
Fortan: used for evaluating complicated mathematic equations
Cobol: Used for developing business applications

General Purpose Application Language: Language used to develop any type


of applications
Ex: C, C++, Java, Python….
Anand Komiripalem

Why Python?
◊ Simple and Easy to Learn:
◊ Python is easy to learn, easy to write. It will be like reading or
writing normal English terms
◊ We don’t require any pre-requisite to learn python
◊ Free to use
◊ Python is a Free Open source language, directly we can
download from internet, install it on the system and start
working
◊ High Level Programming language
◊ Platform Independent (Write once and Run Anywhere)
Anand Komiripalem

◊Interpreted language
◊ We don’t need to compile the program, python will directly
compile at the time of execution
◊Dynamically Typed Programming Language
◊ we don’t need to declare any variable in advance in
python, python will automatically assign the type based on
values we provide
◊Supports Web Development
◊ Python supports a variety of ready made frameworks for
developing websites.
Ex: Django, Flax, Pylons, Webwpy
◊ both Object Oriented and Procedure Oriented
programming languages
Anand Komiripalem

◊ Extensive Libraries support

◊ Fastest growing language in the world

◊ Portable language
◊ Most platforms like Windows, Mac etc.. Supports python

◊ Large community support

◊ Python Supports AI(Artificial Intelligence), Data Science,


Machine Learning, Computer Graphics etc..

◊ Python can be used in Test Automation


Anand Komiripalem

Companies Working with Python


Anand Komiripalem

Limitations of Python
◊ Speed of python is slow as compared to C/C++ or Java
◊ Python is strong in desktop and server platforms, that is it is an
excellent server-side language but for the mobile development,
Python is not a very good language which means it is a weak
language for mobile development.
◊ comparison to the popular technologies like JDBC and ODBC(open
database connectivity), it is found that the Python’s database
access layer is bit underdeveloped and primitive
Anand Komiripalem

Versions of python

Version Year

1.0 Jan 1994

2.0 Oct 2000

3.0 Dec 2008


Anand Komiripalem

Flavors of Python
◊ Cpython: Standrd Python
◊ Jython or Jpython: for implementation of the Python
programming language which is designed to run on the Java
Platform.
◊ Iron Python: implementation of the Python targeting the .NET
Framework. It is entirely written in C# and runs on .NET virtual
machine
◊ PyPy: its primary focus is to overcome drawbacks of python.
◊ Ruby Python: embeds a running Python interpreter in the Ruby
applications.
◊ Anaconda Python: it is distribution for large-scale data
processing, predictive analytics, and scientific computing.
◊ Stackless Python: is a reimplementation of traditional python and
its key point is lightweight threading.
Key Differences Between Java vs Python
Java Python
Code Longer lines of code Less lies of code

Syntax Comparatively Complex Simple Syntax


syntax
Data Type Declaration Statistically Typed Dynamically Typed

Speed Fast Comparatively low


speed
Portability Supports Also Supports

DB Connectivity Fast(most popular) Weaker than Java

Easy to use Difficult Very easy

Mostly used in web Mostly used for


applications and Machine Learning, AI
mobile apps and Data Science
How to install Python
◊ Open a browser window and navigate to the Download page for
Windows at python.org.

◊ Underneath the heading at the top that says Python Releases


for Windows, click on the link for the Latest Python 3 Release -
Python 3.x.x. (As of this writing, the latest is Python 3.6.5.)

◊ Scroll to the bottom and select either Windows x86-64


executable installer for 64-bit or Windows x86 executable
installer for 32-bit.
Anand Komiripalem

Identifiers

◊ Python Identifiers are user-defined names to represent a variable,


function, class, module or any other object.

◊ If you assign some name to a programming entity it is technically


called an identifier.
Anand Komiripalem

Rules for Defining Identifiers


◊ We can use Alphabets(both lower case & Upper case ), Digits (0-9),
underscore( _ ) only
◊ Identifiers Cannot start with digits
◊ t1 = 10 -------------- Valid
◊ 1t = 10 -------------- Invalid

◊ Identifiers are case sensitive


◊ a = 10
◊ A = 10
Both are different

◊ Keywords cannot be used as identifiers


◊ There is no limit for the length of identifiers
◊ If an identifier starts with underscore(_a), it is considered as
protected
◊ If an identifier starts with double underscore(__a), it is considered as
strongly private
◊ __a__, considered as language specific identifier
Anand Komiripalem

◊ Which of the following are valid Python identifiers?

1) 123total X
2) total123 √
3) java2share √
4) ca$h X
5) _abc_abc_ √
6) def X
7) If X
Anand Komiripalem

Keywords
◊ Keywords in Python are reserved words that cannot be used as
ordinary identifiers.

◊ Python has 35 reserved words

◊ True, False, None


◊ and, or, not, is
◊ while, for, break, continue, return, in, yield
◊ try, except, finally, raise, assert
◊ Import, from, as, class, def, pass, global, nonlocal, lambda, del, with,
async,await
Anand Komiripalem

Keywords
Note:
◊ All reserved words contains only alphabets
◊ Except “True, False, None” all the keywords contain only lower case
alphabets.

◊ To get keywords list in python:

>>> import keyword


>>> keyword.kwlist
Anand Komiripalem

Indentation
◊ Most of the programming languages like C, C++, Java use braces { }
to define a block of code. Python uses indentation.

for i in range(1,11):
print(i)
if i == 5:
break
Anand Komiripalem

Comments in python
◊ Comments can be used to explain Python code.

◊ Single line comments:


# this is a single line comment
◊ Multi line comments:
“”” this is a Multiline
comment”””
Anand Komiripalem

Data Types
◊ Data type represents the type of data present inside a variable
◊ In python we are not required to specify the type explicitly. Based on
value provided, the type will be assigned automatically. Hence
Python is dynamically Typed Language

Data types available in python:

Int Float Complex


Bool Str Bytes
Bytearray Range List
Tuple Set Frozenset
Dict None
Anand Komiripalem

Data Types
◊ Python has several inbuilt functions

type(): To check the type of the variable


id(): To get the address of the variable
print(): To print the variable
Anand Komiripalem

Int Data Type


◊ int data type to used represent numbers (integral values)
◊ Integers can be of any length, it is only limited by the memory
available.
Eg: a = 10
type(a) #int
◊ We can represent int values in the following ways
◊ Decimal Form
◊ Binary form
◊ Octal form
◊ Hexa Decimal Form
Anand Komiripalem

Int Data Type


Decimal Form:
◊ Default number system in python
◊ The allowed digits are 0 -9
Eg: a = 10
type(a) #int

Binary Form: (base-2)


◊ Values should be prefixed with 0b or 0B
◊ The only allowed digits are 0 -1
Eg: a = 0B111
b = 0b101
Anand Komiripalem

Int Data Type


Octal Form: (base – 8)
◊ Values should be prefixed with 0o or 0O
◊ The only allowed digits are 0 -7
Eg: a = 0o156 #110
b = 0o181 #error

Hexa Decimal Form: (base-16)


◊ Values should be prefixed with 0x or 0X
◊ The only allowed digits are (0 -9, a-f)
Eg: a = 0xFACE #64206
b = 0xBeer #Error
Anand Komiripalem

Int Data Type


Note: we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal
form

a=10
b=0o10
c=0X10
d=0B10
print(a) #10
print(b) #8
print(c) #16
print(d) #2
Anand Komiripalem

Base Conversions
◊ We can convert values from one base to another.
◊ We have in-built functions to do the base conversions.
◊ bin() : converts values from any base to binary
x=20
bin(x) #0b10100

◊ oct() : converts values from any base to octal


oct(0xface) #0o175316

◊ hex() : converts values from any base to octal


hex(0o146) #0x66
Anand Komiripalem

Float Data Type


◊ Float data type is used to represent floating point values(Decimal
Numbers)
Eg: a = 12.768
type(a) #float
◊ We can represent float values in exponential form also
Eg: a = 1.7e3 #1700.0

◊ The advantage of using exponential form is that we can represent


big values in less memory

Note: We can represent int values in decimal, binary, octal and hexa
decimal forms. But we can represent float values only by using
decimal form.
Anand Komiripalem

Complex Data Type


◊ Complex number is of the form:

a, b can have either integer values or float values

Eg: a = 3+5j
b = 5+12.3j
c = 1.2+3.4j

we can specify real part either by decimal, octal, binary or hexa decimal form but
imaginary part should be in decimal format only
Anand Komiripalem

Complex Data Type


◊ We can perform operations on complex type values.

>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c) # (30+4j)
>>> type(c) # <class 'complex'>

Note: Complex data type has some inbuilt attributes to retrieve the real
part and imaginary part
Anand Komiripalem

Complex Data Type


◊ We can perform operations on complex type values.
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c) # (30+4j)
>>> type(c) # <class 'complex'>

Note: Complex data type has some inbuilt attributes to retrieve the real
part and imaginary part

c = 10.5+3.6j
c.real  10.5
c.imag  3.6
Anand Komiripalem

bool Data Type


◊ We can use this data type to represent boolean values
◊ The only allowed values are: True and False
◊ True means 1 and False means 0
Eg:
a = 10
b = 20
c = a<b
print(c) True
Anand Komiripalem

str Data Type


◊ str represents string data type
◊ String is any sequence of characters enclosed in single/double
characters
Eg:
a = ‘anand’
b = “anand”

◊ We can represent string in multiple line by using triple quotes

Eg:
a = ‘’’anand
komiripalem’’’
b = “”“anand
komiripalem”””
Anand Komiripalem

str Data Type


◊ Triple quotes are used for using single quote or double quotes in a
string
Eg:
a = ‘’’Hai, how “are you’’’
b = “””hello I’m fine”””

◊ We can retrieve the part of the string using indexing which is


specifically called as slicing.
◊ Slice means piece, used for retrieving a part of string sequence.
◊ In python string follows zero based index
◊ Python supports both +ve index and –ve index, +ve index starts 0
index (left to right) and –ve starts with -1 index(right to left)
Anand Komiripalem

str Data Type


Eg:
a = ‘Hai, how are you’
a[5] #h a[:] # ’Hai, how are you’
a[2:7] # ’i, ho” a[1:40] # ‘ai, how are you’
a[40] # error a[::2] # ‘Hi o r o’

◊ We can do operations on string


a = ‘anand’
a+a #anandanand
a*3 # ’anandanandanand
a*a # error
◊ We can get the length of the string by using len() function
a = ‘anand’
len(a) #5
Anand Komiripalem

str Data Type


◊ In python we can represent char values also by using str data type
only. Char data type is not available in python.
Eg:
c = “a”
type(c) # <class ‘str’>

◊ Fundamental data types in python


◊ Int
◊ Float
◊ Complex
◊ Bool
◊ Str
Anand Komiripalem

Type Casting
◊ We can convert one data type value to another, this process of
conversion is called as type casting/ type coersion.
◊ We have inbuilt functions for performing type casting
◊ int()
◊ float()
◊ complex()
◊ bool()
◊ str()
Int():

◊ We can convert values from other data types to int except complex
type
◊ If we want to convert str type to int, then str should contain only
integer values (of base 10)
Anand Komiripalem

Type Casting
Eg:
int(123.45) #123 int(12+34j) # Error
int(True) #1 int(False) #0
int(“10”) #10 int(“12.34”) #error

float():
◊ We can convert values from other data types to float except complex
type
◊ If we want to convert str type to float, then str should contain only
integer of floating values (of base 10)
Eg:
float(123) #123.0 float(12+34j) # Error
float(True) #1.0 float(False) #0.0
float(“10”) #10.0 float(“12.34”) #12.34
Anand Komiripalem

Type Casting
complex():
◊ We can convert values from other data types into complex type
◊ Form-1: (complex(x))
Eg:
complex(13) #13+0j complex (12.34) # 12.34+0j
complex(True) #1+0j complex (False) #0j
complex(“10”) #10+0j complex(“12.34”) #12.34+0j

◊ Form-2: (complex(x,y))
Eg:
complex(5,-3) #5-3j complex(True, False) #1+0j
Anand Komiripalem

Type Casting
bool():
◊ We can convert values from other data types into bool type
Anand Komiripalem

Type Casting
str():
◊ We can convert values from other data types into str type

Eg:
str(“13”) # ’13’ str (“12.34”) # ‘12.34’
str(“True”) # ’True’ str(‘1+5j’) #1+5j
Anand Komiripalem

Fundamental Data types Vs Immutability


◊ In python if a new object is required, first PVM will check if there is
any existing object with same content, if it finds any existing object
then that object will be reused. If it can't find any object then it will
create a new object.
◊ The advantage of this approach is memory utilization will be less and
performance will be improved
◊ But the problem with this approach is if multiple references are
pointing to same object an if we try to change the content of on
reference, it will effect the remaining references. To prevent this we
use the concept of immutability.
◊ Immutability means once we create an object, we cannot perform
any changes to the object, if we try to do some changes then with
those changes a new object will be created without effecting the
remaining references.
Anand Komiripalem

Fundamental Data types Vs Immutability


◊ All fundamental data types are immutable except float and complex
data types because for float and complex every time a new object
will be created. But still these are added under immutability as a
language level (generalized way )

>>> a=10
>>> b=10
>>> a is b #True
>>> id(a) #1572353952
>>> id(b) #1572353952
Anand Komiripalem

Fundamental Data types Vs Immutability


Anand Komiripalem

Bytes Data Type


◊ Bytes represent a group of values like an array
◊ Creating a byte:
x= [10,20,30,40]
b= bytes(x)
type(b) #bytes
b[0] #10 b[-1] #40
Note:
◊ In bytes every value should be in the range of 0 to 256 only
◊ Once create a byte, we cannot change the values in the bytes if we
try to change it will throw an error. So bytes data type is immutable
x=[10,20,30,40]
b=bytes(x)
b[0]=100 # error
Anand Komiripalem

Bytearray Data Type


◊ Bytearray is same as bytes data type except that it is mutable(we
can modify the content)
◊ Creating a byte:
x= [10,20,30,40]
b= bytearray(x)
type(b) #bytearray
b[0] = 100 #[100,20,30,40]
Anand Komiripalem

List Data Type


◊ To represent a group of values as a single entity we go with List
◊ In list:
◊ Insertion order is preserved (the way we store the values will be stored
in same way)
◊ Heterogeneous values are allowed
◊ Duplicates are allowed
◊ Growable in nature
◊ Values should be enclosed within square brackets only
eg:
l= [10, 20, ”anand”, True]
print(l) #[10,20,”anand”,True]
l[1] #20
l[1:3] #[20, ‘anand’ , True]
Anand Komiripalem

List Data Type


◊ We can increase or decrease the size of an array according to our
requirement by using inbuilt functions
◊ append()  for adding values to list
◊ remove()  for removing values from list

eg:
l= [10, 20, 30]
l.append(‘anand’)
print(l) # [10,20,30,’anand’]
l.remove(20)
print(l) # [10,30,’anand’]
l*2 #[10,30,’anand’ , 10,30,’anand’]

◊ Default declaration of list is [] l=[]


Anand Komiripalem

Tuple Data Type


◊ Tuple is exactly same as list data type except that it is immutable .i.e
we cannot change values.
◊ Tuple is represented by braces ()
◊ Tuple can be considered as read only version of list
eg:
t=(10,20,30,40)
type(t) # <class 'tuple'>
t[0]=100 #error
t.append("anand") #error
◊ We can have lists in tuple
eg:
t=(10,20,[30,40])
Anand Komiripalem

Range Data Type


◊ Range is a data type as well as it is a function
◊ Range represents a sequence of values
◊ Range is immutable
Declaring range:
Form 1:
range(x) # represents values from 0 to x-1
eg:
r=range(10) # represents values from 0 to 9
type(t) # <class range'>
for i in r : print(i) # 1,2,3,4,5,6,7,8,9
Anand Komiripalem

Range Data Type


Form 2:
range(x,y) # represents values from x to y-1
eg:
r=range(10, 20) # represents values from 10 to 19
for i in r : print(i) # 11,12,13,14,15,16,17,18,19
Form 3:
range(x,y,z) # values from x to y-1 with z steps
eg:
r=range(5, 20,2)
r[0] #5
for i in r : print(i) # 5,7,9,11,13,15,17,19
Anand Komiripalem

Set Data Type


◊ Set is used to represent a group of values just like list
◊ In set:
◊ Insertion order is not preserved
◊ Duplicates are not allowed
◊ Heterogeneous objects are allowed
◊ Index/slicing concept is not applicable
◊ Is mutable concept
◊ Growable in nature
Declaring set:
s={100,0,10,200,10,anand'}
s # {0, 100, anand', 200, 10}
s[0] # TypeError: 'set' object does not support indexing
Anand Komiripalem

Set Data Type


◊ We can increase or decrease the size of an set according to our
requirement by using inbuilt functions
◊ add()  for adding values to list
◊ remove()  for removing values from list

Eg:
s= {10, 20, 30}
s.add(‘anand’)
print(s) # {10,20,30,’anand’}
s.remove(20)
print(s) # {10,30,’anand’}
Default empty set declaration is set()
Anand Komiripalem

frozenset Data Type


◊ Exactly same as set, the only deference is frozen set is immutable
◊ Functions add() and remove() are not applicable
◊ Declaration of frozen set

s= {10, 20, 30}


fs=frozenset(s)
type(fs) #FROZENSET
Anand Komiripalem

Dict Data Type


◊ To represent a group of individual key value pairs then we can go
with dict
Eg:
d = {101:‘anand',102:'ravi',103:'shiva'}
◊ Duplicate keys are not allowed but values can be duplicated. If we
are trying to insert an entry with duplicate key then old value will be
replaced with new value
◊ We can create empty dictionary as d={}
◊ We can add key-value pairs as follows
d['a']='apple'
d['b']='banana'
Print(d) #{101: 'anand', 102: 'shiva', 'a': 'apple', 'b': 'banana'}
◊ Dict is mutable and the order is not preserved
Anand Komiripalem

None Data Type


◊ None means nothing or no value associated
◊ If the value is not available then in order to handle such type of
cases none is introduced
Anand Komiripalem

Escape characters
◊ escape characters are used for some special purpose in python
◊ The following are various important escape characters in Python

\n ---- New Line


\t ---- Horizontal Tab
\r ----- Carriage Return (courser comes to initial position)
\b ----- Back Space
\f ------ Form Feed
\v ------ Vertical Tab
\‘ ------- Single Quote
\“ ------- Double Quote
\\ ------- Back Slash Symbol
Anand Komiripalem

Operators
◊ Operator is a symbol that performs certain operations/tasks
◊ Types of operators:

Arithmetic Operators
Relational Operators or comparison operators
logical operators
bitwise operators
assignment operator
special operator
Anand Komiripalem

Arithmetic Operators
+ --------- Addition
- --------- Subtraction
* --------- Multiplication
/ --------- Division
% --------- Modulo operator
// --------- floor division Operator
** --------- Exponential / power operator

a=10
b=2
print('a+b=',a+b) #a+b=12
print('a-b=',a-b) #a-b=8
print('a*b=',a*b) #a*b=20
print('a/b=',a/b) #a/b=5.0
print('a//b=',a//b) #a//b=5
print('a%b=',a%b) #a%b=0
print('a**b=',a**b) #a**b=100
Anand Komiripalem

Arithmetic Operators
Note:
◊ / operator always performs floating point arithmetic. Hence it will always
returns float value.
◊ But Floor division (//) can perform both floating point and integral
arithmetic. If arguments are int type then result is int type. If at least one
argument is float type then result is float type.
◊ we can use +,* operators for str type also
◊ If we want to use + operator for str type then compulsory both arguments
should be str type only otherwise we will get error.

“anand"+10 # TypeError: must be str, not int


“anand"+"10" #‘anand10'
Anand Komiripalem

Relational Operators
Operators: <, <=, >, >=, ==, !=

a=10
b=20
print("a > b is ",a>b) # a>b is False
print("a >= b is ",a>=b) #a>=b is False
print("a < b is ",a<b) #a<b is True
print("a <= b is ",a<=b) #a<=b is True
print(“a==b is”, a==b) #a==b is False
print(“a!=b”, a!=b) #a!=b is True
Anand Komiripalem

Relational Operators
We can apply relational operators for str types also.
a=“anand”
b=“anand”
print("a > b is ",a>b) # a>b is False
print("a >= b is ",a>=b) #a>=b is True
print("a < b is ",a<b) #a<b is False
print("a <= b is ",a<=b) #a<=b is True
print(“a==b is”, a==b) #a==b is True
print(“a!=b”, a!=b) #a!=b is False

Note: Chaining of relational operators is possible. In the chaining, if all


comparisons returns True then only result is True. If atleast one
comparison returns False then the result is False

10<20 #True
10<20<30 # True
10<20<30<40 #True
10<20<30<40>50 #False
Anand Komiripalem

Logical Operators
Logical operators supported by python: and, or, not
For boolean behavior:
and  If both arguments are True then only result is True
or  If at least one argument is True then result is True
not Complement
True and False # False
True or False # True
not False #True
For non boolean behavior:
◊ 0 means False , non-zero means True
◊ empty string is always treated as False

x and y : If x is evaluates to false return x otherwise return y

Note: If first argument is zero then result is zero otherwise result is y


Anand Komiripalem

Logical Operators
x or y : If x evaluates to True then result is x otherwise result is y
10 or 20  10
0 or 20  20

not x : If x evaluates to False then result is True otherwise False


not 10  False
not 0  True
Eg:
“anand" and “anand" ==>”anand”
"" and “anand" ==>""
“anand" and "" ==>""
"" or “anand" ==>“anand"
“anand" or ""==>“anand"
not ""==>True
not “anand" ==>False
Anand Komiripalem

Bitwise Operators
◊ Bitwise operators available are:

&  and
|  or
^  xor
~  complement
<< left shift
>>  right shift

◊ Bitwise operators are applicable only on int and boolean types


◊ By mistake if we try to apply any other types we will get Error

print(4&5) # Valid
print(10.5 & 5.6) # TypeError:
print(True & True) # Valid
Anand Komiripalem

Bitwise Operators
◊ &  if both bits are 1 then result is 1 otherwise result is 0
◊ |  if at least one bit is 1 then result is 1 otherwise result is 0
◊ ^  if bits are different then result is 1 otherwise result is 0
◊ ~  complement
◊ << left shift
◊ >>  right shift

4 - 100
print(4&5) #4
5- 101
print(4|5) #5
4 - 100 100
5- 101 print(4^5) #1
101 4 - 100
5- 101
001
Anand Komiripalem

Bitwise Operators
◊ ~  complement
print(~4) #-5
print(~100) # -101
print(~111) #-112
print(~True) # -2
◊ In complement we will get (–n-1) value of the given value

<< operator: the bits move towards left side

print(10<<2) #40
Anand Komiripalem

Bitwise Operators
>> operator: the bits move towards right side

print(10>>2) #2

◊ We can apply bitwise operators for boolean types also


print(True & False) # False
print(True | False) #True
print(True ^ False) # True
print(~True) # -2
print(True<<2) #4
print(True>>2) #0
Anand Komiripalem

Assignment Operators
◊ We use assignment operator to assign values to variables
Eg: x=10

◊ We can combine assignment operator with other operators to form


compound assignment operator.
◊ The following is the list of all possible compound assignment operators
in Python:
+= -=
*= /=
%= //=
**= &=
|= ^=
>>= <<=
◊ Increment and decrement operators are not supported in python
Anand Komiripalem

Assignment Operators
Eg:
x=10
x+=20
print(x) # 30

Ternary Operator (or) Conditional Operator:


Syntax: x = firstValue if condition else secondValue

◊ If condition is True then firstValue will be considered else


secondValue will be considered.
Eg 1:
a,b=10,20
x=30 if a<b else 40
print(x) #30
Anand Komiripalem

Assignment Operators
Eg : Read two numbers from the keyboard and print minimum
value
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)

Eg: Program for Minimum of 3 Numbers


a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min=a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)
Anand Komiripalem

Special Operators
◊ Python supports the following special operators
◊ Identity Operator
◊ Membership operator

Identity Operator:
◊ Identity operators are used for address comparison
◊ The available identity operators are:
◊ Is : r1 is r2 returns True if both r1 and r2 are pointing to the same
object.
◊ Is not: r1 is not r2 returns True if both r1 and r2 are not pointing to the
same object.
Anand Komiripalem

Special Operators
Eg: Eg1:
a=10 x=True
b=10 y=True
print(a is b) #True print( x is y) True
-------------------------------------------------------------------------------------------------------------
a=“anand" list1=["one","two","three"]
b=“anand" list2=["one","two","three"]
print(id(a)) #47541440 print(id(list1)) #50038424
print(id(b)) #47541440 print(id(list2)) #45325928
print(a is b) #True print(list1 is list2) # False
print(list1 is not list2) # True
print(list1 == list2) #True

Note: We can use is operator for address comparison where as ==


operator for content comparison.
Anand Komiripalem

Special Operators
Membership operator:
◊ We can use Membership operators to check whether the given object
present in the given collection. (It may be String, List, Set, Tuple OR Dict)

In  Returns True if the given object present in the specified Collection


not in  Returns True if the given object not present in the specified Collection

Eg: Eg2:
x="hello learning Python is very easy!!!"
print('h' in x) #True list1=["sunny","bunny","chinny","pinny"]
print('d' in x) #False print("sunny" in list1) #True
print('d' not in x) #True print("tunny" in list1) #False
print('Python' in x) #True print("tunny" not in list1) #True
Anand Komiripalem

Mathematical Functions (math Module)

◊ Module is collection of functions, variables and classes etc


◊ math is a module that contains several functions to perform mathematical
operations
◊ In order to use a module in python first we need to import them
◊ Import math is used for importing the math module

Eg:
import math
print(math.sqrt(16)) #4.0
print(math.pi) #3.141592653589793
Anand Komiripalem

Mathematical Functions (math Module)


◊ We can create alias name by using as keyword. import math as m
Eg:
import math as m
print(m.sqrt(16)) #4.0
print(m.pi) #3.141592653589793

◊ We can import a particular member of a module explicitly


◊ we import a member explicitly then it is not required to use module name
while accessing.

Eg:
from math import sqrt,pi
print(sqrt(16)) #4.0
print(pi) # 3.141592653589793
Print(math.pi) #Error: now it wont recognise math module
Anand Komiripalem

Mathematical Functions (math Module)


◊ Some functions available in math module:
◊ ceil(x): Returns the smallest integer greater than or equal to x.
◊ factorial(x): Returns the factorial of x
◊ isfinite(x): Returns True if x is neither an infinity nor a NaN (Not a Number)
◊ exp(x): Returns e**x
◊ pow(x, y): Returns x raised to the power y
◊ sqrt(x): Returns the square root of x
◊ cos(x): Returns the cosine of x
◊ sin(x): Returns the sine of x
◊ tan(x): Returns the tangent of x
◊ pi: Mathematical constant, (3.14159...)

from math import pi


r = 16
print("Area of Circle is :",pi*r**2) #Area of Circle is: 804.247719318987
Anand Komiripalem

Input and Output Statements


Input Statements:
◊ Input statements are used for reading dynamic data from
◊ Python has 2 functions for reading data from keyboard
◊ raw_input() :This function always reads the data from the keyboard in the
form of String Format. We need to perform type casting

◊ input() : input() function can be used to read data directly in our required
format.We are not required to perform type casting.
◊ Note: Above two are supported in Python 2 only
◊ But in Python 3 we have only input() method and raw_input() method is not
available
◊ raw_input() function of Python 2 is renamed as input() function in Python 3

type(input("Enter value:")) Enter value:10 <class 'str'>


type(input("Enter value:")) Enter value:10.5 <class 'str'>
Anand Komiripalem

Input and Output Statements


Eg: a program to read 2 numbers from the keyboard and print sum

x=input("Enter First Number:") Output:


y=input("Enter Second Number:") --------------
i = int(x) Enter First Number: 20
j = int(y) Enter Second Number: 30
print("The Sum:",i+j) The sum: 50

-----------------------------------------------------------
Output:
x=int(input("Enter First Number:")) --------------
y=int(input("Enter Second Number:")) Enter First Number: 40
print("The Sum:",x+y) Enter Second Number: 50
The sum: 90
--------------------------------------------------
print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second
Number:")))
Anand Komiripalem

Input and Output Statements


Eg: Write a Program to read Employee Data from the Keyboard and print that
Data

eno=int(input("Enter Employee No:")) Output:


ename=input("Enter Employee Name:")
--------------
Enter Employee No:1002
esal=float(input("Enter Employee Salary:"))
Enter Employee Name: Anand
eaddr=input("Enter Address:")
Enter Employee Salary:10000
married=bool(input("Married ?[True|False]:"))
Enter Address :Mumbai
print("Please Confirm Information") Married ?[True|False]:True
print("Employee No :",eno) Please Confirm Information
print("Employee Name :",ename) Employee No : 1002
print("Employee Salary :",esal) Employee Name : Anand
print("Employee Address :",eaddr) Employee Salary : 10000.0
print("Employee Married ? :",married) Employee Address : Mumbai
Employee Married ? : True
Anand Komiripalem

Input and Output Statements


split():
◊ Split() is a function used for separating the values by using a separator
◊ Default separator is space(), but we can use any separator as we like

◊ We can read multiple values in a single statement using split()

a,b,c= [float(x) for x in input("Enter 3 float numbers :").split(',')]


print("The Sum is :", a+b+c)
Output:
Enter 3 float numbers :10.5,20.6,20.1
The Sum is : 51.2
Anand Komiripalem

Input and Output Statements


eval():
◊ eval Function take a String and evaluate the Result.
◊ eval dynamically considers data type based on the values provided
Eg:
x = eval(“10+20+30”) x = eval(input(“Enter Expression”))
print(x) # 60 Enter Expression: 10+2*3/4 #11.5

eval() can evaluate the Input to list, tuple, set, etc based the Input.

l = eval(input(“Enter List”)) Enter List [1,2,3,4,5,6]


print (type(l)) <class 'list'>
print(l) [1, 2, 3, 4, 5, 6]
Anand Komiripalem

Command line arguments


◊ The arguments give from the command line at the time of execution
are called command line arguments
◊ ‘argv’ is used for reading values that are passed from command
prompt
◊ argv is a list data type and is available in sys module

◊ Create and save the program and try to run it from command prompt.

from sys import argv #saved this program by name test.py


print(type(argv))
print(argv)
Anand Komiripalem

Command line arguments


Note: argv[0] represents Name of Program. But not first Command Line
Argument. argv[1] represent First Command Line Argument.

◊ At the time of displaying we can remove the file name by using slice
operator
from sys import argv
print(type(argv))
print(argv)
print(argv[1:])
print(len(argv))
Anand Komiripalem

Command line arguments


Eg: program to get the numbers from command line and print the sum
from sys import argv
sum=0
args=argv[1:]
for x in args :
n=int(x)
sum=sum+n
print("The Sum:",sum)

Note 1: Usually space is separator between command line arguments. If our


command line argument itself contains space then we should enclose within
double quotes(but not single quotes)
Anand Komiripalem

Command line arguments


Output Statements:
◊ Used to display the output on the console
◊ print() is an output statement
◊ We can use print in different ways:
Form-1: print() without any argument
◊ Just it prints new line character
Form-2: print(string)
Eg: print(“hello world”) #hello world
Form-3: print(variable arguments)
Eg: a,b,c = 10,20,30
print(“the values are: ”, a,b,c) # the values are 10 20 30
Note: by default the values are separated by space but we can
customize it using “separator”
Anand Komiripalem

Command line arguments


a,b,c=10,20,30
print(a,b,c,sep=',') #10,20,30
print(a,b,c,sep=':') #10:20:30

Form-4: print() with end attribute


If we want output in the same line with space
Eg:
print(“Advanto", end=' ')
print(“Software", end=‘ ')
print(“Pvt Ltd") #Advanto Software Pvt Ltd
Anand Komiripalem

Command line arguments


Form-5: print() with replacement operator ({})

name = “anand"
salary = 10000
print("Hello {} your salary is {} ". format(name, salary))
print("Hello {x} your salary is {y} ". format(x=name, y=salary))

Output
Hello anand your salary is 10000
Hello anand your salary is 10000
Thank Q

You might also like