Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Unit 1

The document provides an introduction to Python, covering its history, features, applications, and the program development life cycle. It explains key concepts such as variables, input/output operations, and decision structures, along with examples of Python syntax. Additionally, it highlights the advantages and limitations of Python as a programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit 1

The document provides an introduction to Python, covering its history, features, applications, and the program development life cycle. It explains key concepts such as variables, input/output operations, and decision structures, along with examples of Python syntax. Additionally, it highlights the advantages and limitations of Python as a programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

PYTHON

UNIT-1 Introduction: Introduction to Python, Program Development Cycle, Input, Processing, and
Output, Displaying Output with the Print Function, Comments, Variables, Reading Input from the Keyboard,
Performing Calculations, Operators. Type conversions, Expressions, More about Data Output.
Data Types, and Expression: Strings Assignment, and Comment, Numeric Data Types and Character
Sets,
Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision Structures,
Comparing Strings, Logical Operators, Boolean Variables. Programming: Introduction to Programming
Concepts with Scratch.

Introduction to Python:

Python is a widely used general-purpose, high level programming language. It was created by Guido van
Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an
emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines
of code.
Python was originally created by Guido Van Rossum, who was a Dutch person from Netherlands in the
Year 1991. Guido Van Rossum created it when he was working in National Research Institute of
Mathematics and Computer Science in Netherlands. He thought to create a scripting language as a
“Hobby” in Christmas break in 1980. He studied all the languages like ABC (All Basic Code), C, C++,
Modula-3, Smalltalk, Algol-68 and Unix Shell and collected best features. He stared implementing it from
1989 and released first working version of Python in 1991. He named it as “Python”, being a big fan of
“Monty Python’s Flying Circus” comedy show broadcasted in BBC from 1969 to 1974.
Python is a high-level, general-purpose programming language for solving problems on modern computer
systems. The language and many supporting tools are free, and Python programs can run on any operating
system. You can download Python, its documentation, and related materials from www.python.org

Python is a programming language that lets us work quickly and integrate systems more efficiently. There are
two major Python versions: Python 2 and Python 3. Both are quite different.

History of Python:
1. Python is widely used high level programming language for general purpose programming and which is
created by Guido Van Rossum and first released in 1991.

2. This is interpreted language and in this language syntax for programmers is fewer lines than other languages.

3. Cpython is a reference implementation of python and it is open source software and this cpython is managed
by non profit Python Software Foundation.

4. Python was released in late 1980’s and its implementation began in Dec’1989 by Guido Van Rossum at
Centrum Wiskunde and Informatic(CWI) in Netherlands

5. Guido Van Rossum decided to write an interpreter for new scripting language and after he had put a name for
it Python.
6. Python 2.0 was released on 16 th Oct’2000 by including new features like cycle detecting garbage collector
and becomes more transparent and community backed.
7. After long period of testing Python 3.0 was released on 3rd Dec’2008.

8. Many of the major features are added in 2.6x and 2.7x versions

9. Now a days so many companies like Google, Intel, Yahoo and Microsoft are using Python for their
projects.
Applications:
1. Web development – Web framework like Django and Flask are based on Python. They help you
write server side code which helps you manage database, write backend programming logic, mapping
urls etc.

2. Machine learning – There are many machine learning applications written in Python. Machine
learning is a way to write a logic so that a machine can learn and solve a particular problem on its
own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is a
machine learning algorithm that recognises user’s interest. Face recognition and Voice recognition in
your phone is another example of machine learning.

3. Data Analysis – Data analysis and data visualisation in form of charts can also be developed using
Python.

4. Scripting – Scripting is writing small programs to automate simple tasks such as sending automated
response emails etc. Such type of applications can also be written in Python programming language.

5. Game development – You can develop games using Python.

6. You can develop Embedded applications in Python.

7. Desktop applications – You can develop desktop application in Python using library like TKinter or
QT.

Organizations using Python :


1) Google(Components of Google spider and Search Engine)
2) Yahoo(Maps)
3) YouTube
4) Mozilla
5) Dropbox
6) Microsoft
7) Cisco
8) Spotify
9) Quora

Features of Python:
1. Simple and easy to learn.
2. Free ware and Open source.
3. High level programming language.
4. Python id platform independent.
5. Portability.
6. Dynamically typed.
M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 2
7. Both procedure oriented and object oriented.
8. Interpreted programming language.
9. Extensible.
10. Embedded.
11. Extensive library.
1) Readable: Python is a very readable language.

2) Easy to Learn: Learning python is easy as this is a expressive and high level programming language,
which means it is easy to understand the language and thus easy to learn.

3) Cross platform: Python is available and can run on various operating systems such as Mac,
Windows, Linux, Unix etc. This makes it a cross platform and portable language.

4) Open Source: Python is a open source programming language.

5) Large standard library: Python comes with a large standard library that has some handy codes and
functions which we can use while writing code in Python.

6) Free: Python is free to download and use. This means you can download it for free and use it in your
application. Python is an example of a FLOSS (Free/Libre Open Source Software), which means you
can freely distribute copies of this software, read its source code and modify it.

7) Supports exception handling: If you are new, you may wonder what is an exception? An exception
is an event that can occur during program exception and can disrupt the normal flow of program.
Python supports exception handling which means we can write less error prone code and can test
various scenarios that can cause an exception later on.

8) Advanced features: Supports generators and list comprehensions.

9) Automatic memory management: Python supports automatic memory management which means
the memory is cleared and freed automatically. You do not have to bother clearing thememory.

Limitations of Python:

1. Performance is not up to the mark.


2. For mobile applications it is not up to the mark.
Flavours of python:

1. Cpython
2. Jython (or) Jpython.
3. Ironpython.
4. Pypy.
5. Rubypython.
6. Anaconda python.
7. Stackless

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 3


Program Development Life cycle
•Program Development Life Cycle (PDLC) is a systematic way of developing quality software. It
provides an organized plan for breaking down the task of program development into manageable chunks,
each of which must be successfully completed before moving on to the next phase.

The Program Development Cycle (PDC) has various states as follow:


a. Problem Definition: Here the formal definition o the problem is stated. This stage gives thorough
understanding of the problem, and all the related factors such as input, output, processing requirements, and
memory requirements etc.

b. Program Design: Once the problem and its requirements have been identified, then the design
of the program will be carried out with tolls like algorithms and flowcharts. An Algorithm is a step-by-
step process to be followed to solve the problem. It is formally written using the English language. The
flowchart is a visual representation of the steps mentioned in the algorithm. This flowchart has some
set of symbols that are connected to perform the intended task. The symbols such as Square, Dimond,
Lines, and Circles etc. are used.
Adding two integer numbers
Algorithm Flowchart
i. Declare variables a,b,c
ii. Read a, and b
from keyboard
iii. Add a, b and store result
in c
iv. Display result

c. Coding: Once the design is completed, the program is written using any programming language such
as C, C++, Python, and Java etc. The Coding usually takes very less time, and syntax rules of the
language are used to write the program.
adding two integers numbers in
Python
a=int(input('Enter
a'))
b=int(input('Enter
b')) c=a+b
print('The sum is',c)
d. Debugging: At this stage the errors such as syntax errors in the programs are detected and corrected.
This stage of program development is an important process. Debugging is also known as program
validation.
e. Testing: The program is tested on a number of suitable test cases. The most insignificant and the most
special cases should be identified and tested.
f. Documentation: Documentation is a very essential step in the program development. Documentation
helps the users and the who actually maintain the software.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 4


g. Maintenance: Even after the software is completed, it needs to be maintained and evaluated regularly.
In software maintenance, the programming team fixes program errors and updates the software when
new features are introduced.

Variables
•Variables are nothing but reserved memory locations to store values. It means that when you create a
variable, you reserve some space in the memory. Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the reserved memory.

Naming rules of variable


• Must begin with a letter (a - z, A - B) or underscore (_)
• Other characters can be letters, numbers or _ (alphanumeric Characters)

• Variables are Case Sensitive ( ‘age’ , ‘Age’, ‘AGE’ are three different variables)
• Can be any (reasonable) length (var.bit_length() returns the number of bits required)
• There are some reserved words which you cannot use as a variable name because Python uses them
for other things.

Assigning Values to Variables


•Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.
•The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.

For example :
counter =100 # An integer assignment
miles =1000.0 # A floating point
name ="John" # A string
print(counter)
print(miles)
print(name)

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively.
This produces the following result − Output:
100
1000.0
‘John’
Multiple Assignments: Python allows you to assign a single value to several variables simultaneously.

For example: a=b=c=1


Here, an integer object is created with the value 1, and all the three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables.
For example: a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.
Python Comments:
M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 5
Comments are descriptions that help programmers better understand the intent and functionality of the
program. It is completely ignored by the Python interpreter.
Single-Line Comments in Python: In Python, we use the hash symbol # to write a single-line comment.

Example 1: Writing Single-Line Comments


# printing a string print('Hello
world')
Output: Hello world
Here, the comment is: # printing a string. This line is ignored by the Python interpreter. Everything that
comes after # is ignored. So, we can also write the above program in a single line as:
print('Hello world') #printing a string
The output of this program will be the same as in Example 1. The interpreter ignores all the text after #.

Multi-Line Comments in Python: We can use # at the beginning of each line of comment on multiple lines.

Example 2: Using multiple #

# it is a multiline
# comment
Here, each line is treated as a single comment and all of them are ignored.
In a similar way, we can use multiline strings (triple quotes) to write multiline comments as shown
below The quotation character can either be ' or ".
'''
I am a multiline
comment! '''
print("Hello World")
Input, Processing, and Output
• Most useful programs accept inputs from some source, process these inputs, and then finally output
results to some destination.
• In terminal-based interactive programs, the input source is the keyboard, and the output destination is
the terminal display.
•The Python shell itself takes inputs as Python expressions or statements. Its processing evaluates these
items. Its outputs are the results displayed in the shell.
• Python provides numerous built-in functions that are readily available to us at the Python prompt.
• Some of the functions like input() and print() are widely used for standard input and output operations
respectively.
Let us see the output section first. : Python Output Using print () function

• We use the print() function to output data to the standard output device (screen). We can also output
data to a file
print() function:The print() function prints the given object to the standard output device (screen) or to
the text stream file.
syntax of print() is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 6
o Objects - object to the printed. * indicates that there may be more than one object o sep -

objects are separated by sep. Default value: ' ' o end - end is printed at last by default it
has \n
o file - must be an object with write(string) method. If omitted it, sys.stdout will beused which
prints objects on the screen.

o flush - A Boolean, specifying if the output is flushed (True) or buffered (False). Default:
False

Example 1: print('This sentence is output to the screen')


Output: This sentence is output to the screen
Example 2: a = 5 print('The value of a
is', a)

Output: The value of a is 5

Example 3: # Two objects are passed print("a =",


a) print("Python is fun.") a = 5
b=a
print('a =', a, '= b')

Output: Python is fun.


a=5=b
Case 1: print without any arguments
print(‘KKR& KSR Engineering College’)
print () # we have not passed any argument by default it takes new line and create one line space
print(‘Computer Science Engineering’)

Output: KKR& KSR Engineering College


Computer Science Engineering
Case 2: print function with string operations (with arguments)
1. print(‘helloworld’) Output: helloworld
2. print(‘hello\nworld’) Output: hello
world
3. print(‘hello\tworld’) Output: hello world

# string concatenation both objects are string only


print(‘tec’ + ‘cse’) Output: teccse print(‘tec’ , ‘cse’) Output:
tec cse 5.
# repeat string into number of times
print(5*’cse’) Output: csecsecsecsecse
print(5*’cse\t’) output: : cse cse cse cse cse

Case 3 print function with any number of arguments

1. (a) print(‘values are :’,10,20,30) Output: values are : 10 20 30

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 7


(b) a,b,c=10,20,30 print(‘values are:’,a,b,c) Output: values are : 10

20 30

2. print function with “sep” attribute: This is used to separate objects


By default, value of sep is empty space(sep=’’)
>>>print('values are:',10,20,30,sep=":")
Output: values are::10:20:30

>>>print('values are:',10,20,30,sep="--")

Output: values are:--10--20—30


Case 4: print statement with end attribute
•The end key of print function will set the string that needs to be appended when printing is done.
•By default, the end key is set by newline character (By default, attribute end =’\n’ in print function). So
after finishing printing all the variables, a newline character is appended. Hence, we get the output of each
print statement in different line. But we will now overwrite the newline character by any character at the
end of the print statement.
Example-1:
• print('Tirumala') # in this statement by default end =’\n’ so it takes new line
• print('rajani') # in this statement by default end =’\n’ so it takes new line
• print('devansh') # in this statement by default end =’\n’ so it takes new line

Output:
Tirumala
rajani
devansh
Note: when you observe output 1st print statement prints output Tirumala and immediately takes new
line character and execute 2nd print statement and followed.

Example-2:
•print ('Tirumala’, end='$')
•print ('rajani' ,end='*')
•print('devansh')
Output: Tirumala$
rajani*
devansh

Case 5: print function with sep and end attribute Example

•print(19,20,30,sep=':',end='$$$')
•print(40,50,sep=':')
•print(70,80,sep=':',end='&&&')
•print(90,100)
Output: 19:20:30$$$
40:50
70:80&&&
M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 8
90 100
Python | Output Formatting
•There are several ways to present the output of a program, data can be printed in a human- readable
form, or written to a file for future use. Sometimes user often wants more control the formatting of output
than simply printing space-separated values. There are severalways to format output.

1. Formatting output using String modulo operator (%):


Syntax: print („formatted string‟ %( variable list)
The % operator can also be used for string formatting. string modulo operator ( % ) is still available in
Python(3.x) and user is using it widely.
Example 1
# Python program showing how to use string modulo operator (%) to print fancier output # print integer
and float value
print ("CSE: % 2d, Portal: % 5.2f"%(1, 05.333)) # print integer value
print ("Total students: % 3d, Boys: % 2d"%(240, 120)) # print octal value
print ("% 7.3o"%(25)) # print exponential value
print ("% 10.3E"%(356.08977))
Output :
CSE: 1, Portal: 5.33
Total students: 240, Boys: 120
031
3.561E+02
Example 2: a=6
print(‘a value is =%i’ %a)
Output: a value is =6
(b) a=6;b=7;c=8
print('a value is =%i and b=%f and c=%i' %(a,b,c))
Output: a value is =6 and b=7.000000 and c=8

2. print function with replacement operator {}or format function


str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and
value formatting. This method lets us concatenate elements within a string through positional
formatting.

Example 1: Name= ‘John’


Salary=’1000’ print(‘hello my name is {} and my salary is
{}’.format(Name,Salary))
Output: hello my name is John and my salary is 1000

Example 2: name='John'
salary=1000 print('hello my name is "{}" and my salary is
"{}"'.format(name,salary))

Output: hello my name is "John" and my salary is "1000"

Example 3: name='John' salary=1000 print('hello my name is


"{0}" and my salary is "{1}"'.format(name,salary))

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 9


Output: hello my name is "John" and my salary is "1000"
Example 4: print('hello my name is "{0}" and my salary is "{1}"'.format(salary,name))
Output: hello my name is "1000" and my salary is "john"

***** **** we can also use variables in the reference operator*********

Example 5: print ('hello my name is "{n}" and my salary is "{s}"‘. format (n=name, s=salary))

Output: hello my name is "john" and my salary is "1000"

Example 6: print ('hello my name is "{n}"and my salary is { s}'.format(s=salary,n=name))


Output: hello my name is "john" and my salary is "1000"

Reading Input from the Keyboard: In python input() is used to read the input from the keyboard
dynamically. By default, the value of the input function will be stored as a string
Syntax: Variable name =input(‘prompt’)

Example:
name =input("Enter Employee Name ")
salary =input("Enter salary ") company
=input("Enter Company name ") print("\
n")
print("Printing Employee Details")
print("Name","Salary","Company")
print(name, salary, company)

Output:
Enter Employee Name Jon
salary 12000
Enter Company name Google
Printing Employee Details
Name Salary Company
Jon 12000 Google
Accept an numeric input from User: To accept an integer value from a user in Python. We need to
convert an input string value into an integer using a int() function.

Example: first_number = int(input("Enter first number "))

We need to convert an input string value into an integer using a float() function.

Example: Program to calculate addition of two input


numbers first_number=int(input("Enter first number "))
second_number=int(input("Enter second number "))
print("First Number:",first_number) print("Second
Number:",second_number) sum1
=first_number+second_number print("Addition of two
number is: ", sum1)

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 10


Output:
Enter first number 20
Enter second number 40
First Number: 20
Second Number: 40
Addition of two number is: 60

Get multiple input values from a user in one line: In Python, we can accept two or three values from
the user in one input() call.

Example: In a single execution of the input() function, we can ask the user he/her name, age, and phone
number and store it in three different variables.
name, age, phone =input("Enter your name, Age, Percentage separated by space ").split() print("\
n")
print("User Details: ", name, age, phone)

Output:
Enter your name, Age, Percentage separated by space John 26 75.50
User Details: John 26 75.50

Performing Calculations
Computers are great at math problems! How can we tell Python to solve a math problem for us? In this
we use numbers in Python and the special symbols we use to tell it what kind of calculation to do.
Example-1:
1. print(2+2)
2. print("2"+"2")

Output:
4
22
Example-2:
Subtraction: print(2 - 2)
Multiplication: print(2 * 2)
Division: print(2 / 2)

Output:
0
4
1.0

Question: Why did the last statement output 1.0?


Answer: When Python does division, it uses a different kind of number called a float. Floats always
have a decimal point. Integers are always whole numbers and do not have decimal points.

PEMDAS.
print((6 - 2) * 5)
print(6 - 2 * 5)

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 11


Example-3:
The first statement is evaluated by Python like this:
1. (6 – 2) * 5 Parentheses first
2. 4 * 5
3. 20
The second statement is evaluated like this:
1. 6 – 2 * 5 Multiplication first
2. 6 – 10
3. -4

Example-4:
The modulo operator (%) finds the remainder of the first number divided by the second number.
print(12 % 10) = 2
12 / 10 = 1 with a remainder of 2.
Integer division (//) is like normal division, but it rounds down if there is a decimal point.
print(5 // 2)
5 // 2 = 2, which is rounded down to 2

Exponentiation (**) raises the first number to the power of the second number. print(3 ** 2) This
is the same as 32
Example-5:
Remember, input() returns a string, and we can’t do math with strings. Fortunately, we can change
strings into ints like so:

two = "2" two =


int(two)
print(two + two)
If you need to work with a decimal point, you can change it to a float instead:
two = float(two)
Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
1. Arithmetic Operators.
2. Comparison/relational Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
7. Bitwise Operators

1. Arithmetic Operators
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left a – b = -10


hand operand.
* Multiplication Multiplies values on either side of the a * b = 200

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 12


operator
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder
** Exponent Performs exponential (power) calculation a**b =10 to the
on operators power 20
// Floor Division - The division of operands 9//2 = 4 and
where the result is the quotient in which 9.0//2.0 = 4.0
the digits after the decimal point are
removed.

Example: x ,y=
15,4
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y) #
Output: x * y = 60
print('x / y =',x*y)
# Output: x / y = 3.75
print('x // y =',x/y)
# Output: x // y = 3 Floor Division Operator
Print(‘x**y=’,x**y)
# Output: x ** y = 50625 Power Operator

Python Mixed-Mode Arithmetic


The calculation which done both integer and floating-point number is called mixed-mode arithmetic.
When each operand is of a different type.
Example:
9/2.0 ---> 4.5

2. Relational Operators
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example

== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
!= If values of two operands are not equal, then (a != b) is true.
condition becomes true.
<> If values of two operands are not equal, then (a <> b) is true. This is
condition becomes true. similar to != operator.
> If the value of left operand is greater than the (a > b) is not true.
value of right operand, then condition becomes
true.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 13


< If the value of left operand is less than the value (a < b) is true.
of right operand, then condition becomes true.

>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then
condition becomes true.

<= If the value of left operand is less than or equal (a <= b) is true.
to the value of right
operand, then condition
becomes true.
Example: x = 5 y = 2 print('x > y is',x>y)
#Output: x > y is True

print('x < y is',x<y) # Output: x < y is False

print('x == y is',x==y) # Output: x == y is False

print('x != y is',x!=y) # Output: x != y is True

print('x >= y is',x>=y) # Output: x >= y is True

print('x <= y is',x<=y) # Output: x <= y is False

print('x != y is',x!=y) # Output: x != y is True

print('x >= y is',x>=y) # Output: x >= y is True

print('x <= y is',x<=y) # Output: x <= y is False

3. Python Logical Operators


There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then:

Operator Description Example


And If both the operands are true then condition (a and b) is true.
Logical AND becomes true.
Or If any of the two operands are non-zero (a or b) is true.
Logical OR then condition becomes true.
not Used to reverse the logical state of its Not (a and b) is false.
Logical NOT operand.
Example :

x = True
y = False

print('x and y is',x and y) # Output: x and y is False


print('x or y is',x or y) # Output: x or y is True
print('not x is',not x) # Output: not x is False

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 14


4. Assignment Operators: Assume variable a holds 10 and variable b holds 20, then

Operator Description Example


= Assigns values from right side operands to c = a + b assigns
left side operand value of a + b into c
+= Add It adds right operand to the left operand and c += a is equivalent
AND assign the result to left operand to c = c + a
-= It subtracts right operand from the left c -= a is equivalent
Subtract AND operand and assign the result to left operand to c = c - a
*= It multiplies right operand with the left c *= a is equivalent
Multiply AND operand and assign the result to left operand to c = c * a
/= It divides left operand with the right operand c /= a is equivalent
Divide AND and assign the result to left operand to c = c / a
%= It takes modulus using two operands and c %= a is
Modulus AND assign the result to left operand equivalent to c =
c%a
**= Performs exponential (power) calculation on c **= a is
Exponent AND operators and assign value to the left operand equivalent to c = c
** a
//= Floor It performs floor division on operators and c //= a is equivalent
Division assign value to the left operand to c = c // a

5. Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below

Operator Description Example

is Evaluates to true if the variables on either side of x is y, here is results in 1 if


the operator point to the same object and false id(x) equals id(y).
otherwise.
is not Evaluates to false if the variables on either side of x is not y, here is not results in
the operator point to the same object and true 1 if id(x) is not equal to id(y).
otherwise.

Example:
x1 , y1 = 5 ,5 x2 ,
y2 = "cse",”cse”
x3 , y3= [1,2,3],[1,2,3]
print(id(x1)) #20935504
print(id(y1)) #20935504
print(x1 is y1) True
print(x1 is not y1) False
print(id(x2)) #21527296
print(id(y2)) #21527296
print(x2 is y2) True
print(x2 is not y2)
M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 15
print(id(x3)) False
#45082264
print(id(y3)) #45061624
print(x3 is y3) True

1. Membership Operators:
Python‘s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below:

Operator Description Example

In Evaluates to true if it finds a variable in the x in y, here in results in a 1 if


specified sequence and false otherwise. x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in x not in y, here not in results
the specified sequence and false otherwise. in a 1 if x is not a member of
sequence y.
in: "in" operator return true if a character or the entire substring is present in the specified string,
otherwise false.
not in: "not in" operator return true if a character or entire substring does not exist in the
specified string, otherwise false Example:
str1="ramuit"
str2="tirumalacse"
str3="ramu"
str4="tirumala"
print(str3 in str1) # True
print(str4 in str2) # True
print(str3 in str2) # False
print("ratan" in "ratanit") #true
print("ratan" in "durgasoft") #False
print(str3 not in str1) # False
print(str4 not in str2) # False
print(str3 not in str2) # True
print("ratan" not in "ratanit") # false
print("ratan" not in "anu") # true

2. Bitwise Operators:
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101

a&b = 0000 1100 a|


b = 0011 1101 a^b
= 0011 0001
~a = 1100 0011

There are following Bitwise operators supported by Python language

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 16


Operator Description Example
& Binary AND Operator copies a bit to the result if it (a & b) = 12
exists in both operands. (means 0000 1100)
| Binary OR It copies a bit if it exists in either (a | b) = 61
operand. (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand (a ^ b) = 49 (means 0011 0001)
but not both.
~ It is unary and has the effect of 'flipping' (~a ) = -61 (means 1100 0011 in 2's
Binary Ones bits. complement form due to a signed binary
Complement number.
<< The left operands value is moved left by a << 2 = 240
Binary Left Shift the number of bits specified by the right (means 1111 0000)
operand.
>> The left operands value is moved right a >> 2 = 15
Binary Right by the number of bits specified bythe (means 0000 1111)
Shift right operand

Data types in Python

In Python, like in all programming languages, data types are used to classify one particular type of data.
This is important because the specific data type we use will determine that what values we can assign to it
and what we can do to it i.e what operations we can perform on it.

Numbers
• Type:Int / float/complex
• Describes the numeric value & decimal value
• These are immutable modifications are not allowed.
Boolean
• bool : type
• represent True/False values.
• 0 =False & 1 =True
• Logical operators and or not return value is Boolean

Strings
• str : type
• Represent group of characters
• Declared with in single or double or triple quotes
• It is immutable modifications are not allowed.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 17


Lists
• list : type
• group of heterogeneous objects in sequence.
• This is mutable modifications are allowed
• Declared with in the square brackets [ ]

Tuples
• tuple : type
• group of heterogeneous objects in sequence
• this is immutable modifications are not allowed.
• Declared within the parenthesis ( )
Sets
• set : type
• group of heterogeneous objects in unordered
• this is mutable modifications are allowed
• declared within brasses { }
Dictionaries
• dict : type
• It stores the data in key value pairs format.
• Keys must be unique & value • It is mutable modifications are allowed.
• Declared within the curly brasses {key:value}

Mutable and immutable Data Types:

Boolean data type : (bool)


• true& false are result values of comparison operation or logical operation in python.
• true & false in python is same as 1 & 0 , 1=true 0=false • except zero it is always True.
• while writing true & false first letter should be capital otherwise error message willbe generated.
• Comparison operations are return Boolean values
Example:
print (1 == 1) #true print (5 >
3) #true
print (True or False) #true
print(3>7) #false print
(True and False) #false

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 18


Strings Data type : (str)

• A string is a list of characters in order enclosed by single quote or double quote.


• Python string is immutable modifications are not allowed once it is created.
• In java String data combine with int data it will become String but not in python.
• String index starts from 0, trying to access character out of index range will generate IndexError.
• In python it is not possible to add any two different data types, possible to add only same data

Slice Notation
• <string_name>[startIndex:endIndex],
• <string_name>[:endIndex],
• <string_name>[startIndex:]

• s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
• s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
• s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing
• s[1:100] is 'ello' -- an index that is too big is truncated down to the string length s[-1] is 'o' - - last
char (1st from the end)
• s[-4] is 'e' -- 4th from the end
• s[:-3] is 'He' -- going up to but not including the last 3 chars.
• s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string

Example:
#a
str="ratanit" print(str[-6:-4]) #at print(str[3]) print(str[-3:]) #nit
print(str[1:3]) #at print(str[:-5]) #ra print(str[3:]) #anit print(str[:]) #ratanit
print(str[:4]) #ratan
print(str[:]) #ratanit print(str[-3]) #n

List data type : (list)


• List is used to store the group of values & we can manipulate them, in list the values are stores in
index format starts with 0;
• List is mutable object so we can do the manipulations.
• A python list is enclosed between square([]) brackets.
• In list insertion order is preserved it means in which order we inserted element same order output
is printed.
• A list can be composed by storing a sequence of different type of values separatedby commas.
<list_name>=[value1,value2,value3,...,valuen];
• The list contians forward indexing & backword indexing.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 19


Example: List data data1=[1,2,3,4] # list of
integers data2=['x','y','z'] # list of String
data3=[12.5,11.6] # list of floats
data4=[] # empty list
data5=['ramu',10,56.4,'a'] # list with mixed datatypes
Practice Examples: Accessing List
data , data1=[1,2,3,4]
data2=['tirumala','anu','deva'] print
(data1[0]) print (data1[0:3]) print
(data2[-3:-1]) print (data1[0:])
print (data2[:2])
print (data2[:])

Tuple data type : (tuple)


• tuple : type
• group of heterogeneous objects in sequence • this is immutable modifications are not
allowed.
• Declared within the parenthesis ( )
• Insertion order is preserved it means in which order we inserted the objects same order
output is printed.
• The tuple contains forward indexing & backward indexing.

Example:
tup1 = ('ratan', 'anu', 'durga') tup2
= (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d" # valid not
recommended tup4=()
tup5 = (10) #not valid
tup6 = (10,)
tup7=(1,2,3,"ratan",10.5)
print(tup1)
print(tup2) print(tup3)
print(tup4) print(type(tup5))
#<class 'int'> print(type(tup6))
#<class 'tuple'> print(tup7)
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses to help us quickly identify
tuples when we look at Python code:
>>> t = ('a', 'b', 'c', 'd', 'e')

set:

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 20


Python also includes a data type for sets. A set is an unordered collection with no duplicate elements.
Basic uses include membership testing and eliminating duplicate entries. Set objects also support
mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets.
Note: to create an empty set you have to use set(), not {}
Example:
# set of integers
my_set = {1, 2,
3} print(my_set)
print(type(my_set
)) #creates empty
set s=set() print(s)
# set of mixed datatypes my_set
= {1.0, "Hello", (1, 2, 3)}
print(my_set)
# set that have duplicates
my_set = {1,2,3,4,3,2}
print(my_set)
# Output: {1, 2, 3, 4}
Frozenset:
• It is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets.
• Frozensets can be created using the function frozenset().
• This datatype supports methods like copy(), difference(),
intersection(), isdisjoint(), issubset(),issuperset(), symmetric_difference() and union(). Being
immutable it does not have method that add or remove elements.

Dictionary data type:


• List,tupple ,set data types are used to represent individual objects as a single entity.
• To store the group of objects as a key-value pairs use dictionary.
• A dictionary is a data type similar to arrays, but works with keys and values instead of indexes.
• Each value stored in a dictionary can be accessed using a key, which is any type of object (a
string, a number, a list, etc.) instead of using its index to address it.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 21


• The keys must be unique keys but values can be duplicated.
Example:

phonebook = {}
phonebook["ramu"] = 935577566
phonebook["anu"] = 936677884 phonebook["devi"]
= 9476655551 print(phonebook)
Example:
Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = { "ramu" : 935577566, "anu" : 936677884, "devi" : 9476655551} print(phonebook)
• Dictionaries can be created using pair of curly braces ( {} ). Each item in the dictionary consist of key,
followed by a colon, which is followed by value. And each item is separated using commas (,) .
• An item has a key and the corresponding value expressed as a pair, key: value.
• In dictionary values can be of any data type and can repeat,.
• Keys must be of immutable type (string, number or tuple with immutable elements) and must be
unique.

Example:

# empty dictionary my_dict


= {}
print(my_dict)
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys my_dict =
{'name': 'John', 1: [2, 4, 3]}
print(my_dict)

Control Structures:
Algorithms require two important control structures: iteration and selection. Both of these are supported by Python in
various forms. The programmer can choose the statement that is most useful for the given circumstance
Selection Statement (Decision Structures):
Selection statements allow programmers to ask questions and then, based on the result, perform different
actions. Most programming languages provide two versions of this useful construct:
1. Simple if statement(single way selection)
2. If else statement (two way selection)
3. If – elif – else statement

1. Simple if Statemnt: Python also has a single way selection construct, the if statement. With this statement, if
the condition is true, an action is performed. In the case where the condition is false, processing simply continues on
to the next statement after the if. Its syntax is
if<condition>:
Statements

Python uses indentation to delimit the blocks of code. Other languages like C uses braces to accomplish this
task. However in python this indentation is mandatory, otherwise program will not work.

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 22


2. if - else Statement:
An if statement can also be followed by an else statement which is optional. An else statement does not
have any condition. The statements in the if block are executed if the Boolean_Expression is True,
otherwise the else block will be executed. The if…else statement used for two-way decision, that means
when we have only two alternatives. The syntax of if-else will be as follow:
if Boolean_Expression:
statements 1
else:
statements 2

3. Nested Decision Structures(if – elif –else): Actually it is short form of else if statement. When we
place if statement into if- else statement then it becomes nested if statement. The elif word is used for
this statement with the following syntax.
if<condition>:
statements
elif <condition>:
statements
elif<condition>:
statements
else:
statements
It is also has the following syntax:
if - else statement:
if<condition>:
Statements
else:
Statements
Example-1:
a=10
if(a>10): print("if
body")
else: print("else body")

Example-2: In python 0=false 1=true


if(1):
print('Hai Ramu')
else:
print('Hai Anu')
Example-3: In python Boolean constants start with uppercase character.
if(False):
print ("true body")
else:
print ("false body")

Example 4:

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 23


x = int(input("Please enter an integer: "))
if x > 0:
print ("Positive")
elif x == 0:
print ("Zero")

Example 5:
number = 23
guess = int(input("Enter an integer : "))
if guess == number:
print("Congratulations, you guessed it.")
elif guess < number:
print("No, it is a little higher number")
else:
print("No, it is a little lower number")
print("rest of the app")

M. Purnachandra Rao, Assistant Professor, Department of IT, KITS Page 24

You might also like