R20-N-Python Unit 1 - Chandu
R20-N-Python Unit 1 - Chandu
R20-N-Python Unit 1 - Chandu
PYTHON PROGRAMMING
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, Using functions and Modules.
Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision
Structures, Comparing Strings, Logical Operators, Boolean Variables.
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total, Input
Validation Loops, Nested Loops..
Introduction to python :
Python is a general-purpose High-Level, Interpreted, Interactive And Object-Oriented
Scripting Language It was created by Guido van Rossum during 1985- 1990.
o Top IT companies like google, facebook, instagram, spotify and netflix among others,use
python.
o Some Major applications :ML,AI,data science and IOT
o Major libraries: Numpy,scipy,keras tensorflow,Django & flask
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is also a developer-friendly
language.
2. Free and Open Source:
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword.
Download Python
Since it is open-source, this means that source code is also available to the public. So you can
download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk
in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to
remember the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and
also we can compile that code in C/C++ language.
7. Python is Portable language:
Python language is also a portable language. For example, if we have python code for windows
and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other
languages like c, c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like
other languages C, C++, Java, etc. there is no need to compile python code this makes it ea sier to
debug our code. The source code of python is converted into an immediate form
called bytecode.
10. Large Standard Library
Python has a large standard library which provides a rich set of module and functions so you do
not have to write your own code for every single thing. There are many libraries present in
python for such as regular expressions, unit-testing, web browsers, etc.
11. Dynamically Typed Language:
Python is a dynamically-typed language. That means the type (for example- int, double, long,
etc.) for a variable is decided at run time not in advance because of this feature we don’t need to
specify the type of variable.
Installing Python
During installation, it will show the various components it is installing and move the progress bar
towards completion. Soon, a new Python 3.9.5 (64-bit) Setup pop-up window will appear with
a Setup was successfuly message.
Python should now be installed.After installing Python in Windows, you can start Python in two
different modes, viz., Python (Command Line) and Python (IDLE).
interactive shell:
In Python, there are two options/methods for running code:
Interactive mode
Script mode
Interactive Mode :
Interactive mode is a command line shell. Typically the interactive mode is used to test the
features of the python, or to run a smaller script that may not be reusable.
Batch Mode or script mode :
Batch mode is mainly used to develop business applications. In batch mode, we can write a
group of python statements in any one of the following editors or IDEs
Editors : Notepad,Notepad++,editPlus,nano,gedit,IDLE,Etc..
IDEs :pycharm,Eric,Eclipse,Netbeans Etc..
1) Interactive Mode: Python provides Interactive Shell to execute code immediatly and
produce output instantly. To get into this shell, write python in the command prompt and start
working with Python.
Press Enter key and the Command Prompt will appear like:
2.Script Mode:Using Script Mode, we can write our Python code in a separate file of any
editor in our Operating System.
NOTE: Path in the command prompt should be location of saved file.where you have saved
your file. In the above case file should be saved at desktop.
We can execute our Python code using a Graphical User Interface (GUI). We can use both
Interactive as well as Script mode in IDE.
1) Interactive Mode
We type Python expression / statement / command after the prompt (>>>) and Python
immediately responds with the output of it.
Executing first program on Python
1) Let’s start with typing print “Hello Python!” after the prompt.
>>>print("Hello Python!")
Output: Hello Python!
Step 3: A Python program is executed only after it is saved with a specific file name. You can
give any name to the file. However, the file name should end with .py
Step 4:To run the Python program, click on Run and then Run Module. Alternatively, just press
CTRL + F5 to run the program.
1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the problem. In
this phase we need to understand the problem statement, what is our requirement, what should be
Chandra Sekhar Koppireddy, CSE Dept Pragati Engineering College (A)
R20 PYTHON PROGRAMMING UNIT 1
the output of the problem solution. These are defined in this first phase of the program
development life cycle.
2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem.
That means we gather the required resources to solve the problem defined in the problem
definition phase. We also determine the bounds of the solution.
3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program development.
That means we write the solution in step by step statements.
enhancement, then we need to repeat all the phases from the starting, so that the encountered
problem is solved or enhancement is added.
Input, Processing, and Output
input …. is something the program receives, usually from the user or from a file.
Processing…is what happens when the program does something with the input.
Output…. is something the program produces, usually to a screen, to a file, or to both.
The input function is used in all latest version of the Python. It takes the input from the user and
then evaluates the expression. The Python interpreter automatically identifies the whether a user
input a string, a number, or a list. Let's understand the following example.
Example –1
>>> name=input("enter your name:")
enter your name:sai
>>> print(name)
sai
>>>
Python Input
To allow flexibility, we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is:
input([prompt])
Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
>>> print(marks)
90.0
>>> print(age)
19
>>> print(name)
sai
Displaying Output with the Print Function
We use the print() function to output data to the standard output device (screen). .
An example of its use is given below.
print('This sentence is output to the screen')
Output
The value of a is 5
In the second print() statement, we can notice that space was added between the string and the
value of variable a. This is by default, but we can change it.
The actual syntax of the print() function is:
sep=‘separator’: (Optional) Specify how to separate the objects, if there is more than one.
Default: ‘ ’
end=‘end’: (Optional) Specify what to print at the end. Default : ‘\n’
file: (Optional) An object with a write method. Default :sys.stdout
flush: (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Python automatically flushes the files when closing them. But you may want to flush the data
before closing any file.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
We can also format strings like the old sprintf() style used in C programming language. We use
the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
reading a comment you can understand the purpose of code much faster then by just going
through the actual code.
.
# This is just a text, it won't be executed.
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a
multi-line comment as well.
'''
This is a
multi-line
comment
'''
Python Comments Example
In this Python program we are seeing three types of comments. Single line comment, multi-line
comment and the comment that is starting in the same line after the code.
'''
We are writing a simple program here
Docstrings in Python
A docstring is short for documentation string.
Python docstrings (documentation strings) are the string literals that appear right after the
definition of a function, method, class, or module.
Triple quotes are used while writing docstrings. For example:
def double(num):
"""Function to double the value"""
return 2*num
Docstrings appear right after the definition of a function, class, or a module. This separates
docstrings from multiline comments using triple quotes.
The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following lines of code:
def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
Run Code
Output
Tokens:
o The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.
o The token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers.
o Literals.
o Operators.
Python Keywords (Reserved Words )
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier. .
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly over the course of
time. There are 35 keywords in Python 3.8
All the keywords except True, False and None are in lowercase and they must be written as
they are.
Python Keywords
False def if raise
None del import return
True elif in try
And else is while
As except lambda with
Assert finally nonlocal yield
Break for not async
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
The first character of the variable must be an alphabet or underscore ( _ )..
Chandra Sekhar Koppireddy, CSE Dept Pragati Engineering College (A)
R20 PYTHON PROGRAMMING UNIT 1
It is recommended to use lowercase letters for the variable name. Rahul and rahul both
are two different variables.
Variables in Python are not subject to this restriction. In Python, a variable may be
assigned a value of one type and then later re-assigned a value of a different type:
>>> var = 23.5
>>> print(var)
23.5
>>> var = "Now I'm a string"
>>> print(var)
Now I'm a string
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
The first character of the variable must be an alphabet or underscore ( _ ).
All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
An identifier can be of any length.
Multiple words can be separated using an underscore, like this_is_a_long_variable
Identifier name must not contain special character (!, @, #, %, ^, &, *).
Keywords cannot be used as identifiers
Examples of valid identifiers: a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.
global = 1
Output
File "<interactive input>", line 1
global = 1 SyntaxError: invalid syntax
Declaring Variable and Assigning Values:
In Python,to create a variable, you just assign it a value and then start using it. Assignment is
done with a single equals sign (=)
We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments..
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
Chandra Sekhar Koppireddy, CSE Dept Pragati Engineering College (A)
R20 PYTHON PROGRAMMING UNIT 1
print(y)
print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
Plus and concatenation operation on the variables
x = 10
y = 20
print(x + y)
p = "Hello"
q = "World"
print(p + " " + q)
Output:
30
Hello World
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.
Indentation in Python refers to the (spaces and tabs) that are used at the
beginning of a statement. The statements with the same indentation belong to the same group
called a suite. Consider the example of a correctly indented Python code statement mentioned
below.
Ex:
if a==1:
print(a)
if b==2:
print(b)
print('end')
In the above code, the first and last line of the statement is related to the same suite because there
is no indentation in front of them. So after executing first "if statement", the Python interpreter
will go into the next statement. If the condition is not true, it will execute the last line of the
statement
input ( prompt )
raw_input ( prompt )
input ( ) : This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a number or list.
If the input provided is not correct then either syntax error or exception is raised by python.
For example –
# Python program showing
# a use of input()
val = input("Enter your value: ")
print(val)
Output:
raw_input ( ) : This function works in older version (like Python 2.x). This function takes
exactly what is typed from the keyboard, convert it to string and then return it to the variable in
which we want to store. For example –
# Python program showing
# a use of raw_input()
g = raw_input("Enter your name : ")
print g
Output :
Here, g is a variable which will get the string value, typed by user during the execution of
program. Typing of data for the raw_input() function is terminated by enter key. We can
use raw_input() to enter numeric data also. In that case we use typecasting.For more details on
typecasting refer this.
Performing Calculations
Here, 9 is integer, and 5.0 is float, then the less general type that is int will be
converted into more general type that is float and the entire expression will result in
float value.
We can even use eval () function to perform calculation at the interpreter. The
expression is written inside the single quotes. For example:
number = 9
print(square_number)
# Output: 81
eval() Syntax
The syntax of eval() is:
eval() Parameters
The eval() function takes three parameters:
expression - the string parsed and evaluated as a Python expression
globals (optional) - a dictionary
locals (optional)- a mapping object. Dictionary is the standard and commonly used
mapping type in Python.
x=1
print(eval('x + 1'))
Output
Here, the eval() function evaluates the expression x + 1 and print is used to display this value.
Python Operators:
The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language.
A sequence of operands and operators, like a + b - 5, is called an Expression. Python
supports many operators for combining data objects into expressions.
Python provides a variety of operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators: Arithmetic operators are used to perform arithmetic operations between
two operands. It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**) operators.
Operator Meaning Example
x%y
Modulus - remainder of the division of left operand by
% (remainde
the right
r of x/y)
x**y (x to
** Exponent - left operand raised to the power of right the power
y)
Comparison operators:
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly. The comparison operators are described in the following table..
Operator Meaning Example
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
Logical operators
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.
Operator Meaning Example
A B A or B A and B
True False
False True
Bitwise operators
The bitwise operators perform bit by bit operation on the values of the two operands
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print ("Line 1 - Value of c is ", c)
c = a | b; # 61 = 0011 1101
print ("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print ("Line 3 - Value of c is ", c)
Assignment operators
Assignment operators are used in Python to assign values to variables. The assignment operators
are used to assign the value of the right expression to the left operand. The assignment operators
are described in the following table.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the
left. There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x–5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print( "Line 3 - Value of c is ", c)
c **= a
print ("Line 4 - Value of c is ", c)
c //= a
print ("Line 5 - Value of c is ", c)
output:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 2097152
Line 5 - Value of c is 99864
Special operators
Python language offers some special types of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators:
The identity operators are used to decide whether an element certain class or type.
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.
Example1:
a = 20
b = 20
if ( a is b ):
print ("Line 1 - a and b have same identity")
else:
print ("Line 1 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
output:
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Membership operators
Python membership operators are used to check the membership of value inside a Python data
structure(string, list, tuple, set and dictionary). If the value is present in the data structure, then
the resulting value is true otherwise it returns false..
in and not in are the membership operators in Python. They are used to test whether a value or
variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similarly, 1 is
key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Type conversions
Data conversion in Python can happen in two ways: either you tell the compiler to convert a
data type to some other type explicitly, or the compiler understands this by itself a nd does it for
you
There are two-types of type-conversions in Python:
Explicit Conversion: In explicit conversion, users convert the data type in to their required type
using int(), float(), str(), etc.
The general form of an explicit data type conversion is as follows:
(required_data_type)(expression)
Implicit Conversion: In implicit conversion, the python interpreter itself converts the lower data
type to greater data type
example:
a_int = 1
b_float = 1.0
c_sum = a_int + b_float
print(c_sum)
print(type(c_sum))
Python String to Int Conversion
It is crucial for a developer to know the different Python Data types and conversions between
them. Let’s take Python String to Int conversion itself, whenever we get the input from the user
we typically use the input() function
The input() function reads a data entered by the user and converts it into a string and returns it.
Even though the user has entered a numeric value, it will be automatically converted
to String by Python, which cannot be used directly for any manipulation.
For example, if we want to divide the number entered by the user by 2.
>>> num = input("Enter a number : ")
Enter a number : 10
>>> num
'10'
The value stored inside num is not an integer 10 but the string ’10’. Let’s check the type
of num for a confirmation.
>>> type(num)
<class 'str'>
If we try to divide the num by 2, we will get an Unsupported operand type error.
>>> print( num /2)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in
int(x) – Returns the integer objects constructed from the argument passed, it returns 0 if
no argument is passed. It will create an integer object with the default base 10 (decimal).
int (x, base) – This method also returns the integer object with the
corresponding base passed as the argument.
Let’s try to fix the issue which has happened in the above code. All we need to do is to just pass
the num variable to the int() function to get it converted to an integer.
>>> num = int(num)
>>> type(num)
<class 'int'>
>>> print(num /2)
5.0
Python Int to String Conversion
Converting a Python Int to String is pretty straight forward, we just need to pass the integer to
the str() function. We don’t have to worry about the type of number or its bases.
>>> num = 13
>>> strNum = str(num)
>>> strNum
'13'
Python built-in functions bin(), oct(), or hex() can be used to convert an integer to a binary, octal,
or hexadecimal string respectively.
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal."
Output:
Enter a decimal number: 10
0b1010 in binary.
0o12 in octal.
0xa in hexadecimal.
Python Expressions:
Expression: An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to produce a
value.
Example:
a+b
c
s-1/7*f
.
.
etc
Expressions are representations of value. They are different from statement in the fact that
statements do something while expressions are representation of value. For example any string is
also an expressions since it represents the value of the string as well.
Python has some advanced constructs through which you can represent values and hence these
constructs are also called expressions.
Python expressions only contain identifiers, literals, and operators. So, what are these?
Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals,
floating point literals, and imaginary literals.
For example, the following code will get all the number within 10 and put them in a list.
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and will keep the
corresponding squares of those numbers as the values.
Generator expression
For example, the following code will initialize a generator object that returns the values within
10 when the object is called.
>>> (x for x in range(10))
<generator object <genexpr> at 0x7fec47aee870>
>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Conditional Expressions
Example:
>>> x = "1" if True else "2"
>>> x
'1'
The following table lists all operators from highest precedence to lowest.
Operator Description
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom.
Example
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print( "Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print( "Value of ((a + b) * c) / d is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
result :
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
Parameters:
value(s): Any value, and as many as you like. Will be converted to string before printed.
sep=’separator’: (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
Example:
>>>print(10,20,30,40,sep='-',end='&’)
Output:
10-20-30-40&
>>>print('apple',1,'mango',2,'orange',3,sep='@',end='#’)
Output:
apple@1@mango@2@orange@3#
Even though there are different ways to print values in Python, we discuss two major
string formats which are used inside the print() function to display the contents onto
the console.
str.format() method
f-strings
str.format() –this function is used to insert value of a variable into another string and
display it as a single string.
Positional arguments are accessed using the index, and keyword arguments are
accessed using the name of the argument.
dataoutput.py Output
#more about data output Enter your country india I
country=input('Enter your country') print('I Love my india
Love my { }'.format(country))
Where { } are called placeholder. The value of the variable is placed inside the
placeholder according to the position. The arguments are placed according to their
position.
dataout.py Output
branch=input('Enter branch name') Enter branch name CSE
Enter the year of study 2
year=int(input('Enter the year of study')) The branch name is CSE
and the year is 2
print('The branch name is {0} and the year is
{1}'.format(branch,year))
dataout1.py
Output:
Using f-string
Dataout2.py
study'))
Output
year of study 2
String(immutable variables)
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines
string.
There are two ways to create multiline strings:
1) Adding black slash at the end of each line.
Example:
text1='hello\
user'
print(text1)
'hellouser'
2) Using triple quotation marks:-
Example:
str2='''''welcome
to
SSSIT'''”
print str2
Output:
welcome
to
SSSIT
EscapeSequence
The newline character \n is called as escape sequence. Escape sequences are the
way Python expresses special characters, such as the tab, the newline, and the
backspace (delete key), as literals.
Comment
A comment is a piece of program text that the interpreter ignores but that
provides useful documentation to programmers. At the very le ast, the author of
a program can include his or her name and a brief statement about the purpose
of the program at the beginning of the program file. This type of comment,
called a docstring, is a multi-line string. This can be written inside Triple
double quotes or Triple single quotes. In addition to docstrings, end-of-line
comments can document a program. These comments begin with the # symbol
and extend to the end of a line.
End-of-line
Docstring
# read word from keyboard
"""
"""
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type.
Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular
class.
Python supports three types of numeric data.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc
For example;
a=5
print("The type of a", type(a))
print(" a is a integer number", isinstance(a,int))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
a is a integer number:True
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number
We can use the slicing operator [ ] to extract an item or a range of items from a list. The index
starts from 0 in Python.
Example:
a = [5,10,15,20,25,30,35,40]
print("a[2] = ", a[2])
print("a[0:3] = ", a[0:3])
print("a[5:] = ", a[5:])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the value of elements of a list can be altered.
Example:
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
2.3 Python Tuple(immutable variables)
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot change
dynamically.
Syntax:Syntax:
tuple = (value1, value2, value3,...valueN)
t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
Example:
t = (5,'program', 1+3j)
print("t[1] = ", t[1])
print("t[1:] = ", t[1:])
print("t[0:3] = ", t[0:3])
# Tuple concatenation using + operator
print (t + t)
# Tuple repatation using * operator
print (t * 3)
t[0] = 10
Output
t[1] = program
t[1:] = ('program', (1+3j))
t[0:3] = (5, 'program', (1+3j))
(5, 'program', (1+3j), 5, 'program', (1+3j))
(5, 'program', (1+3j), 5, 'program', (1+3j), 5, 'program', (1+3j))
Traceback (most recent call last):
t[0] = 10
TypeError: 'tuple' object does not support item assignment
3.Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of any type.
Syntax:Syntax:
dict = { key1:value1, key2:value2,...keyN:valueN }
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
Example:
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ", d[2]);
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
4.Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be represented
by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Example:
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
5.Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
Example:
a = {5,2,3,1,4}
# printing set variable
print("a = ", a)
# data type of variable a
print(type(a))
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets have unique values.
They eliminate duplicates.
Example:
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator [] does
not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
For example, the argument in the function call round(6.6) is the value 6.6, and the value
returned is 7. When an argument is an expression, it is first evaluated, and then its value
is passed to the function for further processing. For instance, the function call abs(4– 5)
first evaluates the expression 4 - 5 and then passes the result,-1, to abs. Finally, abs
returns 1.
Functions and other resources are placed in components called modules. Functions like
abs() and round() from the builtin module are always available for use, whereas
the programmer must explicitly import other functions from the modules where they are
defined. The math module includes several functions that perform basic mathematical
operations
Python Import
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
Output
3.141592653589793
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
Decision making is the most important aspect of almost all the programming
languages. The decisions are made on the validity of the particular conditions.
Condition checking is the backbone of decision making.
Conditional Statement in Python perform different actions depending on whether
a specific Boolean constraint or condition evaluates to true or false.
If Statement The if statement is used to test a specific condition. If the condition is true,
a block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.
If-elif-else The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. .
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block.
The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
The syntax of the if-statement is given
below.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
enter the number?10
Number is even
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
Example 1 Example 2
number = int(input("Enter the number?")) marks = int(input("Enter the marks? "))
if number==10: if marks > 85 and marks <= 100:
print("number is equals to 10") print("Congrats ! you scored grade A ...")
elif number==50: elif marks > 60 and marks <= 85:
print("number is equal to 50"); print("You scored grade B + ...")
elif number==100: elif marks > 40 and marks <= 60:
print("number is equal to 100"); print("You scored grade B ...")
else: elif (marks > 30 and marks <= 40):
print("number is not equal to 10, 50 or print("You scored grade C ...")
100"); else:
print("Sorry you are fail ?")
Output:
Enter the number?15
number is not equal to 10, 50 or 100
Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to
figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
Syntax: Flowchart:
if ( test condition 1):
if ( test condition 2):
Test condition 2 True statements
else:
Test condition 2 False statements
else:
Test condition 1 False statements
Example:input a number check if the number is positive or negative or zero and display
an appropriate message .
num = float(input("Enter a number: ")) Output 1
if num >= 0: Enter a number: 5
if num == 0: Positive number
print("Zero") Output 2
else: Enter a number: -1
print("Positive number") Negative number
else: Output 3
print("Negative number") Enter a number: 0
Zero
Comparing Strings :
To compare two strings, we mean that we want to identify whether the two strings are equivalent
to each other or not, or perhaps which string should be greater or smaller than the other.
String equality is compared using == (double equal sign). This comparison process
is carried out as follow:
First two characters (j and j) from the both the strings are compared using
the ASCII values.
Since both ASCII values are same then next characters (a and a) are
compared. Here they are also equal, and hence next characters (n and n)
from both strings are compared.
True
True
False
False
Boolean Variables
The variables that store Boolean value either True or False called Boolean variables.
If the expression is returning a Boolean value then it is called Boolean expression.
The Boolean data type can be one of two values, either True or False. Named for the
mathematician George Boole, the word Boolean always begins with a capitalized B. The
values True and False will also always be with a capital T and F respectively.
Boolean logic is implemented with Comparison operators and logical operators
BOOLEAN WITH COMPARISION OPERATORS:Comparison operators are used to compare
values and evaluate down to a single Boolean value of either True or False.
Conditional
Meaning of Condition
Operator
== Equal to
!= Not equal to
Program:
a = 30
b = 45
if(a > 30 and b == 45):
print("True")
else:
print("False")
output: False
Or Boolean Operator in Python
The OR operator is similar to the OR bitwise operator. In the bitwise OR, we were focussing
on either of the bit being 1. Here, we take into account if either of the expression is true or not. If
at least one expression is true, consequently, the result is true.
True or True = True
True or False = True
False or True = True
False or False = False
Program:
a = 25
b = 30
if(a > 30 or b < 45):
print("True")
else:
print("False")
output: True
NOTE: You can directly use the word “and ” instead of “&&” to denote the “and ” boolean
operator
bool() function:
The bool() function allows you to evaluate any value, and give you True or False in return,
Example:
print(bool("sai"))- True
print(bool(9))- True
Repetition Structures
Python loops:
In python ,loops statements are used to execute the block of code repeatedly for a
specified number of times or until it meets a specified condition.
Loops are used in programming to repeat a specific block of code.
A loop is a used for iterating over a set of statements repeatedly.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement −
Example WHILE
i=1 i=1
while i < 4: while i < 4:
print(i) print(i)
i+=1 i+=1
print('END')
print('END')
1
1
END
2 2
3 END
END 3
END
Chandra Sekhar Koppireddy, CSE Dept Pragati Engineering College (A)
R20 PYTHON PROGRAMMING UNIT 1
count = 0
while (count == 0): print("Hello Geek")
Note: It is suggested not to use this type of loops as it is a never ending infinite loop where the
condition is always true and you have to forcefully terminate the compiler.
For loop:
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
We use for loop when we know the number of times to iterate.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Example:
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
output:
The sum is 48
Function range()
In the above example, we have iterated over a list using for loop. However we can also use a
range() function in for loop to iterate over numbers defined by range().
range(n): generates a set of whole numbers starting from 0 to (n-1).
For example: range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
Chandra Sekhar Koppireddy, CSE Dept Pragati Engineering College (A)
R20 PYTHON PROGRAMMING UNIT 1
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify
the step_size, the numbers generated are having difference of 1. However by specifying
step_size we can generate numbers having the difference of step_size.
For example: range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
ex: we are using range() function to calculate and display the sum of first 5 natural numbers.
# Program to print the sum of first 5 natural numbers
sum = 0
# iterating over natural numbers using range()
for val in range(1, 6):
sum = sum + val
# displaying sum of first 5 natural numbers
print(sum)
Output: 15
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
output :
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it
executes the block of code in the else and prints No items left.
Calculating a Running Total
We can calculate the sum of input numbers while entering from the keyboard as demonstrated in
the following example.
n=int(input('Enter n:'))
sum=0
for i in range(n):
data=float(input('Enter value'))
sum=sum+data
#display sum
print('Sum is:',sum)
Output:
When we accept user input we need to check that it is valid. This checks to see that it is the sor
t of data we were expecting.
Use a flag variable. This will initially be set to False. If we establish that we have the correct i
nput then we set the flag to True. We can now use the flag to determine what we do next (for i
nstance, we might repeat some code, or use the flag in an if statement).
Syntax
Using a flag
flagName = False
while not flagName:
if [Do check here]:
flagName = True
else:
print('error message')
Example:A length check using a flag
isLongEnough = False
while not isLongEnough:
password = input('Enter password at least 5 characters: ')
if len(password) >= 5:
isLongEnough = True
else:
print('Password entered is too short')
1 , 11 1,5
1 , 12 2,6
1 , 13 3,7
2 , 10
2 , 11
2 , 12
2 , 13
----------------------------******--------------------------------