Ise36 - Modul1 - I PDF
Ise36 - Modul1 - I PDF
FUNDAMENTALS
MR.GANGADHAR IMMADI
Department of ISE,NHCE
MODULE I: FUNDAMENTALS
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS
MODULE I : INTRODUCTION
1.1 INTRODUCTION:
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
Simple− Python has few keywords, simple structure, and a clearly defined syntax.Python
code is more clearly defined and visible to the eyes.Python's source code is fairly easy-
to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Object Oriented – Python supports object oriented features such as Encapsulation,
Polymorphism, Inheritance and data hiding. Encapsulation is wrapping up of data and
methods together. Polymorphism is having more than one form and Inheritance is one
object aquires the properties of other type.
Embedable - C, C++ are also used in embedded systems. But, these programming
languages are slow, error prone and frequently unreadable. Because of these
disadvantages, many embedded programmers have switched their choice to Python.Error
reduction, readability and simple structure makes Python the best choice for embedded
systems.
Robust - Python is a solid, powerful and robust programming language which includes
automatic memory management, exception handling etc. This is one of the reasons why
some of the leading organizations across the globe such as Bank of America, Reddit,
Quora, Google, YouTube, DropBox, for example, have chosen it to power some of their
most critical systems.
Intergrated: Python integrates the Enterprise Application Integration that makes it easy
to develop Web services by invoking COM or COBRA components. It has powerful control
capabilities as it calls directly through C, C++ or Java via Jython. Python also processes
XML and other markup languages as it can run on all modern operating systems through
same byte code.
Databases – Python facilitates the interaction with popular databases for building
applications.
Web Development - frameworks and environments allow Web developers to be more
productive and efficient on Python than with other languages. This is a critical factor when
you need to bring applications to final deployment right away. Django is the most popular
web framework for Python. Flask and Pyramid are two other popular frameworks.Other Python
web frameworks include Zope2, Grok, web2py, and TurboGears.
GUI Programming - Python has a huge number of GUI frameworks (or toolkits) available
for it, from TkInter (traditionally bundled with Python, using Tk) to a number of other
cross-platform solutions, as well as bindings to platform-specific (also known as "native")
technologies.
• Linux distributions use installers written in Python -Python is often an integral part of
Linux distributions. For instance, Ubuntu’s Ubiquity Installer, and Fedora’s and Red Hat
Enterprise Linux’s Anaconda Installer are written in Python.
• Information security industry – Python is intensively used in cyber security domain.
Everything from testing microchips at Intel, to powering Instagram, to building video
games with PyGame, Python is the most sought after programming language for its
power packed capabilities.
• Raspberry Pi - The Raspberry Pi is a low cost, credit-card sized computer that plugs into
a computer monitor or TV, and uses a standard keyboard and mouse. It is a capable
little device that enables people of all ages to explore computing, and to learn how to
program in languages like Scratch and Python. Python is a wonderful and powerful
programming language that's easy to use (easy to read and write) and, with Raspberry
Pi, lets you connect your project to the real world.
• Game Development - You can write whole games in Python using PyGame. See a list of
other PythonGameLibraries maintained in this Wiki, or this list maintained on
DevMaster.net. A full tutorial can be found in the free book "Making Games with
Python & Pygame".
• Web Development - Python has been used to create a variety of web-frameworks
including CherryPy, Django, TurboGears, Bottle, Flask etc.
1.4 CODE TRANSLATION IN PYTHON
Python first compiles your source code (.py file) into a format known as byte code .
Compilation is simply a translation step, and byte code is a lower-level, and platform-
independent, representation of your source code. Compiled code is usually stored in .pyc files ,
and is regenerated when the source is updated, or when otherwise necessary. In order to
distribute a program to people who already have Python installed, you can ship either the .py
files or the .pyc files.
The bytecode (.pyc file) is loaded into the Python runtime and interpreted by a Python Virtual
Machine , which is a piece of code that reads each instruction in the bytecode and executes
whatever operation is indicated. Byte code compilation is automatic, and the PVM is just part
of the Python system that you have installed on your machine. The PVM is always present as
part of the Python system , and is the component that truly runs your scripts. Technically, it's
just the last step of what is called the Python interpreter. And this is how the process is done
(very general). Of course, there are optimizations and caches to improve the performance.
Each time an interpreted program is run, the interpreter must convert source code into
machine code and also pull in the runtime libraries . This conversion process makes the
program run slower than a comparable program written in a compiled language. Python do
something clever to improve its performance . It compiles to bytecode (.pyc files) the first time
it executes a file. This improves substantially the execution of the code next time the module is
imported or executed.
Operating System they are using. Because, there are separate set of editors (IDE)
available for different OS like Window, UNIX, Ubuntu, Soloaris, Mac, etc. The basic Python can
be downloaded from the link:
https://www.python.org/downloads/
Python has rich set of libraries for various purposes like large-scale data processing,
predictive analytics, scientific computing etc. Based on one’s need, the required packages can
be downloaded. But, there is a free open source distribution Anaconda, which simplifies
package management and deployment. Hence, it is suggested for the readers to install
Anaconda from the below given link, rather than just installing a simple Python.
https://anaconda.org/anaconda/python
Successful installation of anaconda provides you Python in a command prompt, the default
editor IDLE and also a browser-based interactive computing environment known as jupyter
notebook.
The jupyter notebook allows the programmer to create notebook documents including
live code, interactive widgets, plots, equations, images etc. To code in Python using
jupyter notebook, search for jupyter notebook in windows search (at Start menu). Now, a
browser window will be opened similar to the one shown in Figure below
You can choose the working directory of your choice for storing your work. To open a
notebook for Python programming, click on New button at the right-side of the screen. Now
select Python 3 from the drop-down list. A new notebook (or workbook will be created
as shown in above figure. Type a command of your choice and press Ctrl+Enter to run
that command. One can give headings/subheadings etc for the commands being typed,
store the entire workbook for future reference etc. Readers are advised to try and
experience various options/menu’s available.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to
install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save
the installer file to your local machine and then run it to find out if your machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just
accept the default settings, wait until the install is finished, and you are done.
The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and
other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).
Example of Python Installation Directory –
Once Python is installed, one can go ahead with working with Python. Use the IDE of
yourchoice for doing programs in Python. After installing Python (or Anaconda
distribution), if you just type ‘python’ in the command prompt, you will get the message as
shown in Figure below. The prompt >>> (usually called as chevron) indicates the system is
ready to take Python instructions. If you would like to use the default IDE of Python,
that is, the IDLE, then you can just run IDLE and you will get the editor as shown
>>> help()
Welcome to Python 3.7's help utility!
If this is your first time using Python, you should definitely check out the tutorial on the
Internet at https://docs.python.org/3.7/tutorial/. Enter the name of any module, keyword, or
topic to get help on writing Python programs and using Python modules. To quit this help
utility and return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes with a one-line
summary of what it does; to list the modules whose name or summary contain a given string
such as "spam", type "modules spam".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class rom or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help> symbols
Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.
!= + <= __
" += <> `
""" , == b"
% - > b'
%= -= >= f"
& . >> f'
&= ... >>= j
' / @ r"
''' // J r'
( //= [ u"
) /= \ u'
* : ] |
** < ^ |=
**= << ^= ~
*= <<= _
help> quit
You are now leaving help and returning to the Python interpreter. If you want to ask for help
on a particular object directly from the interpreter, you can type "help(object)". Executing
"help('string')" has the same effect as typing a particular string at the help> prompt.
>>>
1.7 WORDS AND SENTENCES
Every programming language has its own constructs to form syntax of the language. Basic
constructs of a programming language includes set of characters and keywords that it
supports. The keywords have special meaning in any language and they are intended for doing
specific task. Python has a finite set of keywords as given in Table below.
1.8 TERMINOLOGY
1.8.1 INTERPRETER AND COMPILER
All digital computers can understand only the machine language written in terms of zeros
and ones. But, for the programmer, it is difficult to code in machine language. Hence, we
generally use high level programming languages like Java, C++, PHP, Perl, JavaScript etc. Python
is also one of the high level programming languages. The programs written in high level
languages are then translated to machine level instruction so as to be executed by CPU.
How this translation behaves depending on the type of translators viz. compilers and
interpreters.
A compiler translates the source code of high-level programming language into machine
level language. For this purpose, the source code must be a complete program stored in a file
(with extension, say, .java, .c, .cpp etc). The compiler generates executable files (usually
with extensions .exe, .dll etc) that are in machine language. Later, these executable files
are executed to give the output of the program.
On the other hand, interpreter performs the instructions directly, without requiring them
to be pre-compiled. Interpreter parses (syntactic analysis) the source code ant interprets
it immediately. Hence, every line of code can generate the output immediately, and the
source code as a complete set, need not be stored in a file. That is why, in the
previous section, the usage of single line print(“Hello World”) could able to generate the
output immediately.
Consider an example of adding two numbers –
>>> x=10
>>> y=20
>>> z= x+y
>>> print(z)
30
Here, x, y and z are variables storing respective values. As each line of code above is processed
immediately after the line, the variables are storing the given values. Observe that,
though each line is treated independently, the knowledge (or information) gained in the
previous line will be retained by Python and hence, the further lines can make use of
previously used variables. Thus, each line that we write at the Python prompt are logically
related, though they look independent.
NOTE that, Python do not require variable declaration (unlike in C, C++, Java etc) before its use.
One can use any valid variable name for storing the values. Depending on the type (like
number, string etc) of the value being assigned, the type and behavior of the variable name is
judged by Python.
1.8.2 Writing a Program
As Python is interpreted language, one can keep typing every line of code one after the
other (and immediately getting the output of each line) as shown in previous section. But, in
real-time scenario, typing a big program is not a good idea. It is not easy to logically debug such
lines. Hence, Python programs can be stored in a file with extension .py and then can be run.
Programs written within a file are obviously reusable and can be run whenever we want. Also,
they are transferrable from one machine to other machine via pen-drive, CD etc.
1.8.3 What is a Program?
A program is a sequence of instructions intended to do some task. For example, if we need to
count the number of occurrences of each word in a text document, we can write a
program to do so. Writing a program will make the task easier compared to manually
counting the words in a document. Moreover, most of the times, the program is a generic
solution. Hence, the same program may be used to count the frequency of words in
another file. The person who does not know anything about the programming also can run this
program to count the words.
Programming languages like Python will act as an intermediary between the computer and the
programmer. The end-user can request the programmer to write a program to solve
one’s problem.
1.9 THE BUILDING BLOCKS OF PROGRAMS
There are certain low-level conceptual structures to construct a program in any
programming language. They are called as building-blocks of a program and listed below –
1. Input: Every program may take some inputs from outside. The input may be through
keyboard, mouse, disk-file etc. or even through some sensors like microphone, GPS etc.
2. Output: Purpose of a program itself is to find the solution to a problem. Hence,
every program must generate at least one output. Output may be displayed on a
monitor or can be stored in a file. Output of a program may even be a music/voice
message.
3. Sequential Execution: In general, the instructions in the program are sequentially
executed from the top.
4. Conditional Execution: In some situations, a set of instructions have to be executed
based on the truth-value of a variable or expression. Then conditional constructs (like
if) have to be used. If the condition is true, one set of instructions will be executed and if
the condition is false, the true-block is skipped.
5. Repeated Execution: Some of the problems require a set of instructions to be
repeated multiple times. Such statements can be written with the help of looping
structures like for, while etc.
6. Reuse: When we write the programs for general-purpose utility tasks, it is better to write
them with a separate name, so that they can be used multiple times
whenever/wherever required. This is possible with the help of functions.
The art of programming involves thorough understanding of the above constructs and using
them legibly.
1.10 WHAT COULD POSSIBLY GO WRONG (POSSIBLE ERRORS)
It is obvious that one can do mistakes while writing a program. The possible mistakes are
categorized as below –
Syntax Errors: The statements which are not following the grammar (or syntax) of the
programming language are tend to result in syntax errors. Python is a case-sensitive
language. Hence, there is a chance that a beginner may do some syntactical mistakes
while writing a program. The lines involving such mistakes are encountered by the Python
when you run the program and the errors are thrown by specifying possible reasons for the
error. The programmer has to correct them and then proceed further.
Logical Errors: Logical error occurs due to poor understanding of the problem.
Syntactically, the program will be correct. But, it may not give the expected output.
For example, you are intended to find a%b, but, by mistake you have typed a/b.
Then it is a logical error.
Semantic Errors: A semantic error may happen due to wrong use of variables, wrong
operations or in wrong order. For example, trying to modify un-initialized variable etc.
NOTE: There is one more type of error – runtime error, usually called as exceptions. It may
occur due to wrong input (like trying to divide a number by zero), problem in database
connectivity etc. When a run-time error occurs, the program throws some error, which may
not be understood by the normal user. And he/she may not understand how to overcome
such errors. Hence, suspicious lines of code have to be treated by the programmer
himself by the procedure known as exception handling. Python provides mechanism for
handling various possible exceptions like ArithmeticError, FloatingpointError, EOFError,
MemoryError etc.
Type the following text at the Python prompt and press the Enter −
If you are running new version of Python, then you would need to use print statement with
parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the
following result −
Hello, Python!
print("Hello, Python!")
We assume that you have Python interpreter set in PATH variable. Now, try to run this
program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Classification:
1.12.1 NUMBERS
Number data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −
del var1,var2,var3,……var-n
You can delete a single object or multiple objects by using the del statement. For example −
del var
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers −
Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
1.12.2 STRINGS
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −
1.12.3 LISTS
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One difference between them is that all the items belonging to a list can be of different
data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the
list concatenation operator, and the asterisk (*) is the repetition operator. For example −
1.12.4 TUPLES
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists. For example −
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
1.12.5 DICTIONARY
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces (*+). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print(dict['one']) # Prints value for 'one' key
print(dict[2]) # Prints value for 2 key
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.
The complex() method returns a complex number when real and imaginary parts are provided, or it
converts a string to a complex number.
In general, the complex() method takes two parameters:
real - real part. If real is omitted, it defaults to 0.
Example: Output:
z = complex(2, -3)
print(z) (2-3j)
z = complex(1) (1+0j)
print(z) 0j
z = complex() (5-9j)
print(z)
z = complex('5-9j')
print(z)
Example: Output:
a = 2+3j
a = (2+3j)
print('a =',a)
Type of a is <class 'complex'>
print('Type of a is',type(a))
b = (-0-2j)
b = -2j
Type of b is <class 'complex'>
print('b =',b)
c = 0j
print('Type of b is',type(a))
Type of c is <class 'complex'>
c = 0j
print('c =',c)
print('Type of c is',type(c))
The None keyword is used to define a null value, or no value at all.None is not the same as 0,
False, or an empty string. None is a datatype of its own (NoneType) and only None can be
None.
x = None
if x:
print("Do you think None is True")
else:
print("None is not True...")
1.12.9 SETS
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate
elements. Python’s set class represents the mathematical notion of a set.
>>> s=set([1,2,3,2,3,4,'x',True,2.4])
>>> s
{1, 2, 3, 4, 'x', 2.4}
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,
Example: Output:
counter = 100 # An integer counter = 100 # An integer
assignment assignment
miles = 1000.0 # A floating point miles = 1000.0 # A floating point
name = "John" # A string name = "John" # A string
print(counter) print(counter)
print(miles) print(miles)
print(name) print(name)
a=b=c=1
Here, an integer object is created with the value 1, and all 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 variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
1.13.3: OBJECTS
Each identifier is implicitly associated with the memory address of the object to which it
refers. A Python identifier may be assigned to a special object named None.
Python is a dynamically typed language, as there is no advance declaration associating an
identifier with a particular data type. An identifier can be associated with any type of object,
and it can later be reassigned to another object of the same (or different) type. Although an
identifier has no declared type, the object to which it refers has a definite type. In our first
example, the characters 98.6 are recognized as a floating-point literal, and thus the identifier
Temperature is associated with an instance of the float class having that value.
A programmer can establish analias by assigning a second identifier to an existing object. if
one of the names is reassigned to a new value usinga subsequent assignment statement, that
does not affect the aliased object, rather it breaks the alias.
>>> my_value = 98.6 #state - 1
State – 1 state - 2
state - 3
>>> id(10)
1733846336
>>> b=a
>>> id(b)
1733846336
>>> c=10
>>> id(c)
1733846336
type() : type() method returns class type of the argument(object) passed as parameter.
type() function is mostly used for debugging purposes.
>= If the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means 1100
Complement bits. 0011 in 2's complement
form due to a signed binary
number.
<< Binary Left The left operands value is moved left by a << 2 = 240 (means 1111
Shift the number of bits specified by the right 0000)
operand.
>> Binary Right The left operands value is moved right a >> 2 = 15 (means 0000
Shift by the number of bits specified by the 1111)
right operand.
1.15.5 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 Logical If both the operands are true then condition (a and b) is true.
AND becomes true.If operand 1 is false, and will not >>> 5 and 6
check the operand 2 6
>>> 0 and 6
0
>>> True and True
True
>>> True and False
False
>>> 'a' and 'b'
'b'
or Logical OR If any of the two operands are non-zero then (a or b) is true.
condition becomes true.If first operand is true, or >>> 5 or 6
will not check operand - 2 5
>>> 0 or 6
6
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
>>> not 5
False
>>> not True
False
>>> not False
True
>>> not 0
True
NOTE: IN PYTHON SHELL, NON ZERO VALUE IS TRUE AND ZERO VALUE IS FALSE
1.15.6 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 −
list1 = [] OUTPUT:
list2 = []
list3=list1 True
if (list1 == list2):
print("True") False
else:
print("False") True
if (list1 is list2):
print("True")
else:
print("False")
if (list1 is list3):
print("True")
else:
print("False")
Syntax: Example:
if condition: >>> x=10
# Statements to execute if >>> if x<40:
# condition is true print("Fail")
#observe indentation after if
#Outside if block
Fail #output
Usually, the if conditions have a statement block. In any case, the programmer feels to do
nothing when the condition is true, the statement block can be skipped by just typing pass
statement as shown below –
>>> if x<0:
pass #do nothing when x is negative
A second form of decision making statement is alternative execution. Here, when the
condition is true, one set of statements will be executed and when the condition is false,
another set of statements will be executed. The syntax and flowchart are as given below –
As the condition will be either true or false, only one among Statement block-1 and
Statement block-2 will be get executed. These two alternatives are known as branches.
Syntax: Example:
if (condition): x=int(input("Enter x:"))
# Executes this block - 1 if if x%2==0:
# condition is true print("x is even")
else:
else:
print("x is odd")
# Executes this block - 2if
Sample output:
# condition is false Enter x: 13
#outside if - else x is odd
Some of the programs require more than one possibility to be checked for executing a set of
statements. That means, we may have more than one branch. This is solved with the
help of chained conditionals. The syntax and flowchart is given below –
The conditions are checked one by one sequentially. If any condition is satisfied, the
respective statement block will be executed and further conditions are not checked. Note
that, the last else block is not necessary always.
if (condition): Example:
statement marks=float(input("Enter marks:"))
elif (condition): if marks >= 80:
statement . . print("First Class with Distinction")
else: elif marks >= 60 and marks < 80:
statementis false print("First Class")
#outside elif ladder elif marks >= 50 and marks < 60:
print("Second Class")
elif marks >= 35 and marks < 50:
Sample Output: print("Third Class")
Enter marks: 78 else:
First Class print("Fail")
NOTE: Nested conditionals make the code difficult to read, even though there are proper
indentations. Hence, it is advised to use logical operators like and to simplify the nested
conditionals. For example, the outer and inner conditions in Ex1 above can be joined as -
#do something
1.17 ITERATION
Iteration is a processing repeating some task. In a real time programming, we require a set of
statements to be repeated certain number of times and/or till a condition is met. Every
programming language provides certain constructs to achieve the repetition of tasks. In this
section, we will discuss various such looping structures.
Example: output :
n=1 1
while n<=5: 2
print(n) #observe indentation 3
n=n+1 4
print("over") 5
over
In the above example, a variable n is initialized to 1. Then the condition n<=5 is being
checked. As the condition is true, the block of code containing print statement (print(n)) and
increment statement (n=n+1) are executed. After these two lines, condition is checked again.
The procedure continues till condition becomes false, that is when n becomes 6. Now,
the while-loop is terminated and next statement after the loop will be executed. Thus, in this
example, the loop is iterated for 5 times.
Note that, a variable n is initialized before starting the loop and it is incremented inside
the loop. Such a variable that changes its value for every iteration and controls the total
execution of the loop is called as iteration variable or counter variable. If the count
variable is not updated properly within the loop, then the loop may not terminate and keeps
executing infinitely.
A loop may execute infinite number of times when the condition is never going to become
false. For example,
n=1
while True:
print(n)
n=n+1
Here, the condition specified for the loop is the constant True, which will never get
terminated. Sometimes, the condition is given such a way that it will never become false and
hence by restricting the program control to go out of the loop. This situation may
happen either due to wrong condition or due to not updating the counter variable.
In some situations, we deliberately want to come out of the loop even before the
normal termination of the loop. For this purpose break statement is used. The following
example depicts the usage of break. Here, the values are taken from keyboard until a negative
number is entered. Once the input is found to be negative, the loop terminates.
Sample output:
while True: Enter a number:23
x=int(input("Enter a number:")) You have entered 23
if x>= 0: Enter a number:12
print("You have entered ",x) You have entered 12
else: Enter a number:45
print("You have entered a negative number!!") You have entered 45
break #terminates the loop Enter a number:0
You have entered 0
Enter a number:-2
You have entered a negative number!!
In the above example, we have used the constant True as condition for while-loop, which will
never become false. So, there was a possibility of infinite loop. This has been avoided by using
break statement with a condition. The condition is kept inside the loop such a way that, if
the user input is a negative number, the loop terminates. This indicates that, the loop may
terminate with just one iteration (if user gives negative number for the very first time) or
it may take thousands of iteration (if user keeps on giving only positive numbers as input).
Hence, the number of iterations here is unpredictable. But, we are making sure that it will not
be an infinite-loop, instead, the user has control on the loop.
Sometimes, programmer would like to move to next iteration by skipping few statements in
the loop, based on some condition. For this purpose continue statement is used. For
example, we would like to find the sum of 5 even numbers taken as input from the
keyboard. The logic is -
Read a number from the keyboard
If that number is odd, without doing anything else, just move to next iteration for
reading another number
If the number is even, add it to sum and increment the accumulator variable.
When accumulator crosses 5, stop the program
The program for the above task can be written as –
The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop. When we
know total number of times the set of statements to be executed, for loop will be used.
This is called as a definite loop. The for-loop iterates over a set of numbers, a set of words, lines
in a file etc. The syntax of for-loop would be –
Syntax:
for variable in sequence / list:
Statement – 1
Statement – 2
Statement – n
else:
Else block statements
Outside for and else
Here, for and in are keywords list/sequence is a set of elements on which the loop is
iterated. That is, the loop will be executed till there is an element in list/sequence statements
constitutes body of the loop
Ex: In the below given example, a list names containing three strings has been created. Then
the counter variable x in the for-loop iterates over this list. The variable x takes the
elements in names one by one and the body of the loop is executed.
Example: output :
names=["Ram", "Shyam", "Bheem"] Ram
for x in names: Shyam
print(x) Bheem
The for loop can be used to print (or extract) all the characters in a string as shown below –
When we have a fixed set of numbers to iterate in a for loop, we can use a function
range(). The function range() takes the following format –
The start and end indicates starting and ending values in the sequence, where end is excluded
in the sequence (That is, sequence is up to end-1). The default value of start is 0. The
argument steps indicates the increment/decrement in the values of sequence with the
default value as 1. Hence, the argument steps is optional. Let us consider few examples on
usage of range() function.
Here, the variable count is initialized before the loop. Though the counter variable i is not being
used inside the body of the loop, it controls the number of iterations. The variable
count is incremented in every iteration, and at the end of the loop the total number of
elements in the list is stored in it.
One more loop similar to the above is finding the sum of elements in the list –
total = 0
for x in [4, -2, 41, 34, 25]:
total = total + x
print(“Total:”, total)
Example: Output:
big = None Before Loop: None
print('Before Loop:', big) Iteration Variable: 12 Big: 12
for x in [12, 0, 21,-3]: Iteration Variable: 0 Big: 12
Iteration Variable: 21 Big: 21
if big is None or x > big :
Iteration Variable: -3 Big: 21
big = x
Biggest: 21
print('IterationVariable:', x, 'Big:', big)
print('Biggest:', big)
Here, we initialize the variable big to None. It is a special constant indicating empty.
Hence, we cannot use relational operator == while comparing it with big. Instead, the is
operator must be used. In every iteration, the counter variable x is compared with previous
value of big. If x > big, then x is assigned to big. Similarly, one can have a loop for finding
smallest of elements in the list as given below –
1.18 STRINGS
A string is a sequence of characters, enclosed either within a pair of single quotes or
double quotes. Each character of a string corresponds to an index number, starting with
zero as shown below –
S= “Hello World”
The characters of a string can be accessed using index enclosed within square brackets.
For example,
>>> word1="Hello"
>>> word2='hi'
>>> x=word1[1] #2nd character of word1 is extracted
>>> print(x)
e
>>> y=word2[0] #1st character of word1 is extracted
>>> print(y)
h
Python supports negative indexing of string starting from the end of the string as shown
below – S= “Hello World”
The characters can be extracted using negative index also. For example,
>>> var=“Hello”
>>> print(var[-1])
o
>>> print(var[-4])
e
Whenever the string is too big to remember last positive index, one can use negative index to
extract characters at the end of string.
Getting Length of a String using len()
The len() function can be used to get length of a string.
>>> var="Hello"
>>> ln=len(var)
>>> print(ln)
5
The index for string varies from 0 to length-1. Trying to use the index value beyond this range
generates error.
>>> var="Hello"
>>> ln=len(var)
>>> ch=var[ln]
IndexError: string index out of range
Strings are Immutable
The objects of string class are immutable. That is, once the strings are created (or
initialized), they cannot be modified. No character in the string can be
edited/deleted/added. Instead, one can create a new string using an existing string by
imposing any modification required.
Try to attempt following assignment –
>>> st= “Hello World”
>>> st[3]='t'
Example: Output:
num=int(input("Enter a Number:")) Enter a Number:24
print(type(num)) <class 'int'>
string=input("Enter a string:") Enter a string:hello
print(type(string)) <class 'str'>
logic=bool(input("Enter a boolean value:")) Enter a boolean value:True
print(type(logic)) <class 'bool'>
1.19.2:OUTPUT FORMATTING
The % operator can also be used for string formatting. It interprets the left argument much like
a printf()-style format string to be applied to the right argument. In Python, there is no printf()
function but the functionality of the ancient printf is contained in Python. To this purpose, the
modulo operator % is overloaded by the string class to perform string formatting. Therefore, it
is often called string modulo (or sometimes even called modulus) operator.
String modulo operator ( % ) is still available in Python(3.x) and user is using it widely.
Example:
print("values : % 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:
values : 1, Portal : 5.33
Total students : 240, Boys : 120
031
3.561E+02
Valie is : %s hello world
>>>
1.20 PROGRAMS ON VARIOUS TOPICS OF MODULE I
1. Program to Illustrate while and else statement
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
3. Program to read only positive integers and if negative number is read, should stop
reading input
while True:
num=int(input("Enter a number"))
if num>=0:
print("You have entered ",num)
else:
print("You have entered Negative Number!! STOP")
break
11.Program to find the biggest number in a given list. Numbers to be read from user by using
only one input function
x=input()
y=x.split()
big=None
for i in y:
if big is None or int(i)>big:
big=int(i)
print("Current Big = ",big)
print("Biggest = ",big)
12.Program to search for a keyword in a list of words. Words and keywords to be read from
user
print("Enter 'n' words seperated by white space !!!")
x=input()
print("Enter Key word to be searched")
keyword=input()
words=x.split()
flag=False
for i in words:
if i==keyword:
flag=True
if flag:
print("Key Found")
else:
print("Key Not Found")
13.Program to check a given number if positive or negative
x=int(input())
if x<0:
print(x,"is Negative")
elif x>0:
print(x,"is Positive")
else:
print(x,"is ZERO")
14. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn
print("Enter a Digit")
n=input()
term1=n
term2=n*2
term3=n*3
print(int(term1)+int(term2)+int(term3))
15.Program to read gender and age from user and check whether eligible to marry or not
print("Enter Gender in UPPERCASE only")
gender=input()
print("Enter age (1 - 120)")
age=int(input())
if gender=="MALE":
if age>=21:
print("ELIGIBLE to MARRY")
else:
print("NOT ELIGIBLE to MARRY")
elif gender=="FEMALE":
if age>=18:
print("ELIGIBLE to MARRY")
else:
print("NOT ELIGIBLE to MARRY")
else:
print("INVALID INPUT")
18. Write a Python program which iterates the integers from 1 to 50. For multiples of three
print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers
which are multiples of both three and five print "FizzBuzz".
for i in range(1,51):
if i%3==0 and i%5==0:
print("FIZZBUZZ")
elif i%3==0:
print("FIZZ")
elif i%5==0:
print("BUZZ")
else:
print(i)
20.Program to display the calendar of a month in a year. Year and month to be read from
user
import calendar
print("Enter Year :")
year=int(input())
print("Enter Month")
month=int(input())
print(calendar.month(year,month))
36.Deveop a Python Program to print the following pattern.The maximum star for a row to
be read from the user
*
**
***
****
*****
****
***
**
*
print("Program to print start pattern: \n");
rows = input("Enter max star to be display on single line")
rows = int (rows)
for i in range (0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")
for i in range (rows, 0, -1):
for j in range(0, i -1):
print("*", end=' ')
print("\r")
37. Develop a python program to check whether a given expression is valid parenthesized
expression or not
exp=input("Enter a paranthesized expression:")
count = 0
for i in exp:
if i == "(":
count += 1
elif i== ")":
count -= 1
else: pass
if count==0:
print(exp," is a valid expression")
else:
print(exp," is a invalid expression")
38.Develop a python program to print nth Fibonacci number
n=int(input("Enter n:"))
a=0
b=1
res=None
if n < 0:
print("Incorrect input")
elif n == 0:
res=a
elif n == 1:
res=b
Department of ISE,NHCE | Mr.Gangadhar Immadi 48
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS
else:
for i in range(2,n):
c=a+b
a=b
b=c
res=b
print(n," th fibonacci number = ",res)
42. Write a python program computes roots of a quadratic equation when coefficients a, b
and c are known.
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
43. Python program to check if the input year is a leap year or not
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
44. Python program to find the factorial of a number provided by the user.
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
45. Python Program to Take in the Marks of 5 Subjects and Display the Grade
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
46. Python Program to Read a Number n And Print the Series “1+2+…..+n= “
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
48. Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))
print()
49. The program takes in a date and checks if it a valid date and prints the incremented date
if it is.
Details:
1. Take in the date of the form: dd/mm/yyyy.
2. Split the date and store the day, month and year in separate variables.
3. Use various if-statements to check if the day, month and year are valid.
4. Increment the date if the date is valid and print it
5. Exit.
50. Python Program to Print the Pascal’s triangle for n number of rows given by the user
Details:
1. Take in the number of rows the triangle should have and store it in a separate variable.
2. Using a for loop which ranges from 0 to n-1, append the sub-lists into the list.
3. Then append 1 into the sub-lists.
4. Then use a for loop to determine the value of the number inside the triangle.
5. Print the Pascal’s triangle according to the format.
6. Exit.
Note : User must enter the number of rows that the Pascal’s triangle should have.
if(n!=0):
a[i].append(1)
for i in range(n):
print(" "*(n-i),end=" ",sep=" ")
for j in range(0,i+1):
print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
print()
sum1=0
num=int(input("Enter a number:"))
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print("The number is a strong number")
else:
print("The number is not a strong number")
53. Python Program to Compute a Polynomial Equation given that the Coefficients of the
Polynomial are stored in a List
import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
a=int(input("Enter coefficient:"))
lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
while(j>0):
sum1=sum1+(lst[i]*math.pow(x,j))
break
j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)
54. Python Program to Find the Area of a Triangle Given All Three Sides
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
55. Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + ….. + 1/N
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
56. Python Program to Find the Sum of the Series: 1 + x^2/2 + x^3/3 + … x^n/n
n=int(input("Enter the number of terms:"))
x=int(input("Enter the value of x:"))
sum1=1
for i in range(2,n+1):
sum1=sum1+((x**i)/i)
print("The sum of series is",round(sum1,2))
57. Python Program to Compute the Value of Euler’s Number e. Use the Formula: e = 1 + 1/1!
+ 1/2! + …… 1/n!
import math
n=int(input("Enter the number of terms: "))
sum1=1
for i in range(1,n+1):
sum1=sum1+(1/math.factorial(i))
print("The sum of series is",round(sum1,2))
print(random.randint(min, max))
roll_again = input("Roll the dices again?")