0% found this document useful (0 votes)
160 views

Ise36 - Modul1 - I PDF

Uploaded by

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

Ise36 - Modul1 - I PDF

Uploaded by

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

MODULE I:

FUNDAMENTALS

PYTHON PTOGRAMMING – 19ISE36

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.

1.2 PYTHON FEATURES:


Python's features include −

 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

Department of ISE,NHCE | Mr.Gangadhar Immadi 2


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.3 APPLICATIONS OF PYTHON


• Python has also been used in Artificial intelligence - Python has a standard library in
development, and a few for AI. It has an intuitive syntax, basic control flow, and data
structures. It also supports interpretive run-time, without standard compiler languages.
This makes Python especially useful for prototyping algorithms for AI.
• Python is often used for natural language processing tasks - Scikit-learn is a free
software machine learning library for Python programming language. Scikit-learn is
largely written in Python, with some core algorithms written in Cython to achieve
performance. Cython is a superset of the Python programming language, designed to
give C-like performance with code that is written mostly in Python.

Department of ISE,NHCE | Mr.Gangadhar Immadi 3


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

• 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

Department of ISE,NHCE | Mr.Gangadhar Immadi 4


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.5 PYTHON ENVIRONMENT SETUP


Open a terminal window and type "python" to find out if it is already installed and which
version is installed.

1.5.1 Installing Python


Here is a quick overview of installing Python on various platforms Before getting into
details of the programming language Python, it is better to learn how to install the software.
Python is freely downloadable from the internet. There are multiple IDEs (Integrated
Development Environment) available for working with Python. Some of them are
PyCharm, LiClipse, IDLE etc. When you install Python, the IDLE editor will be available
automatically. Apart from all these editors, Python program can be run on command
prompt also. One has to install suitable IDE depending on their need and the

Department of ISE,NHCE | Mr.Gangadhar Immadi 5


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 6


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.5.2 Unix and Linux Installation


Here are the simple steps to install Python on Unix/Linux machine.
 Open a Web browser and go to https://www.python.org/downloads/.
 Follow the link to download zipped source code available for Unix/Linux.
 Download and extract files.
 Editing the Modules/Setup file if you want to customize some options.
 run ./configure script
 make
 make install

This installs Python at standard location /usr/local/bin and its libraries


at /usr/local/lib/pythonXX where XX is the version of Python.
1.5.3 Windows Installation
Here are the steps to install Python on Windows machine.

 Open a Web browser and go to https://www.python.org/downloads/.

 Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to
install.

Department of ISE,NHCE | Mr.Gangadhar Immadi 7


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

 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.

1.5.4 SETTING UP PATH


Programs and other executable files can be in many directories, so operating systems provide
a search path that lists the directories that the OS searches for executables.

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 –

Step 1 : Copy the below link


C:\Users\GANGADHAR\AppData\Local\Programs\Python\Python37-32\Scripts
Step 2:Right click on my computer
Step3: Go to Properties  Advanced system setting  Environment variables
Step 4: create a new system variable  Give name as path and value as link shown in step 1
and put semicolon(;) at the end, click on ok at all windows

1.5.5 STARTING AND STOPPING FROM COMMAND PROMPT:

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

From windows command prompt do the following activity:

Department of ISE,NHCE | Mr.Gangadhar Immadi 8


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.6 USING IDLE IDE


Once you install python 3.x version a default IDE called IDLE will be installed,start IDLE and use
it from python shell.

1.6.1 USE OF HELP – IN PYTHON SHELL

>>> 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".

Department of ISE,NHCE | Mr.Gangadhar Immadi 9


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 10


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 11


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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 –

Department of ISE,NHCE | Mr.Gangadhar Immadi 12


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 13


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.11 FIRST PYTHON PROGRAM


Let us execute programs in different modes of programming.

1.11.1Interactive Mode Programming


Invoking the interpreter without passing a script file as a parameter brings up the following
prompt −

Type the following text at the Python prompt and press the Enter −

>>> print("Hello, Python!")

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!

1.11.2 Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and continues
until the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the
following source code in a test.py file −

print("Hello, Python!")
We assume that you have Python interpreter set in PATH variable. Now, try to run this
program as follows −

Department of ISE,NHCE | Mr.Gangadhar Immadi 14


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

$ python test.py
This produces the following result −
Hello, Python!

1.12 DATA TYPES


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 15


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

You can delete a single object or multiple objects by using the del statement. For example −

del var

Python supports four different numerical types −


 int (signed integers)

 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 −

Int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

 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 −

str = 'Hello World!'


print(str) # Prints complete string
print(str[0]) # Prints first character of the string
Department of ISE,NHCE | Mr.Gangadhar Immadi 16
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

print(str[2:5]) # Prints characters starting from 3rd to 5th


print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string

This will produce the following result −


Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

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 −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist) # Prints concatenated lists

This produce the following result −


['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

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 −

Department of ISE,NHCE | Mr.Gangadhar Immadi 17


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list
print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(tuple[2:]) # Prints elements starting from 3rd element
print(tinytuple * 2) # Prints list two times
print(tuple + tinytuple) # Prints concatenated lists

This produce the following result −


('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 18


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

This produce the following result −


This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order"; they are simply unordered.

1.12.6 BOOLEAN TYPE:


Boolean values are the two constant objects False and True. They are used to represent truth
values (other values can also be considered false or true). In numeric contexts (for example,
when used as the argument to an arithmetic operator), they behave like the integers 0 and 1,
respectively. The built-in function bool() can be used to cast any value to a Boolean,if the value
can be interpreted as a truth value.
>>> a=True
>>> b=False
>>> True
True
>>> False
False

1.12.7 COMPLEX TYPE:

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.

 imag - imaginary part. If imag is omitted, it default to 0.


If the first parameter passed to this method is a string, it will be interpreted as a complex
number. In this case, second parameter shouldn't be passed.As suggested by the name, the
complex() method returns a complex number.If the string passed to this method is not a valid complex
number, ValueError exception is raised.
Note: The string passed to the complex() should be in the form real+imagj or real+imagJ

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)

Department of ISE,NHCE | Mr.Gangadhar Immadi 19


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

Create complex Number Without Using complex()

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))

1.12.8 NONE TYPE

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}

1.13 VARIABLES/IDENTIFIERS , OBJECTS AND ASSIGNMENTS


1.13.1: RULES AND EXAMPLES FOR VARIABLES / IDENTIFIERS
 Variables names must start with a letter or an underscore, such as:
o _underscore
o underscore_
 The remainder of your variable name may consist of letters, numbers and underscores.
o password1
o n00b
o un_der_scores
 Names are case sensitive.
Department of ISE,NHCE | Mr.Gangadhar Immadi 20
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

o case_sensitive, CASE_SENSITIVE, and Case_Sensitive are each a different


variable.
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example,

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)

1.13.2 MULTIPLE ASSIGNMENT


Python allows you to assign a single value to several variables simultaneously. For example −

a=b=c=1
Here, an integer object is created with the value 1, and all 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

Department of ISE,NHCE | Mr.Gangadhar Immadi 21


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

>>> second_value = my_value #state - 2


>>> second_value
98.6
my_value=98.6+5 #state - 3

State – 1 state - 2

state - 3

1.14 SPECIAL FUNCTIONS


id() : is an inbuilt function in Python.
id(object)
As we can see the function accepts a single parameter and is used to return the identity of an
object. This identity has to be unique and constant for this object during the lifetime.Two
objects with non-overlapping lifetimes may have the same id() value. If we relate this to C,
then they are actually the memory address, here in Python it is the unique id. This function is
generally used internally in Python.

>>> 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.

>>> num=10 >>> logic=True >>> lst=[]


>>> type(logic) >>> type(lst)
>>> type(num)
<class 'bool'> <class 'list'>
<class 'int'>
>>> string='hello' >>> cmpl=2+23j
>>> real=2.3 >>> type(string)
>>> type(real) >>> type(cmpl)
<class 'str'>
<class 'float'> >>> no=None <class 'complex'>
>>> type(no)
<class 'NoneType'>

Department of ISE,NHCE | Mr.Gangadhar Immadi 22


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.15 OPERATORS AND EXPRESSIONS


Python operator is a symbol that performs an operation on one or more operands. An
operand is a variable or a value on which we perform the operation.
Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

1.15.1 ARITHMETIC OPERATORS


Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
+ Adds values on either side of the operator. a + b = 30
- Subtracts right hand operand from left hand operand. a – b = -10
* Multiplies values on either side of the operator a * b = 200
/ True Division: Divides left hand operand by right hand operand b/a=2
Divides left hand operand by right hand operand and returns b%a=0
%
remainder
Performs exponential (power) calculation on operators a**b =10 to the
**
power 20
Floor Division - The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are 9.0//2.0 = 4.0, -
// removed. But if one of the operands is negative, the result is 11//3 = -4, -
floored, i.e., rounded away from zero (towards negative
infinity)
1.15.2 RELATIONAL (COMPARISON ) OPERATORS
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then –


Operator Description Example
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
!= If values of two operands are not equal, then condition (a != b) is true.
becomes true.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
Department of ISE,NHCE | Mr.Gangadhar Immadi 23
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

>= 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.

1.15.3 ASSIGNMENT OPERATORS


Assume variable a holds 10 and variable b holds 20 –
Operator Description Example
= Assigns values from right side operands to left side c = a + b assigns value of a + b
operand into c
+= Add AND It adds right operand to the left operand and assign c += a is equivalent to c = c + a
the result to left operand
-= Subtract AND It subtracts right operand from the left operand and c -= a is equivalent to c = c - a
assign the result to left operand
*= Multiply AND It multiplies right operand with the left operand and c *= a is equivalent to c = c * a
assign the result to left operand
/= Divide AND It divides left operand with the right operand and c /= a is equivalent to c = c / ac
assign the result to left operand /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the c %= a is equivalent to c = c %
result to left operand a
**= Exponent AND Performs exponential (power) calculation on c **= a is equivalent to c = c **
operators and assign value to the left operand a
//= Floor Division It performs floor division on operators and assign c //= a is equivalent to c = c //
value to the left operand a
1.15.4 BITWISE OPERATORS
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
Operator Description Example
& Binary AND Operator copies a bit to the result if it (a & b) (means 0000 1100)
exists in both operands
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means 0011
operand. 1101)
^ Binary XOR It copies the bit if it is set in one operand (a ^ b) = 49 (means 0011
but not both. 0001)

Department of ISE,NHCE | Mr.Gangadhar Immadi 24


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

~ 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 −

Department of ISE,NHCE | Mr.Gangadhar Immadi 25


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

Operator Description Example


in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x is a
the specified sequence and false member of sequence y.
otherwise. >>> y=[1,2,3,4,5]
>>> x=3
>>> x in
>>> x in y
True
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1
variable in the specified sequence and if x is not a member of sequence y.
false otherwise. >>> y=[1,2,3,4,5]
>>> x=3
>>> x not in y
False
1.15.7 IDENTITY OPERATORS
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
Operator Description Example
is Evaluates to true if the variables on either x is y, here is results in 1 if id(x)
side of the operator point to the same equals id(y).
object and false otherwise.
is not Evaluates to false if the variables on either x is not y, here is not results in
side of the operator point to the same 1 if id(x) is not equal to id(y).
object and true otherwise.
Difference between == and is operator in Python: The == operator compares the values of both
the operands and checks for value equality. Whereas is operator checks whether both the
operands refer to the same object or not.

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")

Department of ISE,NHCE | Mr.Gangadhar Immadi 26


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.15.8 OPERATORS PRECEDENCE


The following table lists all operators from highest precedence to lowest.
Sr.No. Operator & Description
1 ** Exponentiation (raise to the power)
2 ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 + - Addition and subtraction
5 >> << Right and left bitwise shift
6 & Bitwise 'AND'
7 ^ | Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators
9 <> == != Equality operators
10 = %= /= //= -= += *= **= Assignment operators
11 is, is not Identity operators
12 in ,not in Membership operators
13 not ,or ,and Logical operators

1.5.9 ESCAPE SEQUENCES


Escape Description Example Output
Sequence
\\ Prints Backslash print ("\\") \
\` Prints single-quote print ("\'") '
\" Pirnts double quote Print( "\"") "
ASCII bell makes ringing the bell alert print ("\a") N/A
\a
sounds ( eg. xterm )
ASCII backspace ( BS ) removes previous Print) "ab" + "\b" + "c") ac
\b
character
ASCII formfeed ( FF ) Print( "hello\fworld") hello
\f
world
ASCII linefeed ( LF ) Print( "hello\nworld") hello
\n
world
Prints a character from the Unicode print u"\N{DAGGER}" †
\N{name}
database
ASCII carriage return (CR). Moves all Print( "123456\rXX_XX") XX_XX6
characters after ( CR ) the the beginning
\r
of the line while overriding same number
of characters moved.
\t ASCII horizontal tab (TAB). Prints TAB Print( "\t* hello") * hello
\t ASCII vertical tab (VT). N/A N/A
\uxxxx Prints 16-bit hex value Unicode character Print( u"\u041b") Л
\Uxxxxxxxx Prints 32-bit hex value Unicode character print (u"\U000001a9") Ʃ
\ooo Prints character based on its octal value Print( "\043") #
\xhh Prints character based on its hex value print ("\x23") #
LinuxConfig.org

Department of ISE,NHCE | Mr.Gangadhar Immadi 27


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.16 DECISSION MAKING STATEMENTS


Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
1.16.1 IF STATEMENT
The basic level of conditional execution can be achieved in Python by using if statement.
The syntax and flowcharts are as below – Block structure for python indentation

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

1.16.2 IF ELSE STATEMENT

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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 28


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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

1.16.3 ELIF LADDER

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")

Department of ISE,NHCE | Mr.Gangadhar Immadi 29


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.16.4 NESTED CONDITIONALS


The conditional statements can be nested. That is, one set of conditional statements can
be nested inside the other. It can be done in multiple ways depending on programmer’s
requirements. Examples are given below –
Ex2. gender=input("Enter gender:")
Ex1. marks=float(input("Enter age=int(input("Enter age:"))
marks:")) if gender == "M" :
if age >= 21:
if marks>=60:
print("Boy, Eligible for Marriage")
if marks<70: else:
print("First Class") print("Boy, Not Eligible for Marriage")
else: elif gender == "F":
print("Distinction") if age >= 18:
Sample Output: print("Girl, Eligible for Marriage")
else:
Enter marks:68
print("Girl, Not Eligible for Marriage")
First Class Sample Output:
Enter gender: F
Enter age: 17
Girl, Not Eligible for Marriage

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 -

if marks>=60 and marks<70:

#do something

Department of ISE,NHCE | Mr.Gangadhar Immadi 30


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.17.1 THE WHILE STATEMENT

The while loop has the syntax as below –


Syntax: Alternative Syntax:
while condition: while condition:
Statement – 1 Statement – 1
Statement – 2 Statement – 2
Statement – 3 Statement – n
Statement – n else:
#outside while #else block statement –
executes when condition
becomes false
Here, while is a keyword. The condition is evaluated first. Till its value remains true, the
statement_1 to statement_n will be executed. When the condition becomes false, the loop
is terminated and statements after the loop will be executed. Consider an example –

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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 31


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

1.17.2 INFINITE LOOPS, BREAK AND CONTINUE

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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 32


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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 –

Example: Sample Output:


sum=0 Enter a number:13
count=0 Enter a number:12
while True: Enter a number:4
x=int(input("Enter a number:")) Enter a number:5
if x%2 !=0: Enter a number:-3
continue Enter a number:8
else: Enter a number:7
sum+=x Enter a number:16
count+=1 Enter a number:6
if count==5: Sum= 46
break
print("Sum= ", sum)

Department of ISE,NHCE | Mr.Gangadhar Immadi 33


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

1.17.3 DEFINITE LOOPS USING FOR

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 –

for i in "Hello": Output:


print(i, end=’\t’) H e l l o

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 –

range(start, end, steps)


Department of ISE,NHCE | Mr.Gangadhar Immadi 34
19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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.

for i in range(5): for i in range(5,0,-1): for i in range(0,10,2):


print(i, end= ‘\t’) print(i, end= ‘\t’) print(i, end= ‘\t’)
Output: Output: Output:
0 1 2 3 4 5 4 3 2 1 0 2 4 6 8

for i in range(-5,-1,1): for i in range(-1,-5,-1): for i in range(-1,-10,-2):


print(i,end=" ") print(i,end=" ") print(i,end=" ")
Output: Output: output:
-5 -4 -3 -2 -1 -2 -3 -4 -1 -3 -5 -7 -9

1.17.4 LOOP PATTERNS


The while-loop and for-loop are usually used to go through a list of items or the contents of a
file and to check maximum or minimum data value. These loops are generally constructed
by the following procedure –
 Initializing one or more variables before the loop starts
 Performing some computation on each item in the loop body, possibly changing the
variables in the body of the loop
 Looking at the resulting variables when the loop completes
The construction of these loop patterns are demonstrated in the following examples.
Counting and Summing Loops: One can use the for loop for counting number of items in the
list as shown –
count = 0
for i in [4, -2, 41, 34, 25]:
count = count + 1
print(“Count:”, count)

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)

Department of ISE,NHCE | Mr.Gangadhar Immadi 35


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

Here, the variable total is called as accumulator because in every iteration, it


accumulates the sum of elements. In each iteration, this variable contains running total of
values so far.
NOTE: In practice, both of the counting and summing loops are not necessary, because
there are built-in functions len() and sum() for the same tasks respectively.
1.17.5 MAXIMUM AND MINIMUM LOOPS:
To find maximum element in the list, the following code can be used –

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 –

small = None Output:


print('Before Loop:', small) Before Loop: None
for x in [12, 0, 21,-3]: Iteration Variable: 12 Small: 12
if small is None or x < small : Iteration Variable: 0 Small: 0
small = x Iteration Variable: 21 Small: 0
print('Iteration Variable:', x, 'Small:', small) Iteration Variable: -3 Small: -3
print('Smallest:', small) Smallest: -3

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,

Department of ISE,NHCE | Mr.Gangadhar Immadi 36


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

>>> 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'

Department of ISE,NHCE | Mr.Gangadhar Immadi 37


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

TypeError: 'str' object does not support item assignment


Here, we are trying to change the 4th character (index 3 means, 4 th character as the
first index is 0) to t. The error message clearly states that an assignment of new item (a string)
is not possible on string object. So, to achieve our requirement, we can create a new string
using slices of existing string as below –
>>> st= “Hello World”
>>> st1= st[:3]+ 't' + st[4:]
>>> print(st1)
Helto World #l is replaced by t in new string st1
1.19:HANDLING INPUT AND OUTPUT FORMATTING
1.19.1: INPUT FUNCTION
A function is defined as a block of organized, reusable code used to perform a single, related
action. Python has many built-in functions; you can also create your own. Python has an input
function which lets you ask a user for some text input. You call this function to tell the program
to stop and wait for the user to key in the data. 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.
 When input() function executes program flow will be stopped until the user has given an
input.
 The text or message display on the output screen to ask a user to enter input value is
optional i.e. the prompt, will be printed on the screen is optional.
 Whatever you enter as input, input function convert it into a string. if you enter an
integer value still input() function convert it into a string. You need to explicitly convert
it into an integer in your code using typecasting.
NOTE : Always the data read from input() will be in string form

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 38


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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")

2. Program to print the version of the Python used


import sys
print(sys.version)
or
import platform
print(platform.python_version())

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

Department of ISE,NHCE | Mr.Gangadhar Immadi 39


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

4. Program to count the number of digits of a given number


number=int(input("Enter a Number"))
pnum=number
count=0
while number>0:
digit=number%10
count=count+1
number=number//10
print("Number of Digits of a Given Number ",pnum,"=",count)
5. Program to find sum of even digits in a given number
number=int(input("Enter a Number"))
pnum=number
esum=0
while number>0:
digit=number%10
if (digit%2)==0:
esum=esum+digit
number=number//10
print("Number of Even Digits of a Given Number ",pnum,"=",esum)

6. Program to find the sum of odd placed digits of a given number


number=int(input("Enter a Number"))
pnum=number
opsum=0
count=0
while number>0:
digit=number%10
count=count+1
if(count%2)!=0:
opsum=opsum+digit
number=number//10
print("Summ of Odd Placed Digits of a Given Number ",pnum,"=",opsum)

7.Program to check a given number is palindrome or not


number=int(input("Enter a Number"))
pnum=number
opsum=0
rev=0
while number>0:
digit=number%10
rev=rev*10+digit
number=number//10
if rev==pnum:
print(pnum," is Palindrome")
else:
print(pnum," is Not a Palindrome")

Department of ISE,NHCE | Mr.Gangadhar Immadi 40


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

8.Program to search for a value in a given list


lst=[45,23,67,87,-10,789]
key=78
if key in lst:
print("Key Present")
else:
print("Key not present")
9. Program to find the biggest number in a given list
#find biggest
lst=[23,87,-1,89,777,23572,678]
big=None
for x in lst:
if big is None or x>big:
big=x
print("Current value of big = ",big)
print("Biggest = ",big)

10.Program to check whether a given number is prime or not


x=24
check=True
for i in range(2,(x//2)):
if(x%i==0):
check=False
break
if check:
print("PRIME")
else:
print("NOT A PRIME")

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()

Department of ISE,NHCE | Mr.Gangadhar Immadi 41


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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")

16.Program to check the type of objects stored in the list


lst=[10,True,False,"HEllo",4.5]
for i in lst:
print(i,"---->",type(i))

Department of ISE,NHCE | Mr.Gangadhar Immadi 42


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

17.Program to generate first 10 fibonacci numbers


fib1=0
fib2=1
count=2
print(fib1)
print(fib2)
while(count<=9):
fib3=fib1+fib2
print(fib3)
fib1=fib2
fib2=fib3
count=count+1

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)

19. Program to print the following pattern


*
**
***
****
*****
for i in range(1,6):
for k in range(6,1,-1):
print(end=" ")
for j in range(1,i+1):
print("*",end=' ')
print()

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))

Department of ISE,NHCE | Mr.Gangadhar Immadi 43


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

21.Program to generate random numbers between 2 and 50


import random
print(random.randint(2,50))

22.Program to generate multiplication table from 1 – 10


for i in range(1,11):
for j in range(1,11):
print(i*j,end='\t')
print()
23.Program to print the character a ascii values stored in a list
lst=[97,98,99,100,65,66,67,68,91]
for i in lst:
print(chr(i),end=' ')
24.Program to simulate the password verification
passwords=["nhce","nhce123","ise7$","welcome","nhce@ise"]
print("Enter Password")
pw=input()
if pw in passwords:
print("Welcome")
else:
print("Acceess Denied")

25.Program to convert a number in decimal to binary without using library


print("Enter a number to be converted to Binary")
num=int(input())
bi=""
while num>0:
digit=num%2
bi=bi+str(digit)
num=num//2
for i in range(len(bi)-1,-1,-1):
print(bi[i],end=' ')
26.Program to convert temperature in degree celcius to farrenheat
celcius=int(input("Enter Temperature in Degree Celcius"))
FarrenHeat=(celcius*1.8)+32
print("Termperature in FarrenHeat = ",FarrenHeat)

Department of ISE,NHCE | Mr.Gangadhar Immadi 44


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

27.Program to check whether a given number is Armstrong number or not


n=input("Enter a Number")
nd=len(n)
num=int(n)
s=0
while num>0:
dig=num%10
s=s+dig**nd
num=num//10
if s==int(n):
print(n,"is ARMSTRONG NUMBER")
else:
print(n,"is NOT A ARMSTRONG NUMBER")

28.Develop a Python program to generate first ‘N’ prime numbers


n=int(input("Enter n:"))
count=0
isprime=True
for i in range(2,1000):
isprime=True
for j in range(2,(i//2+1)):
if i%j==0:
isprime=False
break
if isprime:
count=count+1
print("Prime Number - ",count," : ",i)
if count==n:
break
29. Develop a Python program to print the numbers between a range n1 and n2
n1=int(input("Enter start range:"))
n2=int(input("Enter End range:"))
isprime=True
for i in range(n1,n2+1):
isprime=True
for j in range(2,(i//2+1)):
if i%j==0:
isprime=False
break
if isprime:
print(i)

Department of ISE,NHCE | Mr.Gangadhar Immadi 45


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

30.Develop a python program to print the following pattern


*****
****
***
**
*
for i in range(5):
for j in range(5):
if i<=j:
print("*",end=' ')
print()
31. Develop a python program to print the following pattern
* * * * *
* *
* *
* *
* * * * *
for i in range(5):
for j in range(5):
if i in [1,2,3] and j in [1,2,3]:
print(" ",end=' ')
else:
print("*",end=' ')
print()
32.Deveop a Python Program to print the following pattern
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
for num in range(10):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n")

Department of ISE,NHCE | Mr.Gangadhar Immadi 46


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

33.Deveop a Python Program to print the following pattern


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

print("Second Number Pattern ")


lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=' ')
print("")

34.Deveop a Python Program to print the following pattern


1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
lastNumber = 6
for row in range(1, lastNumber):
for column in range(row, 0, -1):
print(column, end=' ')
print("")
35.Deveop a Python Program to print the following pattern
1
2 1
4 2 1
8 4 2 1
16 8 4 2 1
32 16 8 4 2 1
64 32 16 8 4 2 1
128 64 32 16 8 4 2 1
lastNumber = 9
for i in range(1, lastNumber):
for j in range(-1+i, -1, -1):
print(format(2**j, "4d"), end=' ')
print("")

Department of ISE,NHCE | Mr.Gangadhar Immadi 47


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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)

39.Develop a python program to check whether a given is fibonacce or not.Note: A number is


Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square
import math
n=int(input("Enter a Number : "))
check1 =5*n*n + 4
check2 =5*n*n - 4
v1=int(math.sqrt(check1))
v2=int(math.sqrt(check2))
t1=v1*v1
t2=v2*v2
if t1==check1 or t2==check2:
print(n," is a fibonacci number")
else:
print(n," is a NOT a fibonacci number")
40.Develop a Python program to print the following pattern.
A
BC
DEF
GHIJ
KLMNO
PQRSTU
print("Print Alphabets and Letters pattern in python ")
lastNumber = 6
asciiNumber = 65
for i in range(0, lastNumber):
for j in range(0, i+1):
character = chr(asciiNumber)
print(character, end=' ')
asciiNumber+=1
print(" ")
41.Write a Python program to find the square root of a number without using library
function
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Department of ISE,NHCE | Mr.Gangadhar Immadi 49


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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):

Department of ISE,NHCE | Mr.Gangadhar Immadi 50


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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()

47. Python Program to Print an Identity Matrix


n=int(input("Enter a number: "))
for i in range(0,n):
for j in range(0,n):
if(i==j):
print("1",sep=" ",end=" ")
else:
print("0",sep=" ",end=" ")
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.

Department of ISE,NHCE | Mr.Gangadhar Immadi 51


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

date=input("Enter the date: ")


dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
max1=29
else:
max1=28
if(mm<1 or mm>12):
print("Date is invalid.")
elif(dd<1 or dd>max1):
print("Date is invalid.")
elif(dd==max1 and mm!=12):
dd=1
mm=mm+1
print("The incremented date is: ",dd,mm,yy)
elif(dd==31 and mm==12):
dd=1
mm=1
yy=yy+1
print("The incremented date is: ",dd,mm,yy)
else:
dd=dd+1
print("The incremented date is: ",dd,mm,yy)

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.

n=int(input("Enter number of rows: "))


a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])

Department of ISE,NHCE | Mr.Gangadhar Immadi 52


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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()

51. Python Program to check a number is perfect or not


n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

52. Python Program to Check if a Number is a Strong Number


Details :
1.User must enter the number and store it in a variable.
2.A copy of the original number is made as the original value will get altered in the later course
of the program.
3.Using a while loop, each of the digits of the numbers is obtained.
4.Then the other while loop is used to find the factorial of the individual digits and store it in a
sum variable.
5.If the sum of the factorial of the digits in a number is equal to the original number, the
number is a strong number.
6.The final result is printed.

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")

Department of ISE,NHCE | Mr.Gangadhar Immadi 53


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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))

Department of ISE,NHCE | Mr.Gangadhar Immadi 54


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

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))

58. Python Program to Determine all Pythagorean Triplets in the Range


Details :
1.User must enter the upper limit and store it in a variable.
2.The while and for loop is used to find the value of the Pythagorean triplets using the formula.
3.If the value of a side is greater than the upper limit or if any of the side is 0, the loop is
broken out of.
4.Then the triplets are printed.

limit=int(input("Enter upper limit:"))


c=0
m=2
while(c<limit):
for n in range(1,m+1):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1

59.Develop a program in python to simulate rolling two dice game


import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are....")
print(random.randint(min, max))

Department of ISE,NHCE | Mr.Gangadhar Immadi 55


19ISE36 – PYTHON PROGRAMMING MODULE I: FUNDAMENTALS

print(random.randint(min, max))
roll_again = input("Roll the dices again?")

60. Develop a python program to simulate Guessing the Number game


import random
n = random.randint(1, 99)
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
print()
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it!")
break
print()

Department of ISE,NHCE | Mr.Gangadhar Immadi 56

You might also like