Python Unit 1
Python Unit 1
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.
7. Desktop applications – You can develop desktop application in Python using library like TKinter or
QT.
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.
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.
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. Cpython
2. Jython (or) Jpython.
3. Ironpython.
4. Pypy.
5. Rubypython.
6. Anaconda python.
7. Stackless
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.
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.
• 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.
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.
Multi-Line Comments in Python: We can use # at the beginning of each line of comment on multiple lines.
# 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
20 30
>>>print('values are:',10,20,30,sep="--")
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
•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.
Example 2: name='John'
salary=1000 print('hello my name is "{}" and my salary is
"{}"'.format(name,salary))
Example 5: print ('hello my name is "{n}" and my salary is "{s}"‘. format (n=name, s=salary))
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.
We need to convert an input string value into an integer using a float() function.
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
PEMDAS.
print((6 - 2) * 5)
print(6 - 2 * 5)
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:
1. Arithmetic Operators
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
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
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:
== 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.
>= 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
x = True
y = False
5. Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below
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:
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
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.
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}
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
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:
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:
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.
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 4:
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")